一、可执行文件格式
目标文件有三种格式:
.out pe elf
可重定位(relocatable)文件
可执行(executable)文件
共享(object)文件
ELF文件格式介绍:
Link view:
~~~~~~
ELF header
Program header table(optional)
Section 1
…..
Section n
Section header table
Execution view:
ELF header
Program header
Segment 1
……….
Segment n
Section header table
查看ELF文件头:
readelf –h hello
elf文件与进程地址空间的对应:
二、可执行程序的执行环境
点击(此处)折叠或打开
-
#include <stdio.h>
-
#include <stdlib.h>
-
#include <unistd.h>
-
int main(int argc, char * argv[])
-
{
-
int pid;
-
/* fork another process */
-
pid = fork();
-
if (pid<0)
-
{
-
/* error occurred */
-
fprintf(stderr,"Fork Failed!");
-
exit(-1);
-
}
-
else if (pid==0)
-
{
-
/* child process */
-
execlp("/bin/ls","ls",NULL);
-
}
-
else
-
{
-
/* parent process */
-
/* parent will wait for the child to complete*/
-
wait(NULL);
-
printf("Child Complete!");
-
exit(0);
-
}
- }
fork创建一个子进程,完全复制父进程。Execve要加载的进程将原来的进程环境给覆盖掉。新子进程堆栈也被清空。命令行参数和环境变量如何加载进新子进程堆栈的呢?
命令行参数和环境变量通过指针的形式,传到系统调用的内核处理函数。内核处理函数创建一个新的用户程序堆栈时,会将命令行产生和环境变量拷贝到用户态堆栈中。
Shell程序 à execve à sys_execve
在初始化新程序堆栈时拷贝进去
三、装载时动态链接和运行时动态链接应用举例