编写 LLVM pass 以检测 malloc 函数调用、分配的字节数和指向该内存的变量名称

Hif*_*Hif 5 c llvm

我最近开始使用 LLVM。我正在尝试在给定以下代码的 LLVM 中编写一个通行证

string = (char *)malloc(100);
string = NULL;
Run Code Online (Sandbox Code Playgroud)

和相应的LLVM IR

%call = call noalias i8* @malloc(i64 100) #3
store i8* %call, i8** %string, align 8
store i8* null, i8** %string, align 8
Run Code Online (Sandbox Code Playgroud)

检测指令调用malloc,提取number of bytes分配的(在本例中为 100),address返回的地址和分配给的变量名称。

std::map<std::string, std::tuple<size_t, int> > mem_addrs;  // stores pointer name, address and no. of bytes allocated
Count() : ModulePass(ID) {}

virtual bool runOnModule(Module &M) {
  for (Function &F: M) { 
    for (BasicBlock &B: F) {
        for (Instruction &I: B) {
            if(CallInst* call_inst = dyn_cast<CallInst>(&I)) {
                Function* fn = call_inst->getCalledFunction();
                StringRef fn_name = fn->getName();
                errs() << fn_name << " : " << "\n";
                for(auto args = fn->arg_begin(); args != fn->arg_end(); ++args) {
                    ConstantInt* arg = dyn_cast<ConstantInt>(&(*args));
                    if (arg != NULL)
                            errs() << arg->getValue() << "\n";
                }    
            }
        }
     }  
  }
Run Code Online (Sandbox Code Playgroud)

输出是

-VirtualBox:~/program_analysis$ opt -load $LLVMLIB/CSE231.so -analyze -count < $BENCHMARKS/leaktest/leaktest.bc > $OUTPUTLOGS/welcome.static.log
ok
allocaimw
allocaleak
allocamalloc : 0x2f5d9e0
0  opt             0x0000000001315cf2 llvm::sys::PrintStackTrace(_IO_FILE*) + 34
1  opt             0x0000000001315914
2  libpthread.so.0 0x00007f0b53f12330
3  opt             0x00000000012ec78f llvm::APInt::toString(llvm::SmallVectorImpl<char>&, unsigned int, bool, bool) const + 79
4  opt             0x00000000012ed309 llvm::APInt::print(llvm::raw_ostream&, bool) const + 57
5  CSE231.so       0x00007f0b52f16661
6  opt             0x00000000012ad6cd llvm::legacy::PassManagerImpl::run(llvm::Module&) + 797
7  opt             0x000000000058e190 main + 2752
8  libc.so.6       0x00007f0b5313af45 __libc_start_main + 245
9  opt             0x00000000005ab2ca
Stack dump:
0.  Program arguments: opt -load /home/hifza/program_analysis/llvm/build/Release+Asserts/lib/CSE231.so -analyze -count 
1.  Running pass 'Instruction Counts Pass' on module '<stdin>'.
Segmentation fault (core dumped)
Run Code Online (Sandbox Code Playgroud)

我能够检测malloc指令,但我无法找出相应的内存地址和分配的字节数。任何人都可以指导我如何去做吗?谢谢。

arr*_*owd 1

您不检查 的结果dyn_cast<ConstantInt>(&(*args))。如果转换类型不是 a ConstantInt,则返回nullptr。在下一行 ( arg->getValue()) 中取消引用它。