LINKING. Jo, Heeseung

Similar documents
A Simplistic Program Translation Scheme

Systems I. Linking II

Computer Organization: A Programmer's Perspective

Linking Oct. 15, 2002

Linking Oct. 26, 2009"

CS429: Computer Organization and Architecture

Relocating Symbols and Resolving External References. CS429: Computer Organization and Architecture. m.o Relocation Info

(Extract from the slides by Terrance E. Boult

CS 201 Linking Gerson Robboy Portland State University

Linker Puzzles The course that gives CMU its Zip! Linking Mar 4, A Simplistic Program Translation Scheme. A Better Scheme Using a Linker

Systemprogrammering och operativsystem Laborationer. Linker Puzzles. Systemprogrammering 2007 Föreläsning 1 Compilation and Linking

Example C Program The course that gives CMU its Zip! Linking March 2, Static Linking. Why Linkers? Page # Topics

Linking February 24, 2005

Systems Programming and Computer Architecture ( ) Timothy Roscoe

CSE 2421: Systems I Low-Level Programming and Computer Organization. Linking. Presentation N. Introduction to Linkers

Lecture 16: Linking Computer Architecture and Systems Programming ( )

Exercise Session 7 Computer Architecture and Systems Programming

Example C program. 11: Linking. Why linkers? Modularity! Static linking. Why linkers? Efficiency! What do linkers do? 10/28/2013

Linking. Computer Systems Organization (Spring 2017) CSCI-UA 201, Section 3. Instructor: Joanna Klukowska

Computer Systems. Linking. Han, Hwansoo

Example C Program. Linking CS Instructor: Sanjeev Se(a. int buf[2] = {1, 2}; extern int buf[]; int main() { swap(); return 0; }

E = 2 e lines per set. S = 2 s sets tag. valid bit B = 2 b bytes per cache block (the data) CSE351 Inaugural EdiNon Spring

Linking and Loading. CS61, Lecture 16. Prof. Stephen Chong October 25, 2011

Outline. 1 Background. 2 ELF Linking. 3 Static Linking. 4 Dynamic Linking. 5 Summary. Linker. Various Stages. 1 Linking can be done at compile.

Linking. Today. Next time. Static linking Object files Static & dynamically linked libraries. Exceptional control flows

Revealing Internals of Linkers. Zhiqiang Lin

Systemprogrammering och operativsystem Linker Puzzles. Systemprogrammering 2009 Före lä s n in g 1 Compilation and Linking

Lecture 12-13: Linking

COMPILING OBJECTS AND OTHER LANGUAGE IMPLEMENTATION ISSUES. Credit: Mostly Bryant & O Hallaron

Sungkyunkwan University

CS241 Computer Organization Spring Buffer Overflow

u Linking u Case study: Library interpositioning

Computer Systems Organization

CS 550 Operating Systems Spring Process I

CSE2421 Systems1 Introduction to Low-Level Programming and Computer Organization

238P: Operating Systems. Lecture 7: Basic Architecture of a Program. Anton Burtsev January, 2018

A SimplisHc Program TranslaHon Scheme. TranslaHng the Example Program. Example C Program. Why Linkers? - Modularity. Linking

Today. Linking. Example C Program. Sta7c Linking. Linking Case study: Library interposi7oning

Compiler Drivers = GCC

Generating Programs and Linking. Professor Rick Han Department of Computer Science University of Colorado at Boulder

Carnegie Mellon. Bryant and O Hallaron, Computer Systems: A Programmer s Perspective, Third Edition

Link 7. Static Linking

Executables and Linking. CS449 Spring 2016

Assembly Language Programming Linkers

Link 7.A Static Linking

Link 2. Object Files

CS5460/6460: Operating Systems. Lecture 21: Shared libraries. Anton Burtsev March, 2014

Linkers and Loaders. CS 167 VI 1 Copyright 2008 Thomas W. Doeppner. All rights reserved.

Executables and Linking. CS449 Fall 2017

CIT 595 Spring System Software: Programming Tools. Assembly Process Example: First Pass. Assembly Process Example: Second Pass.

M2 Instruction Set Architecture

Linking. CS 485 Systems Programming Fall Instructor: James Griffioen

Linking. Explain what ELF format is. Explain what an executable is and how it got that way. With huge thanks to Steve Chong for his notes from CS61.

Link 2. Object Files

CS 33. Linkers. CS33 Intro to Computer Systems XXV 1 Copyright 2017 Thomas W. Doeppner. All rights reserved.

Midterm. Median: 56, Mean: "midterm.data" using 1:2 1 / 37

Link 3. Symbols. Young W. Lim Mon. Young W. Lim Link 3. Symbols Mon 1 / 42

Linking and Loading. ICS312 - Spring 2010 Machine-Level and Systems Programming. Henri Casanova

Introduction Selected details Live demos. HrwCC. A self-compiling C-compiler. Stefan Huber Christian Rathgeb Stefan Walkner

Introduction Presentation A

Program Translation. text. text. binary. binary. C program (p1.c) Compiler (gcc -S) Asm code (p1.s) Assembler (gcc or as) Object code (p1.

Lecture 8: linking CS 140. Dawson Engler Stanford CS department

Linking : Introduc on to Computer Systems 13 th Lecture, October 11th, Instructor: Randy Bryant. Carnegie Mellon

CSC 2400: Computing Systems. X86 Assembly: Function Calls"

CPEG421/621 Tutorial

CMSC 313 COMPUTER ORGANIZATION & ASSEMBLY LANGUAGE PROGRAMMING PREVIEW SLIDES 16, SPRING 2013

CSC 2400: Computing Systems. X86 Assembly: Function Calls

Turning C into Object Code Code in files p1.c p2.c Compile with command: gcc -O p1.c p2.c -o p Use optimizations (-O) Put resulting binary in file p

1 /* file cpuid2.s */ 4.asciz "The processor Vendor ID is %s \n" 5.section.bss. 6.lcomm buffer, section.text. 8.globl _start.

Compiler, Assembler, and Linker

CS2141 Software Development using C/C++ Libraries

Link 4. Relocation. Young W. Lim Wed. Young W. Lim Link 4. Relocation Wed 1 / 22

Instruction Set Architectures

Machine Programming 1: Introduction

CSL373: Operating Systems Linking

Link Edits and Relocatable Code

Computer Systems Architecture I. CSE 560M Lecture 3 Prof. Patrick Crowley

High Performance Computing Lecture 1. Matthew Jacob Indian Institute of Science

Compila(on, Disassembly, and Profiling

Operating Systems CMPSC 473. Process Management January 29, Lecture 4 Instructor: Trent Jaeger

CMSC 313 Lecture 12 [draft] How C functions pass parameters

Draft. Chapter 1 Program Structure. 1.1 Introduction. 1.2 The 0s and the 1s. 1.3 Bits and Bytes. 1.4 Representation of Numbers in Memory

Homework. In-line Assembly Code Machine Language Program Efficiency Tricks Reading PAL, pp 3-6, Practice Exam 1

A software view. Computer Systems. The Compilation system. How it works. 1. Preprocesser. 1. Preprocessor (cpp)

Function Calls and Stack Allocation

Deadlock Detection. Several Instances of a Resource Type. Single Instance of Each Resource Type

Instruction Set Architectures

CS 61C: Great Ideas in Computer Architecture CALL continued ( Linking and Loading)

238P: Operating Systems. Lecture 4: Linking and Loading (Basic architecture of a program) Anton Burtsev October, 2018

Assembly I: Basic Operations. Jo, Heeseung

Assembly Programmer s View Lecture 4A Machine-Level Programming I: Introduction

Intel assembly language using gcc

Binghamton University. CS-220 Spring Loading Code. Computer Systems Chapter 7.5, 7.8, 7.9

ASSEMBLY I: BASIC OPERATIONS. Jo, Heeseung

Function Calls and Stack Allocation

Stack. Stack. Function Calls and Stack Allocation. Stack Popping Popping. Stack Pushing Pushing. Page 1

Outline. Unresolved references

Link 4. Relocation. Young W. Lim Thr. Young W. Lim Link 4. Relocation Thr 1 / 26

Process Environment. Pradipta De

CS140 - Summer Handout #8

Transcription:

LINKING Jo, Heeseung

PROGRAM TRANSLATION (1) A simplistic program translation scheme m.c ASCII source file Translator p Binary executable object file (memory image on disk) Problems: - Efficiency: small change requires complete recompilation - Modularity: hard to share common functions (e.g. printf) Solution: - Static linker (or linker) 2

PROGRAM TRANSLATION (2) A better scheme using a linker m.c a.c Translators Translators m.o a.o Separately compiled relocatable object files Linker (ld) p Executable object file (contains code and data for all functions defined in m.c and a.c) 3

PROGRAM TRANSLATION (3) Compiler driver coordinates all steps in the translation and linking process Typically included with each compilation system (gcc) Invokes preprocessor (cpp), compiler (cc1), assembler (as), and linker (ld) Passes command line arguments to appropriate phases Example: create executable p from main.c and swap.c $ gcc -O2 -v -o p main.c swap.c cpp [args] main.c /tmp/main.i cc -S /tmp/main.i -O2 [args] -o /tmp/main.s as [args] -o /tmp/main.o /tmp/main.s <similar process for swap.c> ld -o p [system obj files] /tmp/main.o /tmp/swap.o $ 4

LINKER (1) Why linkers? Modularity - Program can be written as a collection of smaller source files, rather than one monolithic mass - Can build libraries of common functions e.g., math library, standard C library Efficiency in time - Change one source file, compile, and then relink - No need to recompile other source files - e.g., Linux kernel, MySQL,... Efficiency in space - Libraries of common functions can be aggregated into a single file (storage space) - Yet executable files and running memory image contain only code for the functions they actually use (memory space) 6

LINKER (2) What does a linker do? Merges object files - Multiple relocatable (.o) object files -> a single executable object file that can loaded and executed by the loader Resolves external references - External reference: reference to a symbol defined in another object file Relocates symbols - Relocates symbols from their relative locations in the.o files to new absolute positions in the executable - Updates all references to these symbols to reflect their new positions - References can be in either code or data: code: func(); // reference to symbol func data: int *xp = &x; // reference to symbol x 7

ELF (1) Executable and Linkable Format Standard library format for object files Derived from AT&T System V Unix - Later adopted by BSD Unix variants and Linux One unified format for - Relocatable object files (.o) - Executable object files - Shared object files (.so) Generic name: ELF binaries Better support for shared libraries than old a.out formats 8

ELF (2) ELF object file format ELF header - Magic number (\177ELF), type (.o, exec,.so), machine, byte ordering, etc. Program header table - Page size, virtual addresses memory segments (sections), segment sizes.text section - Code.data section - Initialized (static) data.bss section - Uninitialized (static) data - Better for space saving - Has section header but occupies no space ELF header Program header table (required for executables).text section.data section.bss section.symtab.rel.text.rel.data.debug Section header table (required for relocatables) 9

ELF (3) ELF object file format (cont'd).symtab section - Symbol table - Procedures and static variable names - Section names and locations.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) ELF header Program header table (required for executables).text section.data section.bss section.symtab.rel.text.rel.data.debug Section header table (required for relocatables) 10

LOADING EXECUTABLE BINARIES Executable object file for example program p ELF header Program header table (required for executables).text section 0 Process image init and shared lib segments Virtual addr 0x080483e0.data section.bss section.symtab.text segment (r/o) 0x08048494.rel.text.rel.data.data segment (initialized r/w) 0x0804a010.debug Section header table (required for relocatables).bss segment (uninitialized r/w) 0x0804a3b0 11

LINKING EXAMPLE (1) Example C program m.c int e=7; int main() { int r = a(); exit(0); } a.c extern int e; int *ep=&e; int x=15; int y; int a() { return *ep+x+y; } 12

LINKING EXAMPLE (2) Relocating symbols and resolving external references Symbols are lexical entities that name functions and variables Each symbol has a value (typically a memory address) Code consists of symbol definitions and references References can be either local or external Def of local symbol e m.c Ref to external symbol exit (defined in libc.so) int e=7; int main() { int r = a(); exit(0); } Ref to external symbol a Def of local symbol ep extern int e; int *ep=&e; int x=15; int y; int a() { return *ep+x+y; } Def of local symbol a a.c Ref to external symbol e Defs of local symbols x and y 13

LINKING EXAMPLE (3) m.o object file m.c int e=7; int main() { int r = a(); exit(0); } readelf -r m.o Disassembly of section.text: 00000000 <main>: 0: 55 pushl %ebp 1: 89 e5 movl %esp,%ebp 3: e8 fc ff ff ff call 4 <main+0x4> 8: 6a 00 pushl $0x0 a: e8 f5 ff ff ff call b <main+0xb> f: 90 nop Disassembly of section.data: 00000000 <e>: 0: 07 00 00 00 Relocation section [.rel.text]: 00000004 R_386_PC32 a 0000000b R_386_PC32 exit 14

LINKING EXAMPLE (4) a.o object file readelf -r a.o ep Disassembly of section.text: a.c extern int e; int *ep=&e; int x=15; int y; int a() { return *ep+x+y; } 00000000 <a>: 0: 55 pushl %ebp 1: 8b 15 00 00 00 00 movl 0x0,%edx 7: a1 00 00 00 00 movl 0x0,%eax c: 89 e5 movl %esp,%ebp e: 03 02 addl (%edx),%eax 10: 89 ec movl %ebp,%esp 12: 03 05 00 00 00 00 addl 0x0,%eax 18: 5d popl %ebp 19: c3 ret Disassembly of section.data: 00000000 <ep>: 0: 00 00 00 00 00000004 <x>: 4: 0f 00 00 00 y x Relocation section [.rel.data]: 00000000 R_386_32 e 15

LINKING EXAMPLE (6) Merging relocatable object files into an executable object file Relocatable Object Files system code.text system data.data Executable Object File 0 headers system code main().text m.o main() int e = 7.text.data a() more system code a.o a() int *ep = &e int x = 15 int y.text.data.bss system data int e = 7 int *ep = &e int x = 15 uninitialized data.symtab.debug.data.bss 16

LINKING EXAMPLE (7) After relocation and external reference resolution Disassembly of section.data: 0804a018 <e>: 804a018: 07 00 00 00 08048530 <main>: 8048530: 55 pushl %ebp 8048531: 89 e5 movl %esp,%ebp 8048533: e8 08 00 00 00 call 8048540 <a> 8048538: 6a 00 pushl $0x0 804853a: e8 35 ff ff ff call 8048474 <_init+0x94> 804853f: 90 nop 08048540 <a>: 8048540: 55 pushl %ebp 8048541: 8b 15 1c a0 04 08 movl 0x804a01c,%edx 8048547: a1 20 a0 04 08 movl 0x804a020,%eax 804854c: 89 e5 movl %esp,%ebp 804854e: 03 02 addl (%edx),%eax 8048550: 89 ec movl %ebp,%esp 8048552: 03 05 d0 a3 04 08 addl 0x804a3d0,%eax 8048558: 5d popl %ebp 8048559: c3 ret 0804a01c <ep>: 804a01c: 18 a0 04 08 0804a020 <x>: 804a020: 0f 00 00 00 15 ep x m.c int e=7; int main() { int r = a(); exit(0); } a.c extern int e; int *ep=&e; int x=15; int y; int a() { return *ep+x+y; } y return value 17

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

SYMBOL RESOLUTION (2) Linker's symbol rules Rule 1: A strong symbol can only appear once Rule 2: A weak symbol can be overridden by a strong symbol of the same name Rule 3: If there are multiple weak symbols, the linker can pick an arbitrary one 19

SYMBOL RESOLUTION (3) Examples int x; p1(){} int x; p1(){} int x; int y; p1(){} int x=7; int y=5; p1(){} int x=7; p1(){} p1(){} int x; p2(){} double x; p2(){} double x; p2(){} int x; p2(){} 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! References to x will refer to the same initialized variable 20

STATIC LIBRARIES (1) Packaging commonly used functions How to package functions commonly used by programmers? - Math, I/O, memory management, string manipulation, etc. Option 1: Put all functions in 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 21

STATIC LIBRARIES (2) Solution: 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 into executable Further improves modularity and efficiency by packaging commonly used functions - e.g. C standard library (libc), math library (libm), etc. 22

STATIC LIBRARIES (3) Creating static libraries Archiver (ar) allows incremental updates: - Recompile function that changes and replace.o file in archive atoi.c printf.c random.c Translator Translator... Translator atoi.o printf.o random.o Archiver (ar) ar rs libc.a \ atoi.o printf.o random.o libc.a C standard library 23

STATIC LIBRARIES (4) Mechanism Link selectively only the.o files in the archive that are actually needed by the program random.o p1.c p2.c printf.o... Translator Translator atoi.o p1.o p2.o Linker (ld) libc.a static library (archive) of relocatable object files concatenated into one file. p executable object file (only contains code and data for libc functions that are called from p1.c and p2.c) 24

STATIC LIBRARIES (5) Commonly used libraries libc.a (C standard library) - 8MB archive of 900 object files - I/O, memory allocation, signal handling, string handling, data and time, random numbers, integer math, etc. libm.a (C math library) - 1MB archive of 226 object files - Floating point math (sin, cos, tan, log, exp, sqrt, etc.) % ar -t /usr/lib/libc.a sort fork.o fprintf.o fputc.o freopen.o % ar -t /usr/lib/libm.a sort e_acos.o e_acosf.o e_acosh.o e_acoshf.o 25

STATIC LIBRARIES (6) 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 unresolved references - As each new.o or.a file is encountered, try to resolve each unresolved reference in the list against the symbols in the object file - 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 bass> gcc -L. -lmine libtest.o libtest.o: In function `main': libtest.o(.text+0x4): undefined reference to `libfun' bass> gcc -L. libtest.o -lmine 26

SHARED LIBRARIES (1) Static libraries have the following disadvantages: Potential for duplicating lots of common code in the executable files on a filesystem - e.g., every C program needs the standard C library Potential for duplicating lots of code in the virtual memory space of many processes Minor bug fixes of system libraries require each application to explicitly relink P1 P2 User Code1 printf.o User Code2 printf.o 27

SHARED LIBRARIES (2) Solution: shared libraries Dynamic link libraries or DLLs Members are dynamically loaded into memory and linked into an application at run-time Dynamic linking can occur... - When executable is first loaded and run Common case for Linux, handled automatically by ld-linux.so - Also after program has begun In Linux, this is done explicitly by user with dlopen() Basis for high-performance web servers Shared library routines can be shared by multiple processes P1 P2 User Code1 printf.o User Code2 printf.o printf.o 28

SHARED LIBRARIES (3) m.c a.c Translators (cc1, as) Translators (cc1,as) m.o a.o Linker (ld) Partially linked executable p (on disk) p libc.so Shared library of dynamically relocatable object files Fully linked executable p' (in memory) Loader/Dynamic Linker (ld-linux.so) P' libc.so functions called by m.c and a.c are loaded, linked, and (potentially) shared among processes 29

THE COMPLETE PICTURE m.c a.c Translator Translator m.o a.o libwhatever.a Static Linker (ld) p libc.so libm.so Loader/Dynamic Linker (ld-linux.so) p' 30