如何使用libclang注入代码(在C ++中)

时间:2017-11-11 01:28:10

标签: c++ libclang

我想知道如何使用libclang向函数调用插入参数?我必须遵循只打印参数的代码:

class CASTVisitor : public RecursiveASTVisitor<CASTVisitor> 
{
public:
    CASTVisitor(Rewriter &R) : rewriter(R) 
    {
    }

    virtual bool VisitCallExpr(CallExpr *call) 
    {
        for(int i = 0, j = call->getNumArgs(); i < j; ++ i)
        {
            errs() << "argType: " << call->getArg(i)->getType().getAsString() << "\n";
        }

        errs() << "** Added parameter to function call\n";

        return true;
    }
...
};

修改

虽然我可以阅读并设置参数,但我没有看到任何方法在parmVarDcl()匹配器的开头插入一个。

将成员变量添加到基类和复合语句也是如此。您似乎可以更改现有文本,但无法轻松插入新对象。我是对的吗?

1 个答案:

答案 0 :(得分:0)

到目前为止,我找到的唯一解决方案是从光标获取文件指针并手动注入代码:

https://github.com/burnflare/libclang-experiments

CXFile file;
unsigned line;
unsigned offset;

clang_getSpellingLocation(clang_getCursorLocation(cursors[i+1]),
                          &file,
                          &line,
                          NULL,
                          &offset);

const char* filename = clang_getCString(clang_getFileName(file));
printf("\n\nMethod found in %s in line %d, offset %d\n", clang_getCString(clang_getFileName(file)), line, offset);

// File reader
FILE *fr = fopen(filename, "r");
fseek(fr, 0, SEEK_END);
long fsize = ftell(fr);
fseek(fr, 0, SEEK_SET);

// Reading file to string
char *input = malloc(fsize);
fread(input, fsize, 1, fr);
fclose(fr);

// Making an output that is input(start till offset) + code injection + input(offset till end)
FILE *fw = fopen(filename, "w");
char *output = malloc(fsize);
strncpy(output, input, offset);
strcat(output, injectCode);
strcat(output, input+offset);

// Rewrite the whole file with output string
fwrite(output, fsize, sizeof(output), fw);
fclose(fw);

如果有人有更好的想法,请告诉我!