Generating Programs and Linking

Professor Rick Han Department of Computer Science University of Colorado at Boulder CSCI 3753 Announcements

• Moodle - posted last Thursday’s lecture • Programming shell assignment 0 due Thursday at 11:55 pm, not 11 am • Introduction to Operating Systems • Read Chapters 3 and 4 in the textbook Operating System Architecture

App2 App1 App3 Posix, Win32, Java, C API System Libraries and Tools (, Shells, GUIs) System call API OS File Device Scheduler VM “Kernel” System Manager

CPU Memory Disk Display Mouse I/O What is an Application? Program P1 • A software program

consist of a sequence Code of code instructions and data – for now, let a simple app = a program • Computer executes the instructions line by Data line – code instructions operate on data Loading and Executing a Program

OS Loader Main Memory Fetch Code Disk Program and Data CPU P1 P1 P2 binary binary binary Program Counter (PC) Code Code Code Registers

ALU

Data Data Data Write Data Loading and Executing a Program Machine Code instructions of binary OS Loader Main Memory Disk Program P1 shift left by 2 register R1 P1 P2 binary and put in address A binary binary Code Code Code invoke low level system call n to OS: syscall n

jump to address B

Data Data Data Generating a Program’s Binary Executable • We program source code in a high-level language like C or Java, and use tools like compilers Program P1’s to create a program’s binary Binary Executable executable gcc can generate file P1.c any of these stages Code

P1.s P1.o Source Assembler Code

Data technically, there is a preprocessing step before the compiler. “gcc -c” will generate relocatable object files, and not run linker Linking Multiple Object Files Into an Executable P1 or P1.exe file P1.c foo2.o Code

P1.s Source Compiler Assembler P1.o Linker Code cc1 as ld

Data foo3.o • linker combines multiple .o object files into one binary executable file – why split a program into multiple objects and then relink them? – breaking up a program into multiple files, and compiling them separately, reduces amount of recompilation if a single file is edited • don’t have to recompile entire program, just the of the changed source file, then relink object files Linking Multiple Object Files Into an Executable P1 or P1.exe file P1.c foo2.o Code

P1.s Source Compiler Assembler P1.o Linker Code cc1 as ld

Data foo3.o • in combining multiple object files, the linker must – resolve references to variables and functions defined in other object files - this is called symbol resolution – relocate each object’s internal addresses so that the executable’s combination of objects is consistent in its memory references • an object’s code and data are compiled in its own private world to start at address zero Linker Resolves Unknown Symbols P1.c foo2.c

extern void f1(...); extern int globalvar1;

int globalvar1=0; void f1(...) { ---- main(...) { } ----- f1(...) void f2(...) { ------} globalvar1 = 4; ---- }

