how to use ld_preload to intercept c++ program?

longguang.yue yalogr@163.com
Tue Feb 25 01:44:49 GMT 2025


HI, all:
  Is there a mechanism or standard to use ld_preload to intercept c++ program? 

libintercept.so is compiled by "gcc/g++ -Wall -fPIC -shared -Wl,-soname,$(SONAME) -ldl libintercept.o -o libintercept.so",  can intercept many syscall functions including open,creat,openat,read,write.....

In my test,  open,openat, seek, flush and unlink are not intercepted. 



(base) [root@debug preload]# cat c/test_cpp_openrwun.cpp 
#include <iostream>
#include <fstream>
#include <string>
 
int main() {
    std::string filename = "/tmp/test_cpp_openrwun.txt";
    std::string contentToWrite = "Hello, World!";
    std::string contentRead;
 
    std::ofstream outFile;
	outFile.open(filename);
    if (!outFile) {
        std::cerr << "open failed" << std::endl;
        return 1;
    }
 
    outFile << contentToWrite;
	outFile.seekp(0);
	outFile.flush();
    outFile.close(); 
 
    std::ifstream inFile(filename);
    if (!inFile) {
        std::cerr << "read failed" << std::endl;
        return 1;
    }
 
    std::getline(inFile, contentRead); 
    inFile.close(); 
 
    std::cout << contentRead << std::endl;
 
    if (std::remove(filename.c_str()) != 0) {
        std::cerr << "remove failed" << std::endl;
        return 1;
    }
 
    return 0;
}
(base) [root@debug preload]# LD_PRELOAD=libintercept.so ./test_cpp_openrwun 
Intercepted write: fd=3, count=13
Intercepted read: fd=3, count=8191
Intercepted read: fd=3, count=8191
Hello, World!
Intercepted remove: /tmp/test_cpp_openrwun.txt


More information about the Libc-help mailing list