Memory Layout for Process ∞ Stack Data Code CS 140 Lecture Notes: Linkers
CS 140 Lecture Notes: Linkers Creating a Process Source Code Assembly Code Object Code Executable 101010101010101010101010101010101010101010101010 x.c cc x.s as x.o Code ∞ Data Stack 101010101010101010101010101010101010101010101010 101010101010101010101010101010101010101010101010 OS y.c cc y.s as y.o ld a.out 101010101010101010101010101010101010101010101010 z.c cc z.s as z.o Compiler Assembler Linker Loader CS 140 Lecture Notes: Linkers
CS 140 Lecture Notes: Linkers A Simple Example main.c stdio.c extern float sin(); extern printf(), scanf(); main() { double x, result; printf("Type number: "); scanf("%f", &x); result = sin(x); printf("Sine is %f\n", result); } FILE* stdin, stdout; int printf(const char* format,...) { ... fputc(c, stdout); } int scanf(const char* format,...) { c = fgetc(stdin); math.c double sin(double x) { ... } CS 140 Lecture Notes: Linkers
main.o Object File main.c main.o extern float sin(); extern printf(), scanf(); main() { double x, result; printf("Type number: "); scanf("%f", &x); result = sin(x); printf("Sine is %f\n", result); } 30 52 60 86 14 17 main: ... call printf call scanf call sin _s1: "Type number: " _s2: "%f" _s3: "Sine is %f\n" main T[0] _s1 D[0] _s2 D[14] _s3 D[17] printf T[30] printf T[86] scanf T[52] sin T[60] _s1 T[24] _s2 T[54] _s3 T[80] text section data section symbols “Store the final location of sin at offset 60 in the text section” relocation CS 140 Lecture Notes: Linkers
CS 140 Lecture Notes: Linkers printf.o Object File printf.c printf.o FILE* stdin, stdout; int printf(const char* format, ...) { ... fputc(c, stdout); } int scanf(const char* format, c = fgetc(stdin); 44 118 232 306 8 ... printf: load stdout scanf: load stdin stdin: stdout: printf T[44] scanf T[232] stdin D[0] stdout D[8] stdout T[118] stdin T[306] text section data section symbols relocation CS 140 Lecture Notes: Linkers
CS 140 Lecture Notes: Linkers After Pass 2 Memory map: Symbol table: 836 stdio.o data Name File Sec Offset Addr main: main T 0 0 _s1: main D 0 720 _s2: main D 14 734 _s3: main D 17 737 printf: stdio T 38 134 scanf: stdio T 232 328 stdin: stdio D 0 760 stdout: stdio D 8 768 sin: math T 0 508 760 main.o data 720 math.o text 508 stdio.o text 96 main.o text CS 140 Lecture Notes: Linkers
Relocation text section in main.o relocation record in main.o 30 ... call 0 text section in main.o printf T[30] relocation record in main.o printf: 134 symbol table 30 ... call 134 text section in a.out CS 140 Lecture Notes: Linkers