1 / 38

Linking

Linking. Summer 2014 COMP 2130 Intro Computer Systems Computing Science Thompson Rivers University. Your vision? Seek with all your heart?. Course Objectives. The better knowledge of computer systems, the better programing. Your vision? Seek with all your heart?. Course Contents.

laken
Télécharger la présentation

Linking

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Linking Summer 2014 COMP 2130 Intro Computer Systems Computing Science Thompson Rivers University

  2. Your vision? Seek with all your heart? Course Objectives • The better knowledge of computer systems, the better programing. Linking

  3. Your vision? Seek with all your heart? Course Contents • Introduction to computer systems: B&O 1 • Introduction to C programming: K&R 1 – 4 • Data representations: B&O 2.1 – 2.4 • C: advanced topics: K&R 5.1 – 5.10, 6 – 7 • Introduction to IA32 (Intel Architecture 32): B&O 3.1 – 3.8, 3.13 • Compiling, linking, loading, and executing: B&O 7 (except 7.12) • Dynamic memory management – Heap: B&O 9.9.1 – 9.9.2, 9.9.4 – 9.9.5, 9.11 • Code optimization: B&O 5.1 – 5.6, 5.13 • Memory hierarchy, locality, caching: B&O 5.12, 6.1 – 6.3, 6.4.1 – 6.4.2, 6.5, 6.6.2 – 6.6.3, 6.7 • Virtual memory (if time permits): B&O 9.4 – 9.5 Linking

  4. Your vision? Seek with all your heart? Unit Learning Objectives • List two jobs that linkers do. • Explain what “relocatable code” means. • Compare the three types of object files. • Explain the purposes of .text, .rodata, .data, and .bss sections. • Give examples of the three types of symbols. • Compare the two types of libraries. • List the advantages of using shared libraries. Linking

  5. Your vision? Seek with all your heart? Unit Contents • Compiler Drivers • Static Linking • Object Files • Relocatable Object Files • Symbols and Symbol Tables • Static Libraries • Loading Executable Object Files • Shared Libraries Linking

  6. Your vision? Seek with all your heart? Linking • Understanding linkers will help you build large programs. • Understanding linkers will help you avoid dangerous programming errors. • Understanding linking will help you understand how language scoping rules are implemented. • Understanding linking will help you understand other important systems concepts. • Understanding linking will enable you to exploit shared libraries. Linking

  7. Your vision? Seek with all your heart? 1. Compiler Drivers • A compiler driver invokes the language preprocessor, compiler, assembler, and linker. • the name of the compiler driver on cs.tru.ca - gcc Linking

  8. Carnegie Mellon Example C Program main.c swap.c int buf[2] = {1, 2}; int main() { swap(); return 0; } extern int buf[]; int *bufp0 = &buf[0]; static int *bufp1; void swap() { int temp; bufp1 = &buf[1]; temp = *bufp0; *bufp0 = *bufp1; *bufp1 = temp; }

  9. Carnegie Mellon Static Linking • Programs are separately translated, and linked using a compiler driver: • $ gcc -c link1.c • $ gcc -c header.c • $ gcc -o out link1.o header.o • ./out main.c swap.c Source files Translators (cpp, cc1, as) Translators (cpp, cc1, as) Separately compiled relocatable object files main.o swap.o Linker (ld) Fully linked executable object file (contains code and data for all functions defined in main.c and swap.c) p

  10. Your vision? Seek with all your heart? 2. Static Linking • Here, all code is contained in a single executable module. • Library references are more efficient because the library procedures are statically linked into the program. • Static linking increases the file size of your program, and it may increase the code size in memory if other applications, or other copies of your application, are running on the system. Linking

  11. Carnegie Mellon Why Linkers? • Reason 1: Modularity • Program can be written as a collection of smaller source files, rather than one monolithic mass. • Can build libraries of common functions (more on this later) • e.g., Math library, standard C library • Reason 2: Efficiency • Time: Separate compilation • Change one source file, compile, and then relink. • No need to recompile other source files. • Space: Libraries • Common functions can be aggregated into a single file... • Yet executable files and running memory images contain only code for the functions they actually use.

  12. Carnegie Mellon What Do Linkers Do? • Step 1. Symbol resolution • Programs define and reference symbols (variables and functions): • void swap() {…} /* define symbol swap */ • swap(); /* reference symbol swap */ • int *xp = &x; /* define symbol xp, reference x */ • Symbol definitions are stored (by compiler) in symbol table in the .o files. • Symbol table is an array of structs. • Each entry includes name, size, and relative location of symbol. • Linker associates each symbol reference with exactly one symbol definition. • Symbols will be replaced with their relative locationsin the .o files. • Step 2. Relocation • Merges separate code and data sections in the .o files into single sections in the a.out file. • Relocates symbols from their relative locationsin the .o files to their final absolute memory locations in the executable. • Updates all references to these symbols to reflect their new positions.

  13. Your vision? Seek with all your heart? 3. Object Files • Relocatable object file (.o file) • Contains code and data in a form that can be combined with other relocatable object files to form executable object file. • The symbols in each .o file use relative addresses. • Not executable yet • Each .o file is produced from exactly one source (.c) file. • E.g., $ gcc –c swap.c • Executable object file (a.out file) • Contains code and data in a form that can be copied directly into memory and then executed. • Instructions use absolute addresses. • Shared object file (.so file) • Special type of relocatable object file that can be loaded into memory and linked dynamically, at either load time or run-time. • Called Dynamic Link Libraries (DLLs) by Windows Linking

  14. Information An object file may contain five kinds of information. • Header information: overall information about the file, such as the size of the code, name of the source file it was translated from, and creation date. • Object code: Binary instructions and data generated by a compiler or assembler. • Relocation: A list of the places in the object code that have to be fixed up when the linker changes the addresses of the object code. • Symbols: Global symbols defined in this module, symbols to be imported from other modules or defined by the linker. • Debugging information: Other information about the object code not needed for linking but of use to a debugger. This includes source file and line number information, local symbols, descriptions of data structures used by the object code such as C structure definitions. Introduction

  15. Your vision? Seek with all your heart? 4. Relocatable Object Files Linking

  16. Carnegie Mellon Executable and Linkable Format (ELF) • Standard binary format for object files • Originally proposed by AT&T System V Unix • Later adopted by BSD Unix variants and Linux • ELF is flexible and extensible, and it is not bound to any particular processor or architecture. This has allowed it to be adopted by many different operating systems on many different platforms. • One unified format for • Relocatable object files (.o), • Executable object files (a.out) • Shared object files (.so) • Generic name: ELF binaries

  17. Carnegie Mellon • ELF header • Information to parse and interpret the object file: Word size, byte ordering, file type (.o, exec, .so), machine type, etc. • Segment header table • For run time execution: Page size, virtual addresses memory segments (sections), segment sizes. • .textsection • Instruction code • .rodata section • Read only data: jump tables, ... • .datasection • Initialized global variables • .bsssection • Uninitialized global variables • Has section header but occupies no space 0 ELF header Segment header table (required for executables) .text section .rodata section .data section .bss section .symtabsection .rel.txtsection .rel.datasection .debug section Section header table

  18. Carnegie Mellon • .symtab section • Symbol table • Procedure and static variable names • Section names and locations -> used by linker for code relocation • .rel.text section • Relocation info for .textsection • Addresses of instructions that will need to be modified in the executable • Instructions for modifying. • .rel.data section • Relocation info for .datasection • Addresses of pointer data that will need to be modified in the merged executable • .debug section • Info for symbolic debugging (gcc -g) • Section header table • For linking and relocation: Offsets and sizes of each section 0 ELF header Segment header table (required for executables) .text section .rodata section .data section .bss section .symtabsection .rel.txtsection .rel.datasection .debug section Section header table

  19. Types of ELF files ELF files come in three slightly different flavors: • relocatable, • executable, and • shared object. Relocatable files are created by compilers and assemblers but need to be processed by the linker before running. Executable files have all relocation done and all symbols resolved except perhaps shared library symbols to be resolved at runtime. Shared objects are shared libraries, containing both symbol information for the linker and directly runnable code for runtime. Introduction

  20. Your vision? Seek with all your heart? 5. Symbols and Symbol Tables • Global symbols • Symbols defined by module m that can be referenced by other modules. • E.g.: non-static C functions and non-static global variables. (Note that static C functions and static global variables cannot be referred from other files.) • External symbols • Global symbols that are referenced by module m but defined by some other module. • Local symbols • Symbols that are defined and referenced exclusively by module m. • E.g.: C functions and variables defined with the staticattribute. • Local linker symbols are not local program variables. Linking

  21. Resolving Symbols Carnegie Mellon Global External Local Global int buf[2] = {1, 2}; int main() { swap(); return 0; } extern int buf[]; int *bufp0 = &buf[0]; static int *bufp1; void swap() { int temp; bufp1 = &buf[1]; temp = *bufp0; *bufp0 = *bufp1; *bufp1 = temp; } Global main.c External Linker knows nothing of temp extern void swap();is not in main.c. [Q] Is it okay? swap.c

  22. Your vision? Seek with all your heart? 7. Relocation Linking

  23. Relocating Code and Data Carnegie Mellon Relocatable Object Files Executable Object File System code .text 0 Headers .data System data System code main() .text main.o swap() main() .text More system code .data intbuf[2]={1,2} System data .data swap.o int buf[2]={1,2} int *bufp0=&buf[0] swap() .text .bss int *bufp1 .symtab .debug .data int *bufp0=&buf[0] .bss static int *bufp1 Even though private to swap, requires allocation in .bss because of lifespan

  24. Your vision? Seek with all your heart? 6.2-3 Linking with Static Libraries Linking

  25. Packaging Commonly Used Functions Carnegie Mellon • How to package functions commonly used by programmers? • Math, I/O, memory management, string manipulation, etc. • Awkward, given the linker framework so far: • Option 1: Put all functions into a single source file • Programmers link big object file into their programs • Space and time inefficient • Option 2: Put each function in a separate source file • Programmers explicitly link appropriate binaries into their programs • More efficient, but burdensome on the programmer • Types of libraries: • Static libraries • Shared libraries

  26. Solution: Static Libraries Carnegie Mellon • Static libraries (.aarchive files) • Concatenate related relocatable object files into a single file with an index (called an archive). • Enhance linker so that it tries to resolve unresolved external references by looking for the symbols in one or more archives. • If an archive member file resolves reference, link it into the executable.

  27. Creating Static Libraries Carnegie Mellon atoi.c printf.c random.c ... Translator Translator Translator atoi.o printf.o random.o unix> ar rs libc.a \ atoi.o printf.o … random.o Archiver (ar) C standard library libc.a • Archiver allows incremental updates • Recompile function that changes, and replace .o file in archive.

  28. Commonly Used Libraries Carnegie Mellon libc.a (the C standard library) • 8 MB archive of 1392 object files. • I/O, memory allocation, signal handling, string handling, data and time, random numbers, integer math libm.a (the C math library) • 1 MB archive of 401 object files. • floating point math (sin, cos, tan, log, exp, sqrt, …) % ar -t /usr/lib/libc.a | sort … fork.o … fprintf.o fpu_control.o fputc.o freopen.o fscanf.o fseek.o fstab.o … % ar -t /usr/lib/libm.a | sort … e_acos.o e_acosf.o e_acosh.o e_acoshf.o e_acoshl.o e_acosl.o e_asin.o e_asinf.o e_asinl.o …

  29. Linking with Static Libraries Carnegie Mellon multvec.o addvec.o main2.c vector.h Archiver (ar) Translators (cpp, cc1, as) Static libraries libvector.a libc.a Relocatable object files printf.oand any other modules called by printf.o main2.o addvec.o Linker (ld) Fully linked executable object file p2

  30. Using Static Libraries Carnegie Mellon • Linker’s algorithm for resolving external references: • Scan .o files and .a files in the command line order. • During the scan, keep a list of the current unresolved references. • As each new .o or .a file, obj, is encountered, try to resolve each unresolved reference in the list against the symbols defined in obj. • If any entries in the unresolved list at end of scan, then error. • Problem: • Command line order matters! • Moral: put libraries at the end of the command line. unix> gcc libtest.o -L. -lmine unix> gcc -L. -lmine libtest.o libtest.o: In function `main': libtest.o(.text+0x4): undefined reference to `libfun'

  31. Your vision? Seek with all your heart? 9. Loading Executable Object Files Linking

  32. Loading Executable Object Files Carnegie Mellon Memory Invisible to user code Executable Object File Kernel virtual memory 0 ELF header User stack (created at runtime) Program header table (required for executables) %esp (stack pointer) .init section .text section Memory-mapped region for shared libraries .rodata section Loaded into .data section .bss section brk Run-time heap (created by malloc) .symtab .debug Loaded from the executable file Read/write segment (.data, .bss) .line .strtab Read-only segment (.init, .text, .rodata) Section header table (required for relocatables) Unused 0

  33. Your vision? Seek with all your heart? 10. Shared Libraries Linking

  34. Shared Libraries Carnegie Mellon • Static libraries have the following disadvantages: • Duplication in the stored executables (every function need std libc) • Duplication in the running executables • Minor bug fixes of system libraries require each application to explicitly relink • Modern solution: Shared Libraries • Object files that contain code and data that are loaded and linked into an application dynamically, at either load-time or run-time • Also called: dynamic link libraries, DLLs, .so files • Shared library routines can be shared by multiple processes. • Do executable files contain the code in shared libraries? • No. Dynamic linking – The symbols for the code in shared libraries will be resolved with absolute addresses at either load-time or run-time.

  35. Shared Libraries (cont.) Carnegie Mellon • Dynamic linking can occur when executable is first loaded and run (load-time linking). • Common case for Linux, handled automatically by the dynamic linker (ld-linux.so). • Standard C library (libc.so) usually dynamically linked. • Dynamic linking can also occur after program has begun (run-time linking). • The executable is not linked to a shared library at load-time, so it will not contain any stubs into the shared library. • In Linux, this is done by calls to the dlopen() interface. • Distributing software. • High-performance web servers. • Runtime library inter-positioning. • Shared library routines can be shared by multiple processes.

  36. Dynamic Linking at Load-time Carnegie Mellon main2.c vector.h unix> gcc -shared -o libvector.so \ addvec.c multvec.c Translators (cpp, cc1, as) libc.so libvector.so Relocatable object file Relocation and symbol table info main2.o Linker (ld) Partially linked executable object file p2 Loader (execve) libc.so libvector.so Code and data Fully linked executable in memory Dynamic linker (ld-linux.so)

  37. Dynamic Linking at Run-time Carnegie Mellon #include <stdio.h> #include <dlfcn.h> int x[2] = {1, 2}; int y[2] = {3, 4}; int z[2]; int main() { void *handle; void (*addvec)(int *, int *, int *, int); // [Q] ??? char *error; /* dynamically load the shared lib that contains addvec() */ handle = dlopen("./libvector.so", RTLD_LAZY); // lazy binding if (!handle) { fprintf(stderr, "%s\n", dlerror()); exit(1); }

  38. Dynamic Linking at Run-time Carnegie Mellon ... /* get a pointer to the addvec() function we just loaded */ addvec = dlsym(handle, "addvec"); if ((error = dlerror()) != NULL) { fprintf(stderr, "%s\n", error); exit(1); } /* Now we can call addvec() just like any other function */ addvec(x, y, z, 2); printf("z = [%d %d]\n", z[0], z[1]); /* unload the shared library */ if (dlclose(handle) < 0) { fprintf(stderr, "%s\n", dlerror()); exit(1); } return 0; }

More Related