Slides adapted from Bryant and O’Hallaron

Slides:



Advertisements
Similar presentations
Programs in Memory Bryce Boe 2012/08/29 CS32, Summer 2012 B.
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
Linker and Loader. Program building into four stages (C Program) Preprocessing (Preprocessor) It processes include files, conditional compilation instructions.
Linkers and Loaders 1 Linkers & Loaders – A Programmers Perspective.
Linking and Loading Fred Prussack CS 518. L&L: Overview Wake-up Questions Terms and Definitions / General Information LoadingLinking –Static vs. Dynamic.
Winter 2015 COMP 2130 Intro Computer Systems Computing Science Thompson Rivers University Linking.
Generating Programs and Linking Professor Rick Han Department of Computer Science University of Colorado at Boulder.
“The course that gives CMU its Zip!”
CS 330 What software engineers need to know about linking and a few things about execution.
Chapter 91 Memory Management Chapter 9   Review of process from source to executable (linking, loading, addressing)   General discussion of memory.
Linking and Loading Linker collects procedures and links them together object modules into one executable program. Why isn't everything written as just.
Topic 2d High-Level languages and Systems Software
© Janice Regan, CMPT 300, May CMPT 300 Introduction to Operating Systems Memory: Relocation.
CPS3340 COMPUTER ARCHITECTURE Fall Semester, /29/2013 Lecture 13: Compile-Link-Load Instructor: Ashraf Yaseen DEPARTMENT OF MATH & COMPUTER SCIENCE.
Linking Topics Static linking Dynamic linking Case study: Library interpositioning.
Linking Ⅱ.
Linking Alan L. Cox Some slides adapted from CMU slides.
Processes and Threads-I Static and dynamic linking, Loading, Anatomy of a Process.
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.
1 CS503: Operating Systems Spring 2014 Part 0: Program Structure Dongyan Xu Department of Computer Science Purdue University.
Chapter 13 : Symbol Management in Linking
Different Types of Libraries
Slides adapted from Bryant and O’Hallaron
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
CS252: Systems Programming Ninghui Li Based on Slides by Gustavo Rodriguez-Rivera Topic 2: Program Structure and Using GDB.
Linking I Topics Assembly and symbol resolution Static linking Systems I.
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.
Linking Winter 2013 COMP 2130 Intro Computer Systems Computing Science Thompson Rivers University.
Object Files & Linking. Object Sections Compiled code store as object files – Linux : ELF : Extensible Linking Format – Windows : PE : Portable Execution.
Binding & Dynamic Linking Presented by: Raunak Sulekh(1013) Pooja Kapoor(1008)
Program Execution in Linux David Ferry, Chris Gill CSE 522S - Advanced Operating Systems Washington University in St. Louis St. Louis, MO
Alan L. Cox Linking Alan L. Cox Some slides adapted from CMU slides.
Lecture 3 Translation.
Assemblers, linkers, loaders
Computer Architecture & Operations I
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.
Instructor: Randy Bryant
The University of Adelaide, School of Computer Science
Linking & Loading.
Linux Userspace Process Memory Layout
Separate Assembly allows a program to be built from modules rather than a single source file assembler linker source file.
143A: Principles of Operating Systems Lecture 8: Basic Architecture of a Program Anton Burtsev October, 2017.
Program Execution in Linux
CS-3013 Operating Systems C-term 2008
CS1010 Programming Methodology
Topic 2e High-Level languages and Systems Software
Generating Programs and Linking
“The course that gives CMU its Zip!”
Memory Allocation CS 217.
“The course that gives CMU its Zip!”
Memory Management Tasks
Linking.
Linking & Loading CS-502 Operating Systems
Virtual Memory: Systems CSCI 380: Operating Systems
Program Execution in Linux
10/6: Lecture Topics C Brainteaser More on Procedure Call
Linking & Loading CS-502 Operating Systems
Program Assembly.
Instructors: Majd Sakr and Khaled Harras
“The course that gives CMU its Zip!”
Presentation transcript:

Slides adapted from Bryant and O’Hallaron Linking Slides adapted from Bryant and O’Hallaron

