ELF & ELF Loading
- Executable and Linkable Format
ELF包含:
1. Program header: 存各種segments (data, text, bss)
.text – Where read/execute code goes
.data – Programmer initialized read/write data
.bss – Uninitialized data (initially zero by convention)
2. Section header: 存各種sections用來做linking
- Dynamic elf: 會先load dynamic linker 然後在開始load .text, .data等等.
Dynamic Linking
1. Static linking is the result of the linker copying all library routines used in the program into the executable image.
2. Dynamic linking is accomplished by placing the name of a sharable library in the executable image. Actual linking with the library routines does not occur until the image is run, when both executable and library are placed in memory. An advantage of dynamic linking is that multiple programs can share a single copy of the library.
當使用dynamic linking時, 不直接呼叫main, 而要先做下列動作
1. 檢查heaader裡面是否有需要的library
2. Call mmap把library map到目前process的address space
3. Do some bookkeeping and call main()
如何呼叫library function?
1. Library, ex: libc, 大部份的時候都已經load到memory裡面, 因為其他program可能已經在使用.
2. Linker必須要把目前要直行的program所呼叫的function address填上在library裡面的address
3. If the linker doesn’t know where a function will end up, it creates a relocation -> 要求之後再做relocate
4. Part of loading: linker marches through each relocation and overwrites the call target -> 此時linker要去改.text裡面的function address
概念:
Compiler creates a jump table for all external calls
- 這個table就是PLT (Program Linkage Table), PLT指向GOT(Global Offset Table)
- GOT 存的就是<function, address in memory>
所以linker可以藉由PLT拿到某個library function目前在memory裡面的address.
A PLT is a table of absolute addresses to functions. It is used because the link editor doesn’t know where functions in shared objects will be located. Instead, a table is created so that the program and the dynamic linker can work together to find and execute functions in shared objects. I’ve simplified the explanation a bit1, but at a high level:
- Program calls a function in a shared object, the link editor makes sure that the program jumps to a slot in the PLT.
- The program sets some data up for the dynamic linker and then hands control over to it.
- The dynamic linker looks at the info set up by the program and fills in the absolute address of the function that was called in the PLT.
- Then the dynamic linker calls the function.
- Subsequent calls to the same function jump to the same slot in the PLT, but every time after the first call the absolute address is already in the PLT (because when the dynamic linker is invoked the first time, it fills in the absolute address in the PLT).
reference:
1. address-space slide from cse506 Don Porter
2. Linker and Loader
沒有留言:
張貼留言