编写一个llvm编译器插件,完成在store汇编指令前对内存合法性的check。

dds(iceoryx、fastdds等)中间件采用了共享内存,如果app内存越界将共享内存踩踏坏了,将会形成灾难。本插件可以检测到app是否在写共享内存,如果是,我们可以让app assert。从而提高dds的稳定性

插件效果:

插件源码:

#include "llvm/Pass.h"

#include "llvm/IR/Function.h"

#include "llvm/IR/BasicBlock.h"

#include "llvm/IR/Instructions.h"

#include "llvm/Support/raw_ostream.h"

#include "llvm/Pass.h"

#include "llvm/IR/Constants.h"

#include "llvm/Support/CommandLine.h"

#include "llvm/IR/IRBuilder.h"

#include "llvm/IR/Value.h"

#include "llvm/IR/Module.h"

#include "llvm/IR/Function.h"

#include "llvm/IR/BasicBlock.h"

#include "llvm/IR/Instruction.h"

#include "llvm/IR/Instructions.h"

#include "llvm/Support/raw_ostream.h"

#include "llvm/IR/IntrinsicInst.h"

using namespace llvm;

namespace {

struct InsertStubPass : public FunctionPass {

static char ID;

const char *LOG_FUNCTION_STR = "log_function_call"; // 日志打印函数调用

InsertStubPass() : FunctionPass(ID) {}

bool runOnFunction(Function &F) override {

errs().write_escaped(F.getName()) << "-----------\n";

if(F.getName() != "init_ring_buffer")

return true;

// 字符串类型

Type *StringType = Type::getInt8PtrTy(F.getParent()->getContext());

// void type

Type *voidTy = Type::getVoidTy(F.getParent()->getContext());

bool isVarArg = false;

std::vector<Type*> functionCallParams;

functionCallParams.push_back(StringType);

FunctionType *functionCallType = FunctionType::get(

voidTy, functionCallParams, isVarArg

);

F.getParent()->getOrInsertFunction(LOG_FUNCTION_STR, functionCallType);

Function *logFunction = F.getParent()->getFunction(LOG_FUNCTION_STR);

for (BasicBlock &BB : F) {

for (Instruction &I : BB) {

errs() << I << "+++\n";

// 检查是否为mov指令

if ( auto *MOV = dyn_cast<StoreInst>(&I) ) {

errs().write_escaped("store ins") << "-----------\n";

// 在mov指令前插入一个空的call指令作为插桩

IRBuilder<> builder(MOV);

// ReturnInst i;

Value *PointerOperand = MOV->getPointerOperand();

errs() << "Store address: " << *PointerOperand << "\n";

Value *AddrOp = builder.CreatePointerCast(PointerOperand, builder.getInt8PtrTy());

// 该函数的指针变量

// Value *strPointer = builder.CreateGlobalStringPtr(f.getName());

// 自己定义的 日志函数

std::vector<Value *> args;

args.push_back(AddrOp); // 生成日志函数 的参数列表

// 创建自己的日志函数 并传入 本函数的函数指针

CallInst::Create(logFunction, args, "", MOV);

// 可以在这里添加插桩的相关信息,例如标记插桩的名称或其他属性

// StubCall->setName("stub_instruction");

// 如果需要追踪插桩的执行情况,可以在这里添加分析或者断言

// e.g., llvm::Assume(Builder.CreateICmpEQ(StubCall, StubCall));

}

}

}

return true;

}

};

}

char InsertStubPass::ID = 0;

static RegisterPass<InsertStubPass> X("insert-stub", "Insert a stub instruction before mov instructions", false, false);

参考使用流程:

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

无v邪

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值