TExcelTAD
Home › Reverse Engineering & Binary Analysis › Instrumentation: LD_PRELOAD, Frida, DynamoRIO, Pin and eBPF

Instrumentation: LD_PRELOAD, Frida, DynamoRIO, Pin and eBPF

Debuggers stop a program; tracers watch its boundary with the kernel and libraries. Instrumentation goes further: it inserts your own code into the running program, at function entries, at every basic block, or at every instruction, to log arguments, measure coverage, change return values or record a full execution trace. It is how fuzzers measure coverage, how mobile-app analysts inspect encrypted traffic before it is encrypted, and how EDR products watch processes. This lesson runs two instrumentation methods on the course's toys (library interposition with LD_PRELOAD, and compile-time instrumentation) and shows the big frameworks as labelled lab transcripts.

The methods

Method How code gets in Granularity Typical use
Library interposition (LD_PRELOAD on Linux, DYLD_INSERT_LIBRARIES on macOS) the dynamic loader loads your library first, so its functions win symbol resolution exported library functions quick API logging, test doubles
Compile-time (-finstrument-functions, sanitizers, --coverage, SanitizerCoverage) the compiler adds calls functions, edges, memory accesses coverage for fuzzing, profiling, ASan
Dynamic binary instrumentation (DBI): DynamoRIO, Intel Pin, Valgrind the program runs inside a JIT that copies and rewrites code blocks before executing them every instruction or block coverage (DynamoRIO's drcov), memory checking (Valgrind), tracing
Injection and hooking: Frida an agent (a JavaScript engine) is injected into the process; Interceptor.attach patches function entries functions, instructions mobile and desktop app analysis, scripting at run time
Kernel-side probes: eBPF with uprobes / uretprobes, bpftrace the kernel places a breakpoint at a user-space function and runs a verified eBPF program when it hits functions, syscalls system-wide observation without touching the process's memory

Interposition: logging every strcmp

The session builds the configuration toy from the tracing lesson (with -fno-builtin so the compiler doesn't replace strcmp by inline code) and a 15-line shared library that defines its own strcmp, logs both arguments to stderr, and forwards to the real one found with dlsym(RTLD_NEXT, ...). LD_PRELOAD makes the loader use it.

bash · try it yourself
cat > cfgtool.c <<'SRC'
#include <stdio.h>
#include <string.h>
int main(void) {
    char line[64] = "";
    FILE *f = fopen("settings.conf", "r");
    if (f) { if (!fgets(line, sizeof line, f)) line[0] = 0; fclose(f); }
    line[strcspn(line, "\n")] = 0;
    puts(strcmp(line, "mode=verbose") == 0 ? "verbose" : "quiet");
    return 0;
}
SRC
cat > logcmp.c <<'SRC'
#define _GNU_SOURCE
#include <dlfcn.h>
#include <stdio.h>
static int (*real_strcmp)(const char *, const char *);
int strcmp(const char *a, const char *b) {
    if (!real_strcmp) real_strcmp = (int (*)(const char *, const char *))dlsym(RTLD_NEXT, "strcmp");
    int r = real_strcmp(a, b);
    fprintf(stderr, "[hook] strcmp(\"%s\", \"%s\") = %d\n", a, b, r);
    return r;
}
SRC
gcc -O1 -fno-builtin cfgtool.c -o cfgtool
gcc -O1 -shared -fPIC logcmp.c -o logcmp.so
echo "mode=debug" > settings.conf
echo "== normal run";   ./cfgtool
echo "== with LD_PRELOAD"; LD_PRELOAD=./logcmp.so ./cfgtool 2>&1
== normal run
quiet
== with LD_PRELOAD
[hook] strcmp("mode=debug", "mode=verbose") = -18
quiet

Same program, same input; the preloaded library sees the comparison and its constant. Interposition is cheap and powerful, and it is also how some Linux malware hides itself (a preloaded library that filters readdir results to hide files). That dual use is why detection matters.

Compile-time instrumentation

When you have the source (your own code, or a fuzzing target), the compiler can instrument it for you. -finstrument-functions calls two hooks on every function entry and exit; the session prints a call tree from them.

bash · try it yourself
cat > tree.c <<'SRC'
#include <stdio.h>
static int depth;
__attribute__((no_instrument_function))
void __cyg_profile_func_enter(void *fn, void *site) { (void)site; fprintf(stderr, "%*senter %p\n", 2 * depth++, "", fn); }
__attribute__((no_instrument_function))
void __cyg_profile_func_exit(void *fn, void *site)  { (void)site; (void)fn; depth--; }
int leaf(int x)  { return x * 2; }
int mid(int x)   { return leaf(x) + leaf(x + 1); }
int main(void)   { printf("%d\n", mid(3)); return 0; }
SRC
gcc -O0 -no-pie -finstrument-functions tree.c -o tree
./tree 2> calls.txt
echo "== call tree (addresses replaced by names from nm)"
nm tree | awk '$2=="T"' > syms.txt
python3 - <<'PY'
syms = {int(a, 16): n for a, _, n in (l.split() for l in open("syms.txt"))}
for line in open("calls.txt"):
    pre, addr = line.rstrip("\n").rsplit(" ", 1)
    print(pre, syms.get(int(addr, 16), addr))
PY
14
== call tree (addresses replaced by names from nm)
enter main
  enter mid
    enter leaf
    enter leaf

The call tree main → mid → leaf, leaf is recovered from the hooks. Fuzzers use the same idea at edge granularity (SanitizerCoverage's -fsanitize-coverage=trace-pc-guard) to know which new paths an input reached.

Frida, DBI and eBPF: lab transcripts

Lab session: frida-trace and a short Frida script against the same cfgtool toy in the course's Linux VM. Abridged; Frida 16-style output. frida-trace writes a stub handler per function and fills in argument names (and strings for char * arguments) from the system's man pages when they are installed; without them the stub logs only strcmp() until you edit it. The script's -18 is glibc's return value, as in the LD_PRELOAD run (the C standard only promises a negative number).

console
Lab session: Frida on cfgtool (the course's own toy), Linux VM 10.10.0.40
$ frida-trace -i "strcmp" ./cfgtool
Instrumenting...
strcmp: Auto-generated handler at "__handlers__/libc.so.6/strcmp.js"
Started tracing 1 function. Press Ctrl+C to stop.
           /* TID 0x4d2 */
    12 ms  strcmp(s1="mode=debug", s2="mode=verbose")
$ cat hook.js
Interceptor.attach(Module.getExportByName(null, "strcmp"), {
  onEnter(args) { console.log("strcmp", args[0].readUtf8String(), args[1].readUtf8String()); },
  onLeave(ret)  { console.log("  ->", ret.toInt32()); }
});
$ frida -q -l hook.js -f ./cfgtool
strcmp mode=debug mode=verbose
  -> -18

Lab session: an eBPF uprobe with bpftrace (needs root, so it runs in the lab VM, not in this course's sandbox), and coverage with DynamoRIO's drcov:

console
Lab session: bpftrace and DynamoRIO on cfgtool (the course's own toy), Linux VM 10.10.0.40, as root
# bpftrace -e 'uprobe:/usr/lib/x86_64-linux-gnu/libc.so.6:strcmp { printf("%s %s\n", str(arg0), str(arg1)); }' -c ./cfgtool
Attaching 1 probe...
mode=debug mode=verbose
quiet
$ drrun -t drcov -- ./cfgtool
quiet
$ ls drcov.cfgtool.*.log      # basic-block coverage, loadable in Lighthouse (IDA) or Lightkeeper (Binary Ninja)

How instrumentation is detected

  • LD_PRELOAD: the variable in /proc/<pid>/environ, an entry in /etc/ld.so.preload (system-wide, a classic persistence and rootkit location that every Linux incident responder checks), and unexpected libraries in /proc/<pid>/maps.
  • Frida: a frida-agent library or frida threads in the process, its default port 27042 for frida-server, and patched function prologues. Mobile apps with anti-tampering check for these.
  • Inline hooks: the first bytes of a library function replaced by a jmp (the decoder lesson shows how to recognise E9); compare code in memory with the file on disk.
  • eBPF and uprobes are invisible to the process (the breakpoint lives in kernel-managed pages), which is why defenders like them; bpftool prog list shows loaded programs to an administrator.

How systems are protected against unwanted instrumentation

  • Setuid and capability-raising programs ignore LD_PRELOAD (the loader's secure-execution mode); keep it that way and audit /etc/ld.so.preload.
  • Restrict who may trace or load eBPF: kernel.yama.ptrace_scope, and kernel.unprivileged_bpf_disabled set to 2 (unprivileged eBPF off, an administrator can change it back; the default on recent kernels built with BPF_UNPRIV_DEFAULT_OFF, as on Ubuntu) or 1 (off and locked until reboot).
  • For app developers: anti-instrumentation checks raise the cost of analysis of your own app but never stop a determined analyst on a device they control; protect secrets and decisions on the server.

Pitfalls

  • Inlined or builtin functions can't be interposed: strcmp with a constant may become inline code (hence -fno-builtin above), and static binaries ignore LD_PRELOAD entirely.
  • Recursion in hooks: a hook that calls the hooked function (printf inside a printf hook) loops forever; call the real one through the saved pointer.
  • Instrumentation changes timing and memory layout, which can hide or reveal bugs and is noticeable to timing checks.
  • Root-only tools (bpftrace, perf uprobes) belong in the lab VM.

Practice

1. Why did the interposed strcmp need dlsym(RTLD_NEXT, "strcmp")?

To call the real strcmp in libc, the next definition after the preloaded library in the search order; calling strcmp directly would call the hook itself.

2. As an incident responder on a Linux server, which file do you check first for system-wide library injection?

/etc/ld.so.preload (and the LD_PRELOAD variable in the environment of suspicious processes).

3. Which method would you choose to get basic-block coverage of a closed-source Linux binary for fuzzing, and why?

Dynamic binary instrumentation (DynamoRIO drcov, Intel Pin, or QEMU mode in AFL++): it needs no source and sees every block; compile-time coverage needs the source.

Test yourself

How does LD_PRELOAD interpose a function?

  1. It patches the binary on disk
  2. The dynamic loader loads the preloaded library first, so its definition of the symbol wins resolution
  3. It uses ptrace
  4. It edits the kernel

Which tool injects a JavaScript engine into a process to hook functions?

  1. DynamoRIO
  2. Frida
  3. bpftrace
  4. objdump

Why don't setuid programs honour LD_PRELOAD?

  1. They are statically linked
  2. The loader's secure-execution mode ignores it, otherwise any user could inject code into a privileged program
  3. They have no PLT
  4. Because of ASLR

Which file is a classic location for system-wide library injection on Linux?

  1. /etc/passwd
  2. /etc/ld.so.preload
  3. /etc/hosts
  4. /proc/self/status