<<

CS 449 – and gcc Preprocessed Object Linking source source files

.c cpp cc1 .o ld

Preprocessor Compiler Jonathan Misurda [email protected]

Executables Older Executable Formats

•What do we need to store? • a.out (Assembler OUTput) –Code – Oldest format – –No longer commonly used –More? •COFF (Common Object Format) •Agree on a common format (much like with – Older UNIX Format ID3 tags) –No longer commonly used

Modern Executable Formats a.out

•PE () • header –Based on COFF •text segment –Used in 32‐ and 64‐bit Windows •data segment •ELF (Executable and Linkable Format) •text relocations – /UNIX •data relocations •symbol table •Mach‐O file •string table –Mac

1 Header Process’s Address Space

•Every a.out formatted begins with an exec 0x7fffffff structure: Stack $sp struct exec { brk unsigned long a_midmag; //magic number unsigned long a_text; brk unsigned long a_data; Data (Heap) Data (Heap) unsigned long a_bss; unsigned long a_syms; _end unsigned long a_entry; Data (Globals) unsigned long a_trsize; unsigned long a_drsize; Text (Code) }; 0 CS 1550 ‐ 2077

Libraries Linking

•Not all code in a program is what you wrote • Static Linking –Copy code into executable at •Use code that others have written in your own –Done by linker program •Dynamic Linking •How to include this code in your address –Copy code into Address Space at load time or later space? –Done by link

Static Linking Dynamic Linking

#include #include int main() { Shared Objects printf(“The sqrt of 9 is %f\n”, sqrt(9)); /usr/lib/libc.so /usr/lib/libm.so Stack return 0; } Archives Executable Data (Heap) /usr/lib/libc.a /usr/lib/libm.a Data (Heap) ld Object Data (Globals) files Executable Link Loader Text (Code)

.o ld

Linker

2 Dynamic Loading Function Pointers

DLL 2 •How do we call a function when we can’t be

DLL 1 sure what address it’s loaded at?

Stack Stack • Need a level of indirection

Data (Heap) Data (Heap) Data (Heap) Data (Heap) LoadLibrary(“DLL1.dll”); Data (Globals) LoadLibrary(“DLL2.dll”); Data (Globals) •Use a function pointer

Text (Code) Text (Code)

Function Pointers in C

#include int f(int x) { return x; } int main() { int (*g)(int x);

g = f; printf(“%d\n”,g(3)); return 0; }

3