代码改变世界

ld

2016-08-13 22:54  mina  阅读(263)  评论(0编辑  收藏  举报

动态链器,

可执行文件格式,包含代码和数据,引用可能外部文件定义的符号(变量和函数), 因此重定位信息和符号信息也是需要的。辅助信息可选的,如调试信息,硬件信息等。

按区间保存信息,称为段 segment 或节section, 不同文件格式中段和节的含义可能有细微区别;最后可执行文件夹通常都有一个文件头部以描述文件的总体结构。

comple and link, load, source file compiled to object file, then object files link to executable file, then load executable file to memory to run.

ELF[executable and linking format] COFF[ common object file format] a.out[assembler and link editor output]

ELF load precedure

1, kernel read ELF header, then read data structure according to header, to find the loadable segment, and invoke the mmap() function to load the segment content to memory. before load, kernel pass the segment label to mmap() directly,  segment label indicates whether or not the segment is readable, writable, executable  in memory. obviously, text segment are readable and executable, data segment are readable and writable. this way use the modern OS and processor protecting memory functionality.

2, kernel analyze the ELF to get dynamic linker name from PT_INTERP segment, and load the dynamic linker.  the dynamic link of modern LINUX is /lib/ld-linux.so.2

3, kernel set a label-value pair in stack of the new process,  to indicate dynamic linker related operation.

4, kernel pass the control to dynamic linker

5, dynamic linker check the external shared library dependency, and load it by need.

6, dynamic linker redirect the external reference, general speeking, tell the program the external label address which is in the address space of memory shard library. another feaute is lazy redirecting by need

7, dynamic linker execute ELF file  .init code to init the program. in old system, the signature is _init(void), whereas modern system is void __attribute((constructor)) init_function(void){}, the function name is any.

8, dynamic linker pass the control to program, start from entry point from ELF header indication.  defined explictly in a.out and ELF, but implictly in COFF.