Chinaunix首页 | 论坛 | 博客
  • 博客访问: 297049
  • 博文数量: 69
  • 博客积分: 3093
  • 博客等级: 中校
  • 技术积分: 626
  • 用 户 组: 普通用户
  • 注册时间: 2009-08-17 13:48
文章分类

全部博文(69)

文章存档

2011年(27)

2010年(11)

2009年(31)

分类: LINUX

2009-12-02 11:56:16

内核是从哪里开始执行的呢?几乎任何一本源代码分析的书都会给出详细的答案。不过,我试图从一个不同的角度(一个初学者的角度)来叙述,而不是一上来就给出答案。从熟悉的事物入手,慢慢接近陌生的事物,这是比较常见的思路。既然都是二进制代码,那么不妨从最简单的用户态C程序,hello world开始。说不定能找到共同点。恰好我是一个喜欢寻根究底的人。也许,理解了hello world程序的启动过程,有助于更好地理解内核的启动。

好,开始寻根究底吧。从普通的C语言用户态程序开始写。先写一个简单的hello world程序。

/*helloworld.c*/

#include 

int main()

{

    printf("hello world\n");

    return 0;

}

然后gcc helloworld.c -o helloworld,一个最简单的hello world程序出现了。

它是从哪里开始执行的呢?这还不简单?main函数么。地球人都知道。

为什么一定要从main函数开始呢?于是,我开始琢磨这个hello world程序。

file helloworld可知,它是一个elf可执行文件。

反汇编试试。

objdump -d helloworld

反汇编的结果令人吃惊,因为出现了_start()等一堆函数。一定是gcc编译时默认链接了一些库函数。

其实,只要运行gcc -v helloworld.c -o helloworld就会显示gcc详细的编译链接过程。其中包括链接/usr/lib/下的crti.o crt1.o crtn.o等等文件。用objdump查看,_start()函数就定义在crt1.o文件中。

那么helloworld的真正执行的入口在哪里呢?我们可以使用readelf来查看,看有没有有用信息。

readelf -a helloworld

helloworld作为一个elf文件,有elf文件头,section table和各个section等等。有兴趣可以去看看elf文件格式的文档。

用readelf可知,在helloworld的elf文件头的信息中,有这么一项信息:

入口点地址:               0x80482c0

可见,helloworld程序的入口地址在0x80482c0处,而由objdump得:

080482c0 <_start>:

可见,_start()是helloworld程序首先执行的函数。_start()执行完一些初始化工作后,经过层层调用,最终调用main().可以设想,如果_start()里最终调用的是foo(),那么C程序的主函数就不再是main(),而是foo()了。

再进一步:helloworld程序具体是如何执行的呢。我们只能猜测是由bash负责执行的。然而具体看bash代码就太复杂了。我们可以用strace跟踪helloworld的执行。

strace ./helloworld

出来一大堆函数调用。其中第一个是execve().这是一个关键的系统调用,它负责载入helloworld可执行文件并运行。其中有很关键的一步,就是把用户态的eip寄存器(实际上是它在内存中对应的值)设置为elf文件中的入口点地址,也就是_start()。具体可见内核中的sys_execve()函数。

由此可见,程序从哪里开始执行,取决于在刚开始执行的那一刻的eip寄存器的值。而这个eip是由其它程序设置的,在这里,eip是由Linux内核设置的。具体过程如下:

1.用户在shell里运行./helloworld。

2.shell(这里是bash)调用系统调用execve()。

3.execve陷入到内核里执行sys_execve(),把用户态的eip设置为_start()。

4.当系统调用执行完毕,helloworld进程开始运行时,就从_start()开始执行

5.helloworld进程最后才执行到main()。

 

参考:elf文件格式

阅读(1118) | 评论(2) | 转发(0) |
给主人留下些什么吧!~~

fera2009-12-08 16:16:20

As for item 4 above, _start() runs in kernel mode.

fera2009-12-08 16:15:11

Generally speaking, the start up process of an application which has main() as entry point is like below: 1. Kernel creates a new process; 2. Loader loads the executable files, importing its code, data section etc to memory; 3. Kernel sets eip to the first instruction of the executable (main() in the case), sets up the context (typicallly user stack, kernel stack, etc), and mark the process "READY"; 4. Actually in the case _start() does the work such as context setup. Or maybe loading of th