COMS 4995 Advanced Systems Programming

Linking 2

Static library

Shared library


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 sum.o
gcc  -o main-dyn main.o

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

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

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, finds the sum_array() function, and calls it.

main-dlopen demo:

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

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 mymalloc.c && LD_PRELOAD=./  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)


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.


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:


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