how to write a clang plugin to inject some code to the original code while compiling

蹲街弑〆低调 提交于 2020-01-14 14:20:10

问题


i got a problem about how to write a clang plugin that will change the code. i want inject some code to the program,just like this:enter code here

//the original code
//the filename is user_code.cpp
int f1(){
    return 1;
}
int f2(){
    return 2;
}
int f3(){
    return 3;
}
int main(){
   for(int i=0;i<1000;i++)f1();
   for(int i=0;i<10000;i++)f2();
   for(int i=0;i<100000;i++)f3();
   return 0;
}
//the injected code
int function_counter[3];
int f1(){
    function_counter[0]++;
    return 1;
}
int f2(){
    function_counter[1]++;
    return 2;
}
int f3(){
    function_counter[2]++;
    return 3;
}
int main(){
   for(int i=0;i<1000;i++)f1();
   for(int i=0;i<10000;i++)f2();
   for(int i=0;i<100000;i++)f3();
   return 0;
}

now, i can do this by parsing this code to an AST.and traverse it, use ReWriter class to modify the code,at last rewrite the modified code to a new file.but this is not transparent to user.i want write a clang plugin,user just input the command:

 clang -load myplugin.so -plugin myplugin user_code.cpp -o user_code.o

the code first can be injected transparently,and then compile like usualy.what can i do?any suggest?

来源:https://stackoverflow.com/questions/19346660/how-to-write-a-clang-plugin-to-inject-some-code-to-the-original-code-while-compi

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!