C++ Logo

std-discussion

Advanced search

how to use ld_preload to intercept c++ program?

From: longguang.yue <yalogr_at_[hidden]>
Date: Mon, 24 Feb 2025 18:01:49 +0800 (CST)
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_at_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_at_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

Received on 2025-02-24 10:01:56