P1.o foo2.o the P1.o object file will contain a list of foo2.o’s lists unknown symbols, e.g. f1, in a symbol table unknown symbols, e.g. globalvar1 Linker Resolves Unknown Symbols ELF relocatable object file • ELF relocatable object file contains following sections: ELF header – ELF header (type, size, size/# sections) .text – code (.text) .rodata – data (.data, .bss, .rodata) .data • .data = initialized global variables .bss • .bss = uninitialized global variables (does not actually occupy space on .symtab disk, just a placeholder) .rel.text – symbol table (.symtab) – relocation info (.rel.text, .rel.data) .rel.data – symbol table (.debug only if .debug “-g” compile flag used) .line – line info (map C & .text line #s only if “-g”) .strtab – string table (for symbol tables) Section header table Linker Resolves Unknown Symbols

• Symbol table contains 3 types of symbols: – global symbols - defined in this object – global symbols referenced but not defined here – local symbols defined and referenced exclusively by this object, e.g. static global variables and functions • local symbols are not equivalent to local variables, which get allocated on the stack at run time Linker Resolves Unknown Symbols

global symbol referenced here extern float f1(); but defined elsewhere global symbols defined here int globalvar1=0;

void f2(...) {

“local” symbol static int x=-1; ----- }

• The symbol table informs the Linker where symbols referenced or referenceable by each object file can be found: – if another file references globalvar1, then look here for info – if this file reference f2, then another object file’s symbol table will mention f2 Linker Resolves Unknown Symbols

• Each entry in the ELF symbol table looks like: typedef struct { int name; /* string table offset */ int value; /* section offset or VM address */ int size; /* object size in bytes */ char type:4, /* data, func, section or src file name (4 bits) */ binding:4;/* local or global (4 bits) */ char reserved; /* unused */ char section; /* section header index, ABS, UNDEF, */ } ELF_Symbol;

here’s where we flag the undefined status Linker Resolves Unknown Symbols

• During linking, the linker goes through each input object file and determines if unknown symbols are defined in other object files P1.o relocatableobject file P2.o P3.o

Code Code Code

Data Data Data

.symtab .symtab .symtab

function f1() in P1.o defined No defined in is referenced but in P2? P3? Yes not defined, hence Linker unknown Linker Resolves Unknown Symbols

• What if two object files use the same name for a global variable? – Linker resolves multiply defined global symbols – functions and initialized global variables are defined as strong symbols, while uninitialized global variables are weak symbols Rule 1: multiple strong symbols are not allowed Rule 2: choose the strong symbol over the weak symbol Rule 3: given multiple weak symbols, choose any one Linker Resolves Unknown Symbols

• Linking with static libraries – Bundle together many related .o files together into a single file called a library or .a file • e.g. the C library libc.a contains printf(), strcpy(), random(), atoi(), etc. • library is created using the archive ar tool – the library is input to the linker as one file – linker can accept multiple libraries – linker copies only those object modules in the library that are referenced by the application program – Example: gcc main.c /usr/lib/libm.a /usr/lib/libc.a Linker Resolves Unknown Symbols libfoo.a • a static library is a collection of relocatable object modules foo1.o – group together related object modules – within each object, can foo2.o further group related functions – if an application links to foo3.o libfoo.a, and only calls a function in foo3.o, then only foo3.o will be linked into the foo4.o program Linker Resolves Unknown Symbols

• Linker scans object files and libraries sequentially left to right on command line to resolve unknown symbols – for each input file on command line, linker • updates a list of defined symbols with object’s defined symbols • tries to resolve the undefined symbols (from object and from list of previously undefined symbols) with the list of previously defined symbols • carries over the list of defined and undefined symbols to next input object file – so linker looks for undefined symbols only after they’re undefined! • it doesn’t go back over the entire set of input files to resolve the unknown symbol • if an unknown symbol becomes referenced after it was defined, then linker won’t be able to resolve the symbol! • Thus, order on the command line is important - put libraries last! Linker Resolves Unknown Symbols

• Example: gcc libfoo.a main.c – main.c calls a function f1 defined in libfoo.a – scanning left to right, when linker hits libfoo.a, there are no unresolved symbols, so no object modules are copied – when linker hits main.c, f1 is unresolved and gets added to unresolved list – Since there are no more input files, the linker stops and generates a linking error: /tmp/something.o: In function ‘main’: /tmp/something.o: undefined reference to ‘f1’ Linker Resolves Unknown Symbols

•Example: gcc main.c libfoo.a – main.c calls a function f1 defined in libfoo.a – scanning left to right, when linker hits main.c, it will add f1 to the list of unresolved references – when linker next hits libfoo.a, it will look for f1 in the library’s object modules, see that it is found, and add the object module to the linked program – No errors are generated. A binary executable is generated. • Lesson #1: the order of linking can be important, so put libraries at the end of command lines • Lesson #2: an undefined symbol error can also mean that you – didn’t link in the right libraries, didn’t add right library path – forgot to define the symbol somewhere in your code Linker Relocates Addresses

• After resolving symbols, the linker relocates addresses when combining the different object modules – merges separate code .text sections into a single .text section – merges separate .data sections into a single .data section – each section is assigned a memory address – then each symbol reference in the code and data sections is reassigned to the correct memory address • looks at .relo.text and .relo.data to find relocation entries of references that needed address translation – these are virtual memory addresses that are translated at load time into real run-time memory addresses Linked ELF Executable Object File ELF executable object file • ELF executable object file contains following sections: – ELF header (type, size, size/# sections) ELF header – segment header table segment header table – .init (program’s entry point, i.e. address .init of first instruction) – other sections similar .text – Note the absence of .rel.tex and .rodata .rel.data - they’ve been relocated! • Ready to be loaded into memory and .data run .bss – only sections through .bss are loaded .symtab into memory – .symtab and below are not loaded into .debug memory .line – code section is read-only – .data and .bss are read/write .strtab Section header table Loading Executable Object Files Run-time memory • Run-time memory image User stack • Essentially code, data, stack, and heap Unallocated • Code and data loaded from executable file Heap • Stack grows downward, heap Read/write .data, .bss grows upward Read-only .init, .text, .rodata