dyninst动态插桩示例代码:
版本:
dyninst-9.3.1
gcc-4.8.4
简述:示例代码演示动态插桩,在程序运行时动态改变运行的函数。
被插装的程序(mutatee)源码:test_dyninst.c
#include
#include
void old()
{
printf("Oh my god! Pid is %d\n", getpid());
}
void new()
{
printf("Hello world! Pid is %d\n", getpid());
}
int main()
{
while(1){
old();
sleep(5);
}
return 0;
}
用来插装的程序(mutator)的源码:instrument.cpp
#include
#include
#include
#include
#include "BPatch.h"
#include "BPatch_Vector.h"
#include "BPatch_process.h"
#include "BPatch_snippet.h"
int main(int argc, char **argv)
{
BPatch *bpatch = new BPatch;
std::vector
func_old; std::vector
func_new; // Specify the executable file name and process id of the application as arguments BPatch_process *appProc = bpatch->processAttach(argv[1], atoi(argv[2])); // BPatch_process inherit from BPatch_addressSpace BPatch_addressSpace *app = appProc; BPatch_image *appImage = app->getImage(); // Find function:old() std::vector
*tmp = appImage->findFunction("old", func_old); // find function: new() tmp = appImage->findFunction("new", func_new); // Exchange function "old()" to "new()" appProc->replaceFunction(*func_old[0], *func_new[0]); // Detach from the mutatee process, optionally leaving it running appProc->detach(1); }
1.编译
$ gcc test_dyninst.c -o test_dyninst
$ g++ -std=c++11 instrument.cpp /home/sky/dyninst-9.3.1/dyninstAPI/libdyninstAPI.so
PS:c++11的c是小写,系统会自动配成大写的C++,大家注意。
2.先执行test_dyninst ,不断输出old()函数的“Oh my god! Pid is xxx".
3.再执行a.out(instrument.cpp编译结果)。test_dyninst执行结果发生变化时(输出”Hello world! Pid is xxx“),a.out自行退出。