Linux Kernel是如何操控ELF文件

楔子

Glibc操控微软的CLR
Elf操控Glibc,让后者加载CLR
那么谁操控Elf呢?
自然是Linux Kernel了,
本篇来看下。.

例子

hello.c

#include<stdio.h>
#include<unistd.h>
void main()
{
  printf("********************hello world *************************\r\n");
  execlp("/test","test",NULL);
}

test.c

void main()
{
   printf("@@@@@@@@@@@@@@@@@@@ wo shi test @@@@@@@@@@@@@@@@\r\n");
}

命令:

gcc -static -o test test.c
gcc -static -o hello hello.c
echo hello | cpio -o --format=newc > hellofs

 

环境

启动qemu:

qemu-system-x86_64 -kernel arch/x86_64/boot/bzImage -initrd hellofs  -append "nokaslr root=/dev/sda rdinit=/hello console=ttyS0" -s -S  -smp 1 -nographic

lldb链接qemu:

lldb vmlinux
lldb gdb-remote 1234
b do_execve
b load_elf_binary
b __x64_sys_execve

 

调看

(lldb) b __x64_sys_execve
(lldb) c
(lldb) s
(lldb) s
(lldb) p filename 
(const char *) $0 = 0x0000000000499048 "/test"

如下图所示

(lldb) p filename 
(const char *) $0 = 0x0000000000499048 "/test"
(lldb) p *filename
(const char) $1 = '/'

可以看到内核函数__x64_sys_execve确实调用了./hello elf文件,后者则通过execlp调用了./test。

(lldb) c

[    2.184277] Freeing unused kernel image (rodata/data gap) memory: 1332K
[    2.184742] Run /hello as init process
********************hello world *************************
c[    2.259551] Kernel panic - not syncing: Attempted to kill init! exitcode=0x0000ff00
[    2.261976] CPU: 0 PID: 1 Comm: hello Not tainted 5.15.74 #1
[    2.262348] Hardware name: QEMU Standard PC (i440FX + PIIX, 1996), BIOS 1.15.0-1 04/01/2014
[    2.262711] Call Trace:

可以看到输出了hello world

结尾

这只是一个方面的调看,还有很多地方。后面慢慢了解。
作者:江湖评谈