Today Linking Libraries

Example C Program main.c sum.h #include ‘’sum.h’’ int array[2] = {1, 2}; int main() { int val = sum(array, 2); return val; } int sum(int *a, int n); sum.c #include “sum.h” int sum(int *a, int n) { int s = 0; for (int i = 0; i < n; i++) { s += a[i]; } return s;

Static Linking gcc normally does preprocessing, compilation and linking To compile (but not link): gcc -c main.c sum.c sum.h Source files compile gcc –c main.c compile gcc –c sum.c Separately compiled Re-locatable object files main.o sum.o Linker (ld) gcc main.o sum.o Fully linked executable file (contains code and data for all functions defined in main.c and sum.c) a.out

Why Linkers? Modula code & efficient compilation Program can be written as a collection of smaller source files Change one source file, compile that file only, and then relink. Support libraries (no source needed) Build libraries of common functions, other files link against libraries e.g., Math library, standard C library

What Do Linkers Do? Step 1: Symbol resolution Programs define and reference symbols (global variables and functions): void swap() {…} /* define symbol swap */ swap(); /* reference symbol swap */ int *xp = &x; /* define symbol xp, reference x */ Symbol definitions are stored in object file in symbol table. Each entry in symbol table includes name, size, and location of symbol. During symbol resolution step, the linker associates each symbol reference with exactly one symbol definition (i.e. the address of that symbol)

What Do Linkers Do? (cont) Step 2: Relocation Merges separate object files into a single binary executable file Relocates symbols from their relative locations in the .o files to their final absolute memory locations in the executable. Let’s look at these two steps in more detail….

Three Kinds of Object Files (Modules) Relocatable object file (.o file) Each .o file is produced from exactly one source (.c) file Executable object file (a.out file) 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

Executable and Linkable Format (ELF) Standard binary format for object files One unified format for Relocatable object files (.o), Executable object files (a.out) Shared object files (.so) Generic name: ELF binaries

ELF Object File Format Elf header .text section .rodata section file type (.o, exec, .so) ... .text section Code .rodata section Read only data .data section Initialized global variables .bss section Uninitialized global variables “Better Save Space” Has section header but occupies no space ELF header ... .text section .rodata section .data section .bss section .symtab section .rel.txt section .rel.data section .debug section ...

ELF Object File Format (cont.) .symtab section Symbol table (symbol name, type, address) .rel.text section Relocation info for .text section Addresses of instructions that will need to be modified in the executable .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) ELF header Segment header table (required for executables) .text section .rodata section .data section .bss section .symtab section .rel.txt section .rel.data section .debug section ...

Linker Symbols Global symbols External symbols Local symbols Symbols defined in an object file and can be referenced by others E.g.: non-static C functions and non-static global variables. External symbols Global symbols defined by other object files but referenced by this object file. Local symbols Symbols that are defined and referenced exclusively by module m. E.g.: C functions and global variables defined with the static attribute. Local linker symbols are not local program variables

Step 1: Symbol Resolution Referencing a global… …that’s defined here #include “sum.h” int array[2] = {1, 2}; int main() { int val = sum(array, 2); return val; } int sum(int *a, int n) { int i, s = 0; for (i = 0; i < n; i++) { s += a[i]; } return s; …that’s defined here Linker knows nothing of i or s Defining a global Linker knows nothing of val Referencing a global… main.c sum.c

How Linker Resolves Duplicate Symbol Definitions Program symbols are either strong or weak Strong: procedures and initialized globals Weak: uninitialized globals p1.c p2.c strong int foo=5; p1() { } int foo; p2() { } weak strong 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 symbols, 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 Link time error: two strong symbols (p1) int x; p1() {} p1() {} Link time error: two strong symbols (p1) int x; p1() {} int x; p2() {} References to x will refer to the same uninitialized int. Is this what you really want? int x; int y; p1() {} double x; p2() {} Writes to x in p2 might overwrite y! Evil! int x=7; int y=5; p1() {} double x; p2() {} Writes to x in p2 will overwrite y! Nasty! int x=7; p1() {} int x; p2() {} 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 reference an external global variable

