How can intercept libc function in C++ using LD_PRELOAD. I want to write code only in C++ file and all the logic of symbol fishing (dlsym) must be in C++ file. Please give an example.
1 Answer
If you want to intercept only library calls, you can insert your hooks in the GOT
of the executable or at the dynamic loader resolver pointer (GOT[2]
). I don't have sample code at hand, but this aricle is good for background.
If you want to intercept all syscalls (including those in the binary itself, e.g. if it's linked statically), you can use ptrace (PTRACE_SYSCALL)
to be notified of all syscalls happening in the process. There are some examples on StackOverflow but they usually assume you're tracing another process. If you want to trace the same process you're in, you can use the ptrace(PTRACE_TRACEME)
call.
extern "C"
? This effectively lets you write C functions in C++ by assigning C linkage.