Winter 2015 COMP 2130 Intro Computer Systems Computing Science Thompson Rivers University Linking.

Slides:



Advertisements
Similar presentations
Part IV: Memory Management
Advertisements

Fabián E. Bustamante, Spring 2007 Linking Today Static linking Object files Static & dynamically linked libraries Next time Exceptional control flows.
Program Development Tools The GNU (GNU’s Not Unix) Toolchain The GNU toolchain has played a vital role in the development of the Linux kernel, BSD, and.
Linking & Loading CS-502 Operating Systems
Chapter 3 Loaders and Linkers
Linker and Loader. Program building into four stages (C Program) Preprocessing (Preprocessor) It processes include files, conditional compilation instructions.
Mr. D. J. Patel, AITS, Rajkot 1 Operating Systems, by Dhananjay Dhamdhere1 Static and Dynamic Memory Allocation Memory allocation is an aspect of a more.
Linkers and Loaders 1 Linkers & Loaders – A Programmers Perspective.
Computer Organization CS224 Fall 2012 Lesson 12. Synchronization  Two processors or threads sharing an area of memory l P1 writes, then P2 reads l Data.
COMPILING OBJECTS AND OTHER LANGUAGE IMPLEMENTATION ISSUES Credit: Mostly Bryant & O’Hallaron.
Instructor: Erol Sahin
Generating Programs and Linking Professor Rick Han Department of Computer Science University of Colorado at Boulder.
Carnegie Mellon 1 Linking : Introduction to Computer Systems 11 th Lecture, Sept. 30, 2010 Instructors: Randy Bryant and Dave O’Hallaron.
“The course that gives CMU its Zip!”
CS 330 What software engineers need to know about linking and a few things about execution.
A. Frank - P. Weisberg Operating Systems Real Memory Management.
Linking Topics Static linking Object files Static libraries Loading Dynamic linking of shared libraries CS213.
Chapter 91 Memory Management Chapter 9   Review of process from source to executable (linking, loading, addressing)   General discussion of memory.
CS 201 Computer Systems Organization. Today’s agenda Overview of how things work Compilation and linking system Operating system Computer organization.
Carnegie Mellon 1 Linking Lecture, Apr. 11, 2013 These slides are from website which accompanies the book “Computer Systems: A.
Intro to Computer Systems Summer 2014 COMP 2130 Introduction to Computer Systems Computing Science Thompson Rivers University.
Virtual & Dynamic Memory Management Summer 2014 COMP 2130 Intro Computer Systems Computing Science Thompson Rivers University.
CIS250 OPERATING SYSTEMS Memory Management Since we share memory, we need to manage it Memory manager only sees the address A program counter value indicates.
Topic 2d High-Level languages and Systems Software
CS 3214 Computer Systems Godmar Back Lecture 15. Announcements Project 3 due Mar 24 Exercise 7 due Mar 25 CS 3214 Spring /3/2016.
CS 367 Linking Topics Static linking Object files Static libraries
© Janice Regan, CMPT 300, May CMPT 300 Introduction to Operating Systems Memory: Relocation.
Linking February 20, 2001 Topics static linking object files static libraries loading dynamic linking of shared libraries class16.ppt “The course.
Computer System Chapter 7. Linking Lynn Choi Korea University.
CPS3340 COMPUTER ARCHITECTURE Fall Semester, /29/2013 Lecture 13: Compile-Link-Load Instructor: Ashraf Yaseen DEPARTMENT OF MATH & COMPUTER SCIENCE.
Linking Topics Static linking Object files Static libraries Loading.
Linking Topics Static linking Dynamic linking Case study: Library interpositioning.
Instructors: Greg Ganger, Greg Kesden, and Dave O’Hallaron
Linking Ⅱ.
Processes and Threads-I Static and dynamic linking, Loading, Anatomy of a Process.
Linking October 5, 2002 Topics static linking object files static libraries loading dynamic linking of shared libraries Reading: Chapter 7 Problems: 7.8.
CS412/413 Introduction to Compilers and Translators April 14, 1999 Lecture 29: Linking and loading.
Linking Summer 2014 COMP 2130 Intro Computer Systems Computing Science Thompson Rivers University.
Computer System Organization. Overview of how things work Compilation and linking system Operating system Computer organization Today’s agenda.
Chapter 13 : Symbol Management in Linking
Slides adapted from Bryant and O’Hallaron
Carnegie Mellon 1 Bryant and O’Hallaron, Computer Systems: A Programmer’s Perspective, Third Edition Linking : Introduction to Computer Systems 13.
1 Linking. 2 Outline What is linking and why linking Complier driver Static linking Symbols & Symbol Table Suggested reading: 7.1~7.5.
CSc 453 Linking and Loading
Linking I Topics Assembly and symbol resolution Static linking Systems I.
Computer System Chapter 7. Linking Lynn Choi Korea University.
Program Translation and Execution I: Linking Sept. 29, 1998 Topics object files linkers class11.ppt Introduction to Computer Systems.
LECTURE 3 Translation. PROCESS MEMORY There are four general areas of memory in a process. The text area contains the instructions for the application.
Hello world !!! ASCII representation of hello.c.
Carnegie Mellon 1 Introduction to Computer Systems /18-243, fall th Lecture, Sep 29 th Instructors: Roger B. Dannenberg and Greg Ganger 1.
Linking Winter 2013 COMP 2130 Intro Computer Systems Computing Science Thompson Rivers University.
Binding & Dynamic Linking Presented by: Raunak Sulekh(1013) Pooja Kapoor(1008)
Carnegie Mellon Introduction to Computer Systems /18-243, spring th Lecture, Feb. 26 th Instructors: Gregory Kesden and Markus Püschel.
Lecture 3 Translation.
Slides adapted from Bryant and O’Hallaron
CS 367 Linking Topics Static linking Make Utility Object files
Overview of today’s lecture
Linking Topics Static linking Object files Static libraries Loading
Linking & Loading.
Program Execution in Linux
CS-3013 Operating Systems C-term 2008
“The course that gives CMU its Zip!”
“The course that gives CMU its Zip!”
Linking.
Linking & Loading CS-502 Operating Systems
Program Execution in Linux
Linking & Loading CS-502 Operating Systems
Linking and Loading Professor Hugh C. Lauer CS-2011, Machine Organization and Assembly Language (Slides include copyright materials from Computer Systems:
Instructors: Majd Sakr and Khaled Harras
“The course that gives CMU its Zip!”
Presentation transcript:

Winter 2015 COMP 2130 Intro Computer Systems Computing Science Thompson Rivers University Linking

Course Objectives TRU-COMP2130 Linking 2 The better knowledge of computer systems, the better programing. Computer SystemC Programming Language Computer architecture CPU (Central Processing Unit) IA32 assembly language Introduction to C language Compiling, linking, loading, executing Physical main memory MMU (Memory Management Unit) Virtual memory space Memory hierarchy Cache Dynamic memory management Better coding – locality Reliable and efficient programming for power programmers (to avoid strange errors, to optimize codes, to avoid security holes, …) Your vision? Seek with all your heart?

3 Unit Contents Compiler Drivers Static Linking Object Files Relocatable Object Files Symbols and Symbol Tables Static Libraries Loading Executable Object Files Shared Libraries

4 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.

5 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 use shared libraries properly.

6 1. Compiler Drivers A compiler driver invokes the language preprocessor, compiler, assembler, and linker as needed on behalf of the user. The name of the compiler driver on our Linux box is gcc

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

Example C Program Carnegie Mellon The driver first runs the C preprocessor (cpp), which translates the C source file main.c into an ASCII intermediate file main.i: cpp [other arguments] main.c /tmp/main.i Next, the driver runs the C compiler (cc1), which translates main.i into an ASCII assembly language file main.s. cc1 /tmp/main.i main.c -O2 [other arguments] -o /tmp/main.s Then, the driver runs the assembler (as), which translates main.s into a relocatable object file main.o: as [other arguments] -o /tmp/main.o /tmp/main.s The driver goes through the same process to generate swap.o. Finally, it runs the linker program ld, which combines main.o and swap.o, along with the necessary system object files, to create the executable object file p: ld -o p [system object files and args] /tmp/main.o /tmp/swap.o

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 Linker (ld) Translators (cpp, cc1, as) main.c main.o Translators (cpp, cc1, as) swap.c swap.o p Source files Separately compiled relocatable object files Fully linked executable object file (contains code and data for all functions defined in main.c and swap.c ) Carnegie Mellon

10 2. Static Linking To build the executable, the linker must perform two main tasks: Symbol resolution. Object files define and reference symbols. The purpose of symbol resolution is to associate each symbol reference with exactly one symbol definition. Relocation. Compilers and assemblers generate code and data sections that start at address 0. The linker relocates these sections by associating a memory location with each symbol definition, and then modifying all of the references to those symbols so that they point to this memory location.

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 locations in 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 locations in the.o files to their final absolute memory locations in the executable. Updates all references to these symbols to reflect their new positions. 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. Carnegie Mellon

13 3. Object Files Object files come in three forms: Relocatable object file (.o file) Contains binary code and data in a form that can be combined with other relocatable object files at compile time 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

14 3. Object Files Compilers and assemblers generate relocatable object files (including shared object files). Linkers generate executable object files. Technically, an object module is a sequence of bytes, and an object file is an object module stored on disk in a file. However, we will use these terms interchangeably. Object file formats vary from system to system. Modern Unix systems - such as Linux, later versions of System V Unix, BSD Unix variants, and Sun Solaris - use the Unix Executable and Linkable Format (ELF). Although our discussion will focus on ELF, the basic concepts are similar, regardless of the particular format.

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. 15

16 4. Relocatable Object Files

Standard binary format for object files for Modern Unix systems 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 Carnegie Mellon Executable and Linkable Format (ELF)

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..text section Instruction code.rodata section Read only data: jump tables,....data section Initialized global variables.bss section Uninitialized global variables Has section header but occupies no space 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.text section Addresses of instructions that will need to be modified in the executable Instructions for modifying..rel.data section Relocation info for.data section 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 Carnegie Mellon

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. 20

21 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 static attribute. Local linker symbols are not local program variables.

Resolving Symbols int buf[2] = {1, 2}; int main() { swap(); return 0; } main.c extern int buf[]; int *bufp0 = &buf[0]; static int *bufp1; void swap() { int temp; bufp1 = &buf[1]; temp = *bufp0; *bufp0 = *bufp1; *bufp1 = temp; } swap.c Global External Local Global Carnegie Mellon

23 7. Relocation

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

Strong and Weak Symbols Program symbols are either strong or weak Strong: procedures and initialized globals Weak: uninitialized globals int foo=5; p1() { } int foo; p2() { } p1.cp2.c strong weak strong

Linker’s Symbol Rules Rule 1: Multiple strong symbols are not allowed Each item can be defined only once Otherwise: Linker error Rule 2: Given a strong symbol and multiple weak symbol, choose the strong symbol References to the weak symbol resolve to the strong symbol Rule 3: If there are multiple weak symbols, pick an arbitrary one Can override this with gcc –fno-common

Linker Puzzles int x; p1() {} int x; p2() {} int x; int y; p1() {} double x; p2() {} int x=7; int y=5; p1() {} double x; p2() {} int x=7; p1() {} int x; p2() {} int x; p1() {} Link time error: two strong symbols ( p1 ) References to x will refer to the same uninitialized int. Is this what you really want? Writes to x in p2 might overwrite y ! Evil! Writes to x in p2 will overwrite y ! Nasty! Nightmare scenario: two identical weak structs, compiled by different compilers with different alignment rules. References to x will refer to the same initialized variable.

Global Variables Avoid if you can Otherwise Use static if you can Initialize if you define a global variable Use extern if you use external global variable

29 Linking with Static Libraries

Packaging Commonly Used Functions 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 Carnegie Mellon

Solution: Static Libraries Static libraries (. a archive 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. Carnegie Mellon

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

Commonly Used Libraries 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 … Carnegie Mellon

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

Using Static Libraries 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' Carnegie Mellon

36 9. Loading Executable Object Files

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

Shared Libraries

Shared Libraries 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. Carnegie Mellon

Shared Libraries (cont.) 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. Carnegie Mellon

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

Dynamic Linking at Run-time #include 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); } Carnegie Mellon

Questions? Carnegie Mellon