1. Question: How Linux executes the main function.
This article uses a simple C program (SIMPLE.C) as an example to explain. Code as follows,
- int Main ()
- {
- return(0);
- }
2. Compiling
~ #gcc-O simple simple.c
3. View basic information about an executable file
~ #objdump-F Simple
Simple:file format elf32-i386 architecture:i386, Flags 0x00000112:exec_p, has_syms, d_paged start address 0x080482d0
With Objdump This tool, you can get some key information about the executable file.
For example, the simple file format is "ELF32", the starting address of the file is 0x80482d0, and so on.
4. What is Elf
ELF is the abbreviation for executable and linking format, and is one of several common target file formats (and executable file formats) on UNIX.
The ELF's head structure provides basic information about the Elf file, and its data structure can be seen in/usr/include/elf.h, as shown below:
- typedef struct
- {
- unsigned char e_ident[ei_nident]; /* Magic number and other info * /
- Elf32_half E_type; / * Object File type * /
- Elf32_half E_machine; / * Architecture * /
- Elf32_word e_version; / * Object file version * /
- Elf32_addr E_entry; / * Entry point virtual address * /
- Elf32_off E_phoff; / * Program Header Table File offset * /
- Elf32_off E_shoff; / * Section Header Table file offset * /
- Elf32_word E_flags; / * PROCESSOR-SPECIFIC flags * /
- Elf32_half e_ehsize; / * ELF Header size in bytes * /
- Elf32_half e_phentsize; / * Program Header table Entry Size * /
- Elf32_half E_phnum; / * Program Header table Entry count * /
- Elf32_half e_shentsize; / * Section Header table Entry size * /
- Elf32_half E_shnum; / * Section Header table Entry count * /
- Elf32_half E_shstrndx; / * section Header string Table index * /
- } ELF32_EHDR;
Where E_entry stores the starting address of the execution file.
5. About the starting address
~ #objdump-D Simple
- 80482d0 <_start>:
- 80482d0:31 Ed XOR%ebp,%ebp
- 80482d2:5e Pop%esi
- 80482d3:89 E1 mov%esp,%ecx
- 80482d5:83 e4 F0 and $0xfffffff0,%esp
- 80482D8:50 Push%eax
- 80482d9:54 Push%ESP
- 80482DA:52 Push%edx
- 80482db:68 Push $0x8048420
- 80482e0:68, $0x8048274, Geneva
- 80482E5:51 Push%ECX
- 80482E6:56 Push%esi
- 80482e7:68 D0, Push $0x80483d0
- 80482ec:e8 CB FF FF call 80482BC <_init+0x48>
- 80482f1:f4 HLT
- 80482f2:89 f6 mov%esi,%esi
This command can get the simple disassembly code, you can see that the starting address 0x80482d0 corresponds to the _start this routine. What this code does is that the EBP is cleared 0, the value of the ESP is adjusted, and then some data is pushed to the stack, and finally a function is called.
The execution process of main function in Linux