Step 2: Relocation Relocatable Object Files Executable Object File Headers main() swap() More system code Executable Object File .text .symtab .debug .data System code System data int array[2]={1,2} System code .text .data System data main.o main() .text .data int array[2]={1,2} sum.o sum() .text

Relocation Entries int array[2] = {1, 2}; int main() { int val = sum(array, 2); return val; } main.c 0000000000000000 <main>: 0: 48 83 ec 08 sub $0x8,%rsp 4: be 02 00 00 00 mov $0x2,%esi 9: bf 00 00 00 00 mov $0x0,%edi # %edi = &array a: R_X86_64_32 array # Relocation entry e: e8 00 00 00 00 callq 13 <main+0x13> # sum() f: R_X86_64_PC32 sum-0x4 # Relocation entry 13: 48 83 c4 08 add $0x8,%rsp 17: c3 retq main.o Source: objdump –r –d main.o

Relocated .text section 00000000004004d0 <main>: 4004d0: 48 83 ec 08 sub $0x8,%rsp 4004d4: be 02 00 00 00 mov $0x2,%esi 4004d9: bf 18 10 60 00 mov $0x601018,%edi # %edi = &array 4004de: e8 05 00 00 00 callq 4004e8 <sum> # sum() 4004e3: 48 83 c4 08 add $0x8,%rsp 4004e7: c3 retq 00000000004004e8 <sum>: 4004e8: b8 00 00 00 00 mov $0x0,%eax 4004ed: ba 00 00 00 00 mov $0x0,%edx 4004f2: eb 09 jmp 4004fd <sum+0x15> 4004f4: 48 63 ca movslq %edx,%rcx 4004f7: 03 04 8f add (%rdi,%rcx,4),%eax 4004fa: 83 c2 01 add $0x1,%edx 4004fd: 39 f2 cmp %esi,%edx 4004ff: 7c f3 jl 4004f4 <sum+0xc> 400501: f3 c3 repz retq objdump -d a.out

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

Today Linking Libraries

How to package commonly used functions Strawman solutions: Put all functions into a single source file, programmers link against one big object file ✗ Inefficient linking Put each function in a separate source file, programmers explicitly link against appropriate object files. ✗ burdensome on the programmer Static libraries (.a archive files) Concatenate several object files together with an index (called an archive). ✗ Duplication in the running executable Dynamic libraries (.so files)

Dynamic linking: Shared Libraries 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). In Linux, this is done by calls to the dlopen() interface. Shared library routines can be shared by multiple processes. More on this when we learn about virtual memory

Dynamic Linking at Load-time main.c sum.h unix> gcc -shared -o libmysum.so \ sum.c myotherfunctions.c compile libc.so libmysum.so Relocatable object file main.o Relocation and symbol table info Linker (ld) Partially linked executable object file a.out Loader (execve) libc.so libmysum.so Code and data Fully linked executable in memory Dynamic linker (ld-linux.so)

Dynamic Linking at Run-time #include <stdio.h> #include <stdlib.h> #include <dlfcn.h> int array[2] = {1, 2}; int main() { void *handle; void (*sum)(int *, int); char *error; /* Dynamically load the shared library that contains sum() */ handle = dlopen("./libmysum.so", RTLD_LAZY); if (!handle) { fprintf(stderr, "%s\n", dlerror()); exit(1); } dll.c

Dynamic Linking at Run-time ... /* Get a pointer to the sum() function we just loaded */ sum = dlsym(handle, ”sum"); if ((error = dlerror()) != NULL) { fprintf(stderr, "%s\n", error); exit(1); } /* Now we can call sum() just like any other function */ int z = sum(array, 2); printf("z = %d \n", z); /* Unload the shared library */ if (dlclose(handle) < 0) { fprintf(stderr, "%s\n", dlerror()); return 0; dll.c

Linking Summary Linking is a technique that allows programs to be constructed from multiple object files. Linking can happen at different times in a program’s lifetime: Compile time (when a program is compiled) Load time (when a program is loaded into memory) Run time (while a program is executing) Understanding linking can help you avoid nasty errors and make you a better programmer.