我正在尝试使用 LLVM 构建一个简单版本的代码分析工具。
我有一些 .ll 文件,其中包含某些程序的中间 LLVM 表示。
如何从 LLVM 的中间表示中获取在程序的每个函数中执行的函数调用列表?
我拥有的输入参数是代表程序的 LLVM: Module 类的一个实例。然后,我使用函数 getFunctionList () 获取程序中存在的函数列表。
void getFunctionCalls(const Module *M)
{
// Iterate functions in program
for (auto curFref = M->getFunctionList().begin(), endFref = M->getFunctionList().end();
curFref != endFref; ++curFref) {
// For each function
// Get list of function calls
}
}
Run Code Online (Sandbox Code Playgroud)
这是我们工作的代码片段在这里:
for (auto &module : Ctx.getModules()) {
auto &functionList = module->getModule()->getFunctionList();
for (auto &function : functionList) {
for (auto &bb : function) {
for (auto &instruction : bb) {
if (CallInst *callInst = dyn_cast<CallInst>(&instruction)) {
if (Function *calledFunction = callInst->getCalledFunction()) {
if (calledFunction->getName().startswith("llvm.dbg.declare")) {
Run Code Online (Sandbox Code Playgroud)
还要记住,也有InvokeInst可以通过类似方式获得的调用指令。
谷歌CallInst vs InvokeInst并了解有或没有被调用函数的函数。如果一个函数没有被调用的函数,这就是间接调用。当源代码不是直接调用函数而是调用函数指针时,间接调用出现在 LLVM IR 中。在 C++ 中,当某个类通过抽象接口(多态)进行操作时,通常会发生这种情况。所以请记住,即使您有适当的调用指令,也不是 100% 总是可以跟踪被调用的函数。
| 归档时间: |
|
| 查看次数: |
2917 次 |
| 最近记录: |