【问题标题】:How to get the dynamic assigned heap address and malloc size with llvm pass instrumentation at runtime?如何在运行时通过 llvm pass 检测获取动态分配的堆地址和 malloc 大小?
【发布时间】:2020-03-12 22:19:58
【问题描述】:

遍历基本块,在运行时获取 malloc 大小 args 和返回地址。 我在 IR 中的每个调用 malloc() 站点检测 printf() 函数,并希望它可以在运行时打印 malloc 大小。 在示例中,大小为 inst.getOperand(0),malloc 大小从 scanf() 中获取。

for (auto &BB : F) {
    for (auto Inst = BB.begin(); Inst != BB.end(); Inst++) {
        Instruction &inst = *Inst;    
        if(CallInst* call_inst = dyn_cast<CallInst>(&inst)) {         
           Function* fn = call_inst->getCalledFunction();
           if(fn == "malloc"){
                /* do something to get heap address and malloc size*/
                // for example
                /* declare printf function */
                IRBuilder<> builder(call_inst);
                std::vector<llvm::Type *> putsArgs;
                putsArgs.push_back(builder.getInt8Ty()->getPointerTo());
                llvm::ArrayRef<llvm::Type*>  argsRef(putsArgs);

                /* declare a varible and assign, then puts args */
                llvm::FunctionType *putsType =
                    llvm::FunctionType::get(builder.getInt64Ty(), argsRef, true);
                llvm::Constant *putsFunc = M.getOrInsertFunction("printf", putsType);
                Value *allocDeclrInt;
                Value *RightValue = IntegerType::get(64, inst.getOperand(0));

                StoreInst store=builder.CreateStore(RightValue,allocDeclrInt, false);
                LoadInst *a = builder.CreateLoad(allocDeclrInt);
                Value *intFormat = builder.CreateGlobalStringPtr("%d");

                std::vector<llvm::Value *> values;
                values.clear();
                values.push_back(intFormat);
                values.push_back(a);

                //puts size
                builder.CreateCall(putsFunc, values);
           }
        }
    }
}

我的 test.c 文件包含:

int a=0;
scanf("%d",&a); 
p1=(char*)malloc(a*sizeof(char));

IR 语言:

  %conv = sext i32 %29 to i64, !dbg !81
  %a.size = alloca i32, !dbg !82
  store i32 10, i32* %a.size, !dbg !82
  %30 = load i32, i32* %a.size, !dbg !82
  %31 = call i32 (i8*, ...) @printf(i8* getelementptr inbounds ([3 x i8], [3 x i8]* @0, i32 0, i32 0), i32 %30), !dbg !82
  %32 = call i32 (i8*, ...) @printf(i8* getelementptr inbounds ([17 x i8], [17 x i8]* @1, i32 0, i32 0)), !dbg !82
  %call1 = call i8* @malloc(i64 %conv), !dbg !82

我可以在运行时获取分配的大小和堆地址吗?

【问题讨论】:

    标签: dynamic runtime llvm instrumentation


    【解决方案1】:

    malloc() 本身在运行时选择它的地址(而且有些实现保证每次程序运行时返回值会有所不同),所以如果要获取堆地址,就得换成自己的实现malloc 的。

    获取 malloc 大小更容易:如果 callInst->getArgOperand(0)ConstantInt,则您有大小。如果没有,您也许可以fold it,但这可能超出您的兴趣?

    【讨论】:

    • 嗨,我想我没有清楚地描述我的问题并更改了帖子。我打算在编译时进行检测并在运行时获取大小和堆地址。你能给我一些建议吗?
    猜你喜欢
    • 2022-11-16
    • 2010-10-25
    • 2014-08-21
    • 1970-01-01
    • 1970-01-01
    • 2014-06-12
    • 1970-01-01
    • 2015-04-28
    相关资源
    最近更新 更多