Notes about linux /proc/kcore
本文将mark下linux中/proc/kcore
相关notes。
What
/proc/kcore
is a file in the virtual /proc filesystem of a Linux machine. It is created by the kernel in fs/proc/kcore.c and allows read access to all the kernels virtual memory space from userland.
Internally it has the format of an ELF core dump file (ELF Type 4/ET_CORE). That means it has the same format as a core file from a crashed process; but instead of capturing the (static) state of a single process at the moment of the crash, it provides a real time view into the state of the whole system.
How
- The ELF header (
Elf64_Ehdr
): It’s at the start of every ELF file. We need two pieces of information from it: the location and number of entries of the program header table. - The Program headers (
Elf64_Phdr
): An ELF file contains an array of program header structures. There are various subtypes of program headers, but we care only about the ones marked asPT_LOAD
. Each of these headers describe a loadable segment - a part of the file that is loaded into memory. In/proc/kcore
, they describe where in the file each portion of the system memory can be found.
On x86-64 systems, Linux maintains a complete one-to-one map of all physical memory in the kernels virtual address space. So by reading the right ranges of kernel virtual memory, one can get a complete copy of the content of the physical memory of that system.
每个PT_LOAD
header用来记录一段 memory region,并描述了这段 memory region对应的文件offset、内核虚拟地址和长度。
步骤
- 使用
open
系统调用打开/proc/kcore
文件 - 遍历ELF文件中的程序头表(Program Header Table),找到包含目标内核虚拟地址的段(每个段描述了内核虚拟地址到文件offset的映射关系)
- 根据计算出的文件offset,使用
lseek
定位到目标位置,使用read
读取目标地址的内容
参考资料: