- Linux what is system map
- System.map
- What Are Symbols?
- What Is The Kernel Symbol Table?
- What Is The System.map File?
- What Is An Oops?
- What Does An Oops Have To Do With System.map?
- Where Should System.map Be Located?
- What else uses the System.map
- What Happens If I Don’t Have A Healthy System.map?
- How Do I Remedy The Above Situation?
- Исследуем процесс загрузки Linux
- Этап 3: Загрузчик 2 этапа операционной системы
- 3.3. Файл System.map
- 3.3.1. Что такое «Таблица символов ядра»?
- 3.3.2. Когда и кем используется таблица символов ядра?
- 3.3.3. Где находится таблица символов ядра?
- Linux what is system map
- ОПИСАНИЕ
- ВОЗВРАЩАЕМЫЕ ЗНАЧЕНИЯ
- ЗАМЕЧАНИЯ
- НАЙДЕННЫЕ ОШИБКИ
Linux what is system map
This section gives a «very brief» and «introduction» to some of the Linux Kernel System. If you have time you can give one reading.
The vmlinuz is the Linux kernel executable. This is located at /boot/vmlinuz. This can be a soft link to something like /boot/vmlinuz-2.4.18-19.8.0
The vmlinux is the uncompressed built kernel, vmlinuz is the compressed one, that has been made bootable. (Note both names vmlinux and vmlinuz look same except for last letter z). Generally, you don’t need to worry about vmlinux, it is just an intermediate step.
The kernel usually makes a bzImage, and stores it in arch/i386/boot, and it is up to the user to copy it to /boot and configure GRUB or LILO.
the .b files are «bootloader» files. they are part of the dance required to get a kernel into memory to begin with. You should NOT touch them.
The ‘message’ file contains the message your bootloader will display, prompting you to choose an OS. So DO NOT touch it.
The bzImage is the compressed kernel image created with command ‘make bzImage’ during kernel compile.
This is created by utils/modlist.
Everytime you compile and install the kernel image in /boot, you should also copy the corresponding config file to /boot area, for documentation and future reference. Do NOT touch or edit these files!!
System.map is a «phone directory» list of function in a particular build of a kernel. It is typically a symlink to the System.map of the currently running kernel. If you use the wrong (or no) System.map, debugging crashes is harder, but has no other effects. Without System.map, you may face minor annoyance messages.
Do NOT touch the System.map files.
How The Kernel Symbol Table Is Created ? System.map is produced by ‘nm vmlinux’ and irrelevant or uninteresting symbols are grepped out, When you compile the kernel, this file ‘System.map’ is created at /usr/src/linux/System.map. Something like below:
System.map
There seems to be a dearth of information about the System.map file. It’s really nothing mysterious, and in the scheme of things, it’s really not that important. But a lack of documentation makes it shady. It’s like an earlobe; we all have one, but nobody really knows why. This is a little web page I cooked up that explains the why.
Note, I’m not out to be 100% correct. For instance, it’s possible for a system to not have /proc filesystem support, but most systems do. I’m going to assume you «go with the flow» and have a fairly typical system.
Some of the stuff on oopses comes from Alessandro Rubini’s «Linux Device Drivers» which is where I learned most of what I know about kernel programming.
What Are Symbols?
In the context of programming, a symbol is the building block of a program: it is a variable name or a function name. It should be of no surprise that the kernel has symbols, just like the programs you write. The difference is, of course, that the kernel is a very complicated piece of coding and has many, many global symbols.
What Is The Kernel Symbol Table?
The kernel doesn’t use symbol names. It’s much happier knowing a variable or function name by the variable or function’s address. Rather than using size_t BytesRead, the kernel prefers to refer to this variable as (for example) c0343f20.
Humans, on the other hand, do not appreciate names like c0343f20. We prefer to use something like size_t BytesRead. Normally, this doesn’t present much of a problem. The kernel is mainly written in C, so the compiler/linker allows us to use symbol names when we code and allows the kernel to use addresses when it runs. Everyone is happy.
There are situations, however, where we need to know the address of a symbol (or the symbol for an address). This is done by a symbol table, and is very similar to how gdb can give you the function name from a address (or an address from a function name). A symbol table is a listing of all symbols along with their address. Here is an example of a symbol table:
You can see that the variable named dmi_broken is at the kernel address c03441a0.
What Is The System.map File?
There are 2 files that are used as a symbol table:
- /proc/ksyms
- System.map
There. You now know what the System.map file is.
Every time you compile a new kernel, the addresses of various symbol names are bound to change.
/proc/ksyms is a «proc file» and is created on the fly when a kernel boots up. Actually, it’s not really a file; it’s simply a representation of kernel data which is given the illusion of being a disk file. If you don’t believe me, try finding the filesize of /proc/ksyms. Therefore, it will always be correct for the kernel that is currently running..
However, System.map is an actual file on your filesystem. When you compile a new kernel, your old System.map has wrong symbol information. A new System.map is generated with each kernel compile and you need to replace the old copy with your new copy.
What Is An Oops?
What is the most common bug in your homebrewed programs? The segfault. Good ol’ signal 11.
What is the most common bug in the Linux kernel? The segfault. Except here, the notion of a segfault is much more complicated and can be, as you can imagine, much more serious. When the kernel dereferences an invalid pointer, it’s not called a segfault — it’s called an «oops». An oops indicates a kernel bug and should always be reported and fixed.
Note that an oops is not the same thing as a segfault. Your program cannot recover from a segfault. The kernel doesn’t necessarily have to be in an unstable state when an oops occurs. The Linux kernel is very robust; the oops may just kill the current process and leave the rest of the kernel in a good, solid state.
An oops is not a kernel panic. In a panic, the kernel cannot continue; the system grinds to a halt and must be restarted. An oops may cause a panic if a vital part of the system is destroyed. An oops in a device driver, for example, will almost never cause a panic.
When an oops occurs, the system will print out information that is relevent to debugging the problem, like the contents of all the CPU registers, and the location of page descriptor tables. In particular, the contents of the EIP (instruction pointer) is printed. Like this:
What Does An Oops Have To Do With System.map?
You can agree that the information given in EIP and Call Trace is not very informative. But more importantly, it’s really not informative to a kernel developer either. Since a symbol doesn’t have a fixed address, c010b860 can point anywhere.
To help us use this cryptic oops output, Linux uses a daemon called klogd, the kernel logging daemon. klogd intercepts kernel oopses and logs them with syslogd, changing some of the useless information like c010b860 with information that humans can use. In other words, klogd is a kernel message logger which can perform name-address resolution. Once klogd tranforms the kernel message, it uses whatever logger is in place to log system wide messages, usually syslogd.
To perform name-address resolution, klogd uses System.map. Now you know what an oops has to do with System.map.
Fine print: There are actually two types of address resolution are performed by klogd.
- Static translation, which uses the System.map file.
- Dynamic translation which is used with loadable modules, doesn’t use
System.map and is therefore not relevant to this discussion, but I’ll describe it briefly anyhow.
Klogd Dynamic Translation
Suppose you load a kernel module which generates an oops. An oops message is generated, and klogd intercepts it. It is found that the oops occured at d00cf810. Since this address belongs to a dynamically loaded module, it has no entry in the System.map file. klogd will search for it, find nothing, and conclude that a loadable module must have generated the oops. klogd then queries the kernel for symbols that were exported by loadable modules. Even if the module author didn’t export his symbols, at the very least, klogd will know what module generated the oops, which is better than knowing nothing about the oops at all.
There’s other software that uses System.map, and I’ll get into that shortly.
Where Should System.map Be Located?
System.map should be located wherever the software that uses it looks for it. That being said, let me talk about where klogd looks for it. Upon bootup, if klogd isn’t given the location of System.map as an argument, it will look for System.map in 3 places, in the following order:
- /boot/System.map
- /System.map
- /usr/src/linux/System.map
System.map also has versioning information, and klogd intelligently searches for the correct map file. For instance, suppose you’re running kernel 2.4.18 and the associated map file is /boot/System.map. You now compile a new kernel 2.5.1 in the tree /usr/src/linux. During the compiling process, the file /usr/src/linux/System.map is created. When you boot your new kernel, klogd will first look at /boot/System.map, determine it’s not the correct map file for the booting kernel, then look at /usr/src/linux/System.map, determine that it is the correct map file for the booting kernel and start reading the symbols.
A few nota bene’s:
- Somewhere during the 2.5.x series, the Linux kernel started to untar into linux-version, rather than just linux (show of hands — how many people have been waiting for this to happen?). I don’t know if klogd has been modified to search in /usr/src/linux-version/System.map yet. TODO: Look at the klogd srouce. If someone beats me to it, please email me and let me know if klogd has been modified to look in the new directory name for the linux source code.
- The man page doesn’t tell the whole the story. Look at this:
Apparently, not only does klogd look for the correct version of the map in the 3 klogd search directories, but klogd also knows to look for the name «System.map» followed by «-kernelversion», like System.map-2.4.18. This is undocumented feature of klogd.
A few drivers will need System.map to resolve symbols (since they’re linked against the kernel headers instead of, say, glibc). They will not work correctly without the System.map created for the particular kernel you’re currently running. This is NOT the same thing as a module not loading because of a kernel version mismatch. That has to do with the kernel version, not the kernel symbol table which changes between kernels of the same version!
What else uses the System.map
Don’t think that System.map is only useful for kernel oopses. Although the kernel itself doesn’t really use System.map, other programs such as klogd, lsof,
and many other pieces of software like dosemu require a correct System.map.
What Happens If I Don’t Have A Healthy System.map?
Suppose you have multiple kernels on the same machine. You need a separate System.map files for each kernel! If boot a kernel that doesn’t have a System.map file, you’ll periodically see a message like: System.map does not match actual kernel Not a fatal error, but can be annoying to see everytime you do a ps ax. Some software, like dosemu, may not work correctly (although I don’t know of anything off the top of my head). Lastly, your klogd or ksymoops output will not be reliable in case of a kernel oops.
How Do I Remedy The Above Situation?
The solution is to keep all your System.map files in /boot and rename them with the kernel version. Suppose you have multiple kernels like:
Then just rename your map files according to the kernel version and put them in /boot, like:
Now what if you have two copies of the same kernel? Like:
- /boot/vmlinuz-2.2.14
- /boot/vmlinuz-2.2.14.nosound
The best answer would be if all software looked for the following files:
Источник
Исследуем процесс загрузки Linux
(C) В.А.Костромин, 2007
(версия файла от 6.08.2007 г.)
Этап 3: Загрузчик 2 этапа операционной системы
3.3. Файл System.map
Информации о назначении этого файла в сети на удивление мало. Единственная содержательная статья — это заметка [16]. Во всех других найденных поисковиком ссылках просто утверждается, что этот файл нужно переносить в загрузочный каталог вместе со вновь скомпилированным ядром. Кроме заметки [16] упоминание файла System.map можно найти в man-страничках к утилитам klogd и ps.
3.3.1. Что такое «Таблица символов ядра»?
Однако имеются ситуации, когда нам нужно знать адреса символов (или определить название символа по его адресу). Для этого и создается таблица символов ядра. В ней перечислены все символы ядра и даны их соответствующие адреса. Вот несколько строк из таблицы символов ядра версии 2.6.14, установленного в системе ASP Linux 11. Эти строки позволят вам составить представление об этой таблице, а в своей системе вы можете просмотреть ее, заглянув в файл /boot/System.map.
Листинг 5. Несколько первых строк из таблицы символов ядра
Вы можете, например, видеть, что переменная с именем L6 расположена в ядре по адресу c0100199.
3.3.2. Когда и кем используется таблица символов ядра?
Как видите, информация, выдаваемая в строках EIP и Call Trace, для человека не очень информативна. Чтобы сделать ее более понятной для программиста, klogd преобразует адрес вызова (Call Trace) в символическое имя и передает эту информацию демону системного протоколиррования syslogd. Для преобразования адресов в имена как раз и используется таблица символов ядра.
3.3.3. Где находится таблица символов ядра?
Как говорится в статье [16], хотя man-страница к klogd и утверждает, что таблица символов ядра может находиться в файле /usr/src/linux/System.map, это не прослеживается в исходных кодах демона klogd. В той же статье утверждается, что демон klogd ищет в упомянутых каталогах не только файл System.map, но и файл System.map-release, где -release — номер версии текущего ядра. Причем, если обнаруживается файл System.map для ядра другой версии, поиск продолжается.
Утилита ps ищет таблицу символов ядра в следующих файлах:
Источник
Linux what is system map
void * mmap(void * start , size_t length , int prot , int flags , int fd , off_t offset );
int munmap(void * start , size_t length );
ОПИСАНИЕ
Аргумент prot описывает желаемый режим защиты памяти (он не должен конфликтовать с режимом открытия файла). Оно является либо PROT_NONE либо побитовым ИЛИ одного или нескольких флагов PROT_*. PROT_EXEC (данные в страницах могут исполняться); PROT_READ (данные можно читать); PROT_WRITE (в эту область можно записывать информацию); PROT_NONE (доступ к этой области памяти запрещен).
Параметр flags задает тип отражаемого объекта, опции отражения и указывает, принадлежат ли отраженные данные только этому процессу или их могут читать другие. Он состоит из комбинации следующих битов: MAP_FIXED Не использовать другой адрес, если адрес задан в параметрах функции. Если заданный адрес не может быть использован, то функция mmap вернет сообщение об ошибке. Если используется MAP_FIXED, то start должен быть пропорционален размеру страницы. Использование этой опции не рекомендуется. MAP_SHARED Разделить использование этого отражения с другими процессами, отражающими тот же объект. Запись информации в эту область памяти будет эквивалентна записи в файл. Файл может не обновляться до вызова функций msync (2) или munmap (2) . MAP_PRIVATE Создать неразделяемое отражение с механизмом copy-on-write. Запись в эту область памяти не влияет на файл. Не определено, являются или нет изменения в файле после вызова mmap видимыми в отраженном диапазоне.
Вы должны задать либо MAP_SHARED, либо MAP_PRIVATE.
Эти три флага описаны в POSIX.1b (бывшем POSIX.4) and SUSv2. В Linux также анализируются следующие нестандартные флаги: MAP_DENYWRITE Этот флаг игнорируется. (Раньше он обозначал, что попытки записи в подчиненные файлы должны завершаться с кодом ошибки ETXTBUSY. Но это стало основой для атак типа ‘отказ-в-доступе’ — ‘denial-of-service’.) MAP_EXECUTABLE Этот флаг игнорируется. MAP_NORESERVE (Используется вместе с MAP_PRIVATE.) Не выделяет страницы пространства подкачки для этого отображения. Если пространство подкачки выделяется, то это частное пространство копирования-при-записи может быть изменено. Если оно не выделено, то можно получить SIGSEGV при записи и отсутствии доступной памяти. MAP_LOCKED (Linux 2.5.37 и выше) Блокировать страницу или размеченную область в памяти так, как это делает mlock() . Этот флаг игнорируется в старых ядрах. MAP_GROWSDOWN Используется для стеков. Для VM системы ядра обозначает, что отображение должно распространяться вниз по памяти. MAP_ANONYMOUS Отображение не резервируется ни в каком файле; аргументы fd и offset игнорируются. Этот флаг вместе с MAP_SHARED реализован с Linux 2.4. MAP_ANON Псевдоним для MAP_ANONYMOUS. Не используется. MAP_FILE Флаг совместимости. Игнорируется.
MAP_32BIT Поместить размещение в первые 2Гб адресного рпостранства процесса. Игнорируется, если указано MAP_FIXED . Этот флаг сейчас поддерживается только на x86-64 для 64-битных программ.
Некоторые системы документируют дополнительные флаги MAP_AUTOGROW, MAP_AUTORESRV, MAP_COPY и MAP_LOCAL.
fd должно быть корректным описателем файла, если только не установлено MAP_ANONYMOUS, так как в этом случае аргумент игнорируется.
offset должен быть пропорционален размеру страницы, получаемому при помощи функции getpagesize (2).
Memory mapped by mmap is preserved across fork (2), with the same attributes.
A file is mapped in multiples of the page size. For a file that is not a multiple of the page size, the remaining memory is zeroed when mapped, and writes to that region are not written out to the file. The effect of changing the size of the underlying file of a mapping on the pages that correspond to added or removed regions of the file is unspecified. Системный вызов munmap удаляет все отражения из заданной области памяти, после чего все ссылки на данную область будут вызывать ошибку «неправильное обращение к памяти» (invalid memory reference). Отражение удаляется автоматически при завершении процесса. С другой стороны, закрытие файла не приведет к снятию отражения.
Адрес start должно быть кратен размеру страницы. Все страницы, содержащие часть указанного диапазона, не отображены, и последующие ссылки на эти страницы будут генерировать SIGSEGV. Это не будет являться ошибкой, если указанный диапазон не содержит отображенных страниц. Для отображений ‘файл-бэкэнд’ поле st_atime отображаемого файла может быть обновлено в любой момент между mmap() и соответствующим снятием отображения; первое обращение к отображенной странице обновит поле, если оно до этого уже не было обновлено.
Поля st_ctime и st_mtime файла, отображенного по PROT_WRITE и MAP_SHARED, будут обновлены после записи в отображенний диапазон, и до вызова последующего msync() с флагом MS_SYNC или MS_ASYNC, если такой случится.
ВОЗВРАЩАЕМЫЕ ЗНАЧЕНИЯ
ЗАМЕЧАНИЯ
НАЙДЕННЫЕ ОШИБКИ
Использование отражаемой области памяти может привести к следующим сигналам: SIGSEGV (попытка записи в область памяти, заданную mmap как область для чтения); SIGBUS (попытка доступа к части буфера, которая не является файлом; например, она может находиться за пределами файла. Подобной является ситуация, когда другой процесс уменьшает длину файла).
Источник