Cheat Sheet - Linux: /linux/ - CLI: /linux/cli/ - locate vs type vs which vs whereis: /linux/cli/locate-vs-type-vs-which-vs-whereis/ - make: /linux/cli/make/ - awk: /linux/cli/awk/ - find: /linux/cli/find/ - grep: /linux/cli/grep/ - pgrep: /linux/cli/pgrep/ - ps: /linux/cli/ps/ - pstree: /linux/cli/pstree/ - trap: /linux/cli/trap/ - xargs: /linux/cli/xargs/ - Shell: /linux/shell/ - BASH_SOURCE: /linux/shell/bash-source/ - Redirection: /linux/shell/redirection/ - Special Variables: /linux/shell/special-variables/ - Scripting Tips: /linux/shell/script-tips/ - set -o vi: /linux/shell/bash-vi-mode/ - Shell Processing Order: /linux/shell/process-order/ - What are Interactive and Login Shells?: /linux/shell/interactive-login/ - Double Quote Expansion: /linux/shell/shell-expansion/ - System Programming: /linux/system-programming/ - File I/O: /linux/system-programming/file-io/ - Process: /linux/system-programming/process/ - Shared Libraries: /linux/system-programming/shared-libraries/ - Kernel: /linux/kernel/ - Go: /programming/go/ - Concurrency: /programming/go/concurrency/ - CSP (Communicating Sequential Processes) and Channels: /programming/go/concurrency/csp/ - Channel: /programming/go/concurrency/channel/ - Select: /programming/go/concurrency/select/ - sync: /programming/go/concurrency/sync/ - Concurrency Patterns: /programming/go/concurrency/patterns/ - Goroutines and the Go Runtime: /programming/go/concurrency/runtime/ - Standard Library: /programming/go/std/ - os: /programming/go/std/os/ - context: /programming/go/std/context/ - io: /programming/go/std/io/ - json: /programming/go/std/json/ - net/http: /programming/go/std/net-http/ - slog: /programming/go/std/slog/ - testing: /programming/go/std/testing/ - time: /programming/go/std/time/ - Ellipsis (...): /programming/go/ellipsis/ - error: /programming/go/error/ - Function: /programming/go/function/ - Go Tool: /programming/go/tool/ - Interface: /programming/go/interface/ - Map: /programming/go/map/ - Package and Module: /programming/go/package-module/ - Pointer: /programming/go/pointer/ - Slice: /programming/go/slice/ - String: /programming/go/string/ - Switch: /programming/go/switch/ - Comparison: /programming/go/comparison/ - defaultdict: /programming/python/collections/defaultdict/ - heapq: /programming/python/collections/heapq/ - @cache: /programming/python/cache/ - abc: /programming/python/abc/ - bisect: /programming/python/bisect/ - Type Hints: /programming/python/type-hints/ - Passing Mechanism: /programming/python/passing-mechanism/ - uv: /programming/python/uv/ - *args and **kwargs: /programming/python/args-kwargs/ - re: /programming/python/re/ - C: /programming/c/ - Pointers and Arrays: /programming/c/pointer/ - Syntax Basics: /programming/c/syntax-basics/ - static: /programming/c/static/ - Bit Manipulation: /programming/c/bit-manipulation/ - C vs C++: /programming/c/c-vs-cpp/ - stdatomic: /programming/c/stdatomic/ - C++: /programming/cpp/ - RAII (Resource Acquisition Is Initialization): /programming/cpp/raii/ - Copy Elision & Move Semantics: /programming/cpp/copy-elision-and-move-semantics/ - Most Vexing Parse & In-Class Initializer: /programming/cpp/most-vexing-parse/ - C++ Keywords Reference: /programming/cpp/keywords/ - C++ Primer: /programming/cpp/primer/ - Variables and Basic Types: /programming/cpp/primer/variables-and-basic-types/ - Expressions: /programming/cpp/primer/expressions/ - Type Conversions and Casts: /programming/cpp/primer/type-conversions-and-casts/ - Statements: /programming/cpp/primer/statements/ - Functions: /programming/cpp/primer/functions/ - Classes: /programming/cpp/primer/classes/ - The IO Library: /programming/cpp/primer/io-library/ - STL: /programming/cpp/primer/stl/ - Lambda Expressions: /programming/cpp/primer/lambda/ - Smart Pointers: /programming/cpp/primer/smart-pointers/ - Copy Control: /programming/cpp/primer/copy-control/ - Overloaded Operations and Conversions: /programming/cpp/primer/operator-overloading/ - Object-Oriented Programming (OOP): /programming/cpp/primer/oop/ - Templates and Generic Programming: /programming/cpp/primer/templates/ - Namespaces: /programming/cpp/primer/namespaces/ - Pointers to Class Member: /programming/cpp/primer/pointers-to-class-member/ - Advanced: /programming/cpp/advanced/ - Error Handling: /programming/cpp/advanced/error-handling/ - Concurrency & Threading: /programming/cpp/advanced/concurrency/ - Unit Testing: /programming/cpp/advanced/unit-testing/ - Comparison: /programming/comparison/ - Kubernetes: /cloud-devops/kubernetes/ - Fleet: /cloud-devops/kubernetes/gke/fleet/ - Kustomize vs Helm: /cloud-devops/kubernetes/kustomize-vs-helm/ - API Extension: /cloud-devops/kubernetes/api-extension/ - Concept: /cloud-devops/kubernetes/kueue/concept/ - DRA: /cloud-devops/kubernetes/dra/ - Secret Manager: /cloud-devops/terraform/google-secret-manager/ - Knowledge: /network/knowledge/ - PDU: /network/knowledge/osi-model/ - curl: /network/cli/curl/ - Concurrency Concepts: /cs/concurrency-and-parallelism/concepts/ - Concurrency vs Parallelism: /cs/concurrency-and-parallelism/concurrency-vs-parallelism/ - Mutex vs Atomic: /cs/concurrency-and-parallelism/mutex-vs-atomic/ - Regular Expression: /cs/regular-expression/ - Multiplexer vs Dispatcher: /cs/multiplexer-vs-dispatcher/ - Driver and Runtime: /ai-ml/gpu/driver-and-runtime/ - Serving: /ai-ml/serving/ - Dotfiles: /dotfiles/ - Git: /dotfiles/git/ - Cheat Sheet: /dotfiles/git/cheat-sheet/ - revisions: /dotfiles/git/revisions/ - Submodule vs Worktree: /dotfiles/git/submodule-vs-worktree/ - checkout, reset -> switch, restore: /dotfiles/git/checkout-switch-restore-reset/ - rebase: /dotfiles/git/rebase/ - Branching and Merging: /dotfiles/git/branching-merging/ - Vim: /dotfiles/vim/ - Plugin: /dotfiles/vim/plugin/ - auto-pairs: /dotfiles/vim/plugin/auto-pairs/ - vim-commentary: /dotfiles/vim/plugin/vim-commentary/ - vim-easymotion: /dotfiles/vim/plugin/vim-easymotion/ - vim-surround: /dotfiles/vim/plugin/vim-surround/ - Marks: /dotfiles/vim/tips/marks/ - vimrc: /dotfiles/vim/vimrc/ - lf: /dotfiles/lf/ Based on *The Linux Programming Interface* Chapter 41 (Fundamentals of Shared Libraries) and Chapter 42 (Advanced Features of Shared Libraries). # Shared Libraries --- ## 1. Header vs Static vs Shared Library (TLPI Ch 41) C libraries (eg. `glibc`) separate compile-time declarations from link-time and runtime binaries. | Artifact | Extension & Example Path | Role | Phase | | :--- | :--- | :--- | :--- | | **Header** | `.h` (`/usr/include/dlfcn.h`) | Plain-text function signatures, types, and macros | Compile time (`gcc -c`) | | **Static Library** | `.a` (`libc.a`) | Archive of `.o` object files copied directly into the executable | Link time (`gcc -static`) | | **Shared Library** | `.so` (`/lib/x86_64-linux-gnu/libc.so.6`) | Precompiled Position-Independent machine code loaded once into memory and shared across processes | Runtime (`ld.so` dynamic linker) | ### Building and Inspecting Shared Libraries ```bash $ gcc -fPIC -shared -Wall -o libfoo.so foo.c $ ldd $ nm -D libfoo.so ``` - `-fPIC`: Generate Position-Independent Code so the library can be mapped at any virtual address - `-shared`: Produce a shared object (`.so`) instead of an executable requiring `main` - `ldd`: List shared libraries required by a binary and their resolved paths - `nm -D`: Inspect exported dynamic symbols in a `.so` file --- ## 2. Dynamic Loading API: `dlopen` & `dlsym` (TLPI Ch 42) `glibc` API for loading shared libraries into memory and resolving symbol addresses dynamically **at runtime** rather than at program startup (`man 3 dlopen`, `man 3 dlsym`). The **`RTLD_`** prefix stands for **R**un-**T**ime **L**ink-**D**ynamic. ```c #include void *dlopen(const char *filename, int flags); void *dlsym(void *restrict handle, const char *restrict symbol); int dlclose(void *handle); char *dlerror(void); ``` - **Linker Flag**: Link with `-ldl` for portability across older `glibc` releases (merged into `libc.so.6` since `glibc` 2.34) ### 1. `dlopen`: Opening a Library - ``: Path or soname of the `.so` file to open (`NULL` returns a handle to the main program's global symbol scope) - `` (resolution mode required): - `RTLD_LAZY`: Resolve function symbols lazily on first call - `RTLD_NOW`: Resolve all undefined symbols immediately before `dlopen` returns - `RTLD_GLOBAL`: Make loaded symbols available for symbol resolution of subsequently loaded libraries - **Return Value**: Opaque `handle` pointer on success, or `NULL` on failure (inspect reason via `dlerror()`) ### 2. `dlsym`: Resolving Function and Variable Addresses - ``: Target scope for symbol lookup — either a `handle` returned by `dlopen` or one of the following **pseudo-handles** (requires `#define _GNU_SOURCE`): - **`RTLD_DEFAULT`**: Search using the default library load order starting from the first loaded object - **`RTLD_NEXT`**: Search **starting from the library loaded after the current one**. Used inside an interposed wrapper function to find and delegate to the original implementation. - ``: Null-terminated symbol name string (eg. `"cuMemAlloc_v2"`) - **Return Value**: Virtual memory address (`void *`) of the symbol. Because no type metadata is stored, the caller must know and cast to the exact function pointer signature. ### 3. `dlerror`: Shared Error Buffer Inspection and Reset `dlopen`, `dlsym`, `dlvsym`, and `dlclose` all share a **single per-thread error buffer**. Calling `dlerror()` both 1) returns the most recent error message string and 2) clears that internal buffer (returning `NULL` if no error is pending). ```c void *handle = dlopen("libcuda.so.1", RTLD_LAZY); if (!handle) { // Entered only when dlopen fails; if dlopen succeeds, an older stale error may still sit in the buffer fprintf(stderr, "dlopen failed: %s\n", dlerror()); exit(EXIT_FAILURE); } dlerror(); // Step 1: Clear any stale error left in the shared buffer typedef int (*cuInit_fn)(unsigned int); cuInit_fn fn = (cuInit_fn) dlsym(handle, "cuInit"); // Step 2: Look up symbol address char *err = dlerror(); // Step 3: Check whether Step 2 recorded an error if (err != NULL) { fprintf(stderr, "dlsym failed: %s\n", err); exit(EXIT_FAILURE); } int rc = fn(0); dlclose(handle); ``` {{% hint info %}} Because a valid symbol address can legitimately be `0` (`NULL`) and an earlier unchecked call may have left a stale message in the shared buffer, POSIX specifies the three-step sequence (`dlerror()` reset -> `dlsym()` -> `dlerror()` check) rather than testing `fn == NULL`. {{% /hint %}} --- ## 3. Symbol Interposition: Pairing `LD_PRELOAD` with `RTLD_NEXT` The dynamic linker (`ld-linux.so`) resolves symbols using the **first loaded library (1st in load order)** that defines them. Symbol interposition pairs two mechanisms: **`LD_PRELOAD` injects a wrapper `.so` into the 1st slot to intercept calls**, and **`dlsym(RTLD_NEXT, ...)` inside that wrapper locates the displaced original function in the 2nd slot** to delegate the real work. ```text App calls malloc(64) │ ▼ [1st in load order — injected via LD_PRELOAD or /etc/ld.so.preload] libhook.so : malloc() <-- Interposed wrapper runs first │ │ dlsym(RTLD_NEXT, "malloc") --> "Search libraries loaded AFTER libhook.so" ▼ [2nd in load order — original shared library] libc.so.6 : malloc() <-- Delegates to original glibc implementation ``` ### 1. Preload Injection Mechanisms | Mechanism | Scope | Characteristics | | :--- | :--- | :--- | | **`LD_PRELOAD`** | Process environment variable | Convenient for single commands (`$ LD_PRELOAD=./libhook.so ./app`). Can be cleared by child processes and ignored on setuid binaries | | **`/etc/ld.so.preload`** | System/container-wide file | Forces `ld.so` to preload listed `.so` paths into the 1st slot of **every process**. Cannot be bypassed by clearing `environ` (used by container GPU limiters such as [HAMi Device Plugin `server.go#L1603-L1608`](https://github.com/Project-HAMi/HAMi/blob/48e0977c0bfc08c76e3ad1269a79b822ff754eb7/pkg/device-plugin/nvidiadevice/nvinternal/plugin/server.go#L1603-L1608)) | ### 2. Function Wrapping with `LD_PRELOAD` + `RTLD_NEXT` ```c #define _GNU_SOURCE #include #include typedef void *(*malloc_fn)(size_t); void *malloc(size_t size) { static malloc_fn real_malloc = NULL; // Caches address of displaced original malloc if (real_malloc == NULL) { real_malloc = (malloc_fn) dlsym(RTLD_NEXT, "malloc"); } void *p = real_malloc(size); write(STDERR_FILENO, "[hook] malloc called\n", 21); return p; } ``` ```bash $ gcc -fPIC -shared -Wall -o libhook.so hook.c -ldl $ LD_PRELOAD=./libhook.so ls ``` - **Infinite Recursion Hazard**: Never call `printf` inside a `malloc` hook. Because `glibc`'s `printf` internally calls `malloc` to allocate its output buffer, calling `printf` triggers infinite recursion (`malloc -> printf -> malloc`) and crashes with a stack overflow. Use allocation-free system calls such as `write(2)` instead. ### 3. `dlvsym` and Hooking `dlsym` Itself When a runtime (eg. CUDA `libcudart.so`) resolves driver symbols dynamically via `dlsym(handle, "cuMemAlloc_v2")` rather than direct symbol imports, ordinary function wrappers are bypassed and **`dlsym` itself must be interposed**. Calling `dlsym(RTLD_NEXT, "dlsym")` inside the fake `dlsym` triggers **infinite recursion** back into the 1st-slot fake `dlsym`. Use `dlvsym` to bootstrap the real `dlsym` pointer instead (eg. [HAMi-core `libvgpu.c#L55-L61`](https://github.com/Project-HAMi/HAMi-core/blob/8417257eecce03ae34d1711bf47002d70b5bfc12/src/libvgpu.c#L55-L61)): ```c #define _GNU_SOURCE #include void *dlvsym(void *restrict handle, const char *restrict symbol, const char *restrict version); ``` - `dlvsym`: Looks up a symbol matching both name and `glibc` symbol version string (eg. `"GLIBC_2.2.5"` on x86_64, `"GLIBC_2.17"` on aarch64). - Because its function name differs from `dlsym`, it is not intercepted by the fake `dlsym` and safely retrieves `libc.so.6`'s original `dlsym` address. ```bash $ objdump -T /lib/x86_64-linux-gnu/libc.so.6 | grep ' dlsym$' ```