This commit is contained in:
Rick Sprague 2024-10-10 19:43:42 -04:00
parent 09f73b704a
commit d13cafcdeb
10 changed files with 87 additions and 0 deletions

1
.gitignore vendored
View File

@ -1 +1,2 @@
**/build
**/.cache

View File

@ -0,0 +1,8 @@
cmake_minimum_required(VERSION 3.5)
project(interceptor)
set(CMAKE_EXPORT_COMPILE_COMMANDS ON)
add_subdirectory(target)
add_subdirectory(instrument)
add_subdirectory(app)

View File

@ -0,0 +1,6 @@
cmake_minimum_required(VERSION 3.5)
project(app)
file(GLOB SOURCES "src/*.cpp")
add_executable(${PROJECT_NAME} ${SOURCES})
target_link_libraries(${PROJECT_NAME} PRIVATE target)

View File

@ -0,0 +1,7 @@
#include "A.h"
int main(int argc, const char *argp[], const char *envp[]) {
A a;
a.method("test");
return 0;
}

View File

@ -0,0 +1 @@
build/compile_commands.json

View File

@ -0,0 +1,10 @@
cmake_minimum_required(VERSION 3.5)
project(instrument)
file(GLOB SOURCES "src/*.cpp")
add_library(${PROJECT_NAME} SHARED ${SOURCES})
add_dependencies(${PROJECT_NAME} target)
target_link_libraries(${PROJECT_NAME}
PRIVATE
dl
)

View File

@ -0,0 +1,31 @@
#include <dlfcn.h>
#include <string>
#include <iostream>
using std::cout;
using std::endl;
class A;
// Function pointer to store the original method
typedef void (*MethodType)(A *, const std::string &);
MethodType original_method = nullptr;
extern "C" void _ZN1A6methodERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEE(A *obj, const std::string &msg) {
cout << "Intercepted A::method with message: " << msg << endl;
// Call the original method if it was found
if (original_method) {
original_method(obj, msg);
}
}
// Initialization function
extern "C" void __attribute__((constructor)) init() {
cout << "Shared library has been preloaded." << endl;
// Get the original A::method using dlsym and RTLD_NEXT
original_method = (MethodType)dlsym(RTLD_NEXT, "_ZN1A6methodERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEE");
if (!original_method) {
cout << "Error: unable to find original A::method" << endl;
}
}

View File

@ -0,0 +1,8 @@
cmake_minimum_required(VERSION 3.5)
project(target)
file(GLOB SOURCES "src/*.cpp")
add_library(${PROJECT_NAME} SHARED ${SOURCES})
target_include_directories(${PROJECT_NAME}
PUBLIC
include)

View File

@ -0,0 +1,7 @@
#pragma once
#include <string>
class A {
public:
void method(const std::string& msg);
};

View File

@ -0,0 +1,8 @@
#include "A.h"
#include <iostream>
using std::cout;
using std::endl;
void A::method(const std::string &msg) {
cout << "original: " << msg << endl;
}