分析源代码编译链接过程和shell中ELF格式可执行文件的初始化执行过程

来源:互联网 发布:好听的淘宝优惠群取名 编辑:程序博客网 时间:2024/06/04 18:03

刘昆

+《Linux内核分析》MOOC课程http://mooc.study.163.com/course/USTC-1000029000 ”


一、本文用到的三个源文件代码如下,三个进程将使用同一个进程号,第三个进程执行系统命令查看当前进程使用的动态库信息

//第一个进程,通过execv执行当前目录下进程2

#include <stdio.h>

#include <unistd.h>

int main(){

    printf("This is the first process, PID = %d\n",getpid());

    execv("./2",NULL);

}


//第二进程,通过EXEC执行新的进程3

#include <stdio.h>

#include <unistd.h>

int main(){

    printf("This is the second process, PID = %d\n",getpid());

    execv("./3",NULL);

}

//进程3,通过system()函数,执行系统命令,查看当前进程的虚拟内存信息

#include <stdio.h>

#include <unistd.h>


int main(){

    printf("This is the third process, PID = %d\n",getpid());

   char str[100] = {};

    sprintf(str,"cat /proc/%d/maps >> 1.txt",getpid());

    system(str);

}



二、通过readelf -h 获得进程3的elf文件头信息

ELF Header:
  Magic:   7f 45 4c 46 01 01 01 00 00 00 00 00 00 00 00 00 
  Class:                             ELF32
  Data:                              2's complement, little endian
  Version:                           1 (current)
  OS/ABI:                            UNIX - System V
  ABI Version:                       0
  Type:                              EXEC (Executable file)
  Machine:                           Intel 80386
  Version:                           0x1
  Entry point address:               0x8048390
  Start of program headers:          52 (bytes into file)
  Start of section headers:          4420 (bytes into file)
  Flags:                             0x0
  Size of this header:               52 (bytes)
  Size of program headers:           32 (bytes)
  Number of program headers:         9
  Size of section headers:           40 (bytes)
  Number of section headers:         30
  Section header string table index: 27

三、通过cat /proc/$PID/maps获得进程3的虚拟内存信息
08048000-08049000 r-xp 00000000 08:01 2136691    /home/kks/test/3
08049000-0804a000 r--p 00000000 08:01 2136691    /home/kks/test/3
0804a000-0804b000 rw-p 00001000 08:01 2136691    /home/kks/test/3
b75e4000-b75e5000 rw-p 00000000 00:00 0 
b75e5000-b7784000 r-xp 00000000 08:01 1704863    /lib/i386-linux-gnu/libc-2.15.so
b7784000-b7786000 r--p 0019f000 08:01 1704863    /lib/i386-linux-gnu/libc-2.15.so
b7786000-b7787000 rw-p 001a1000 08:01 1704863    /lib/i386-linux-gnu/libc-2.15.so
b7787000-b778a000 rw-p 00000000 00:00 0 
b779b000-b779e000 rw-p 00000000 00:00 0 
b779e000-b779f000 r-xp 00000000 00:00 0          [vdso]
b779f000-b77bf000 r-xp 00000000 08:01 1704843    /lib/i386-linux-gnu/ld-2.15.so
b77bf000-b77c0000 r--p 0001f000 08:01 1704843    /lib/i386-linux-gnu/ld-2.15.so
b77c0000-b77c1000 rw-p 00020000 08:01 1704843    /lib/i386-linux-gnu/ld-2.15.so
bff6b000-bff8c000 rw-p 00000000 00:00 0          [stack]

四、exec*进程的系统调用过程(ELF可执行程序的初始化执行实现过程)

首先,系统调用的流程:
do_execve -> do_execve_common -> exec_binprm-> search_binary_handler->fmt->load_binary(bprm)->load_elf_binary -> start_thread
其次,start_thead完成进程原有堆栈向新堆栈的过渡





0 0