COMS 4995 Advanced Systems Programming

Linking 2

Static library

Shared library

Motivation

Building and running a shared library

main-dyn demo:

$ # Object files that will go into a shared library must be compiled with -fpic.
$ # gcc -shared builds a shared library.
$ make
gcc -Wall -fpic   -c -o main.o main.c
gcc -Wall -fpic   -c -o sum.o sum.c
gcc -shared -o libsum.so sum.o
gcc  -o main-dyn main.o libsum.so

$ # Dynamic linker can't find our libsum shared library
$ ./main-dyn 
./main-dyn: error while loading shared libraries: libsum.so: cannot open shared object file: No such file or directory
$ ldd main-dyn
        linux-vdso.so.1 (0x00007ffc951cf000)
        libsum.so => not found
        libc.so.6 => /lib/x86_64-linux-gnu/libc.so.6 (0x00007f279d400000)
        /lib64/ld-linux-x86-64.so.2 (0x00007f279d74f000)

$ # Shared library must either be registered on the system or in LD_LIBRARY_PATH
$ LD_LIBRARY_PATH=. ./main-dyn 
sum=10

Loading & linking shared library using dlopen()

A shared library can be dynamically loaded and linked at runtime without previously having linked to it. The main-dlopen program dynamically links against libsum.so, finds the sum_array() function, and calls it.

main-dlopen demo:

$ # Note that we do not link against libsum.so
$ gcc -Wall  main-dlopen.c 
$ LD_LIBRARY_PATH=. ./a.out
sum=10

Library Interpositioning

We will use mymalloc.c, adapted from CSAPP Figure 7.22, to demonstrate a powerful technique called “library interpositioning”. The dynamic linker in Linux will load in shared objects specified in the LD_PRELOAD environment variable before all others. This feature can be used to override functions in other shared objects.

cal demo: Intercept malloc() and free() calls in the cal program:

$ gcc -fpic -shared -o mm.so mymalloc.c && LD_PRELOAD=./mm.so  cal
malloc wrapper called
free wrapper called
malloc wrapper called
malloc wrapper called
...
free wrapper called
malloc wrapper called
malloc wrapper called
     April 2024       
Su Mo Tu We Th Fr Sa  
    1  2  3  4  5  6  
 7  8  9 10 11 12 13  
14 15 16 17 18 19 20  
21 22 23 24 25 26 27  
28 29 30              
                      
free wrapper called

Position Independent Code (PIC)

Motivation

Referencing global data from shared objects

Global offset table (GOT) adds one level of indirection for global data. CSAPP Figure 7.18 demonstrates how PIC uses the GOT to reference global data from shared objects.

csapp-fig7.18

Referencing functions from shared objects

Procedure linkage table (PLT) & GOT together add two levels of indirection for global functions defined in shared objects. This is illustrated in CSAPP Figure 7.19:

csapp-fig7.19

PLT & GOT demo:

PIE vs Static/Dynamic linking

PIE and static/dynamic linkage are orthogonal concepts. Running file, ldd, and objdump on the following four executables demonstrates this point:


Last updated: 2024-04-09