插装LLVM使用C / C ++ code [英] Instrumenting C/C++ code using LLVM

查看:192
本文介绍了插装LLVM使用C / C ++ code的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想写一个LLVM传递到每一个仪器内存访问。
这里就是我要做的。

I want to write a LLVM pass to instrument every memory access. Here is what I am trying to do.

由于任何C / C ++程序(如下面给出的),我试图调用插入一些功能,之前和之后的每读取/指令从内存中写入/。例如,考虑下面的C ++程序(Account.cpp)

Given any C/C++ program (like the one given below), I am trying to insert calls to some function, before and after every instruction that reads/writes to/from memory. For example consider the below C++ program (Account.cpp)

#include <stdio.h>

class Account {
int balance;

public:
Account(int b)
{
   balance = b;   
}
~Account(){ }

int read() 
{
  int r;  
  r = balance;   
  return r;
}

void deposit(int n) 
{   
  balance = balance + n;   
}

void withdraw(int n) 
{
  int r = read();   
  balance = r - n;   
}
};

int main ()
{ 
  Account* a = new Account(10); 
  a->deposit(1);
  a->withdraw(2);  
  delete a; 
}

所以在改编之后我的程序应该是这样的:

So after the instrumentation my program should look like :

#include <stdio.h>

class Account 
{
  int balance;

public:
Account(int b)
{
  balance = b;   
}
~Account(){ }

int read() 
{
  int r;  
  foo();
  r = balance;
  foo();   
  return r;
}

void deposit(int n) 
{ 
  foo(); 
  balance = balance + n;
  foo();   
}

void withdraw(int n) 
{
  foo();
  int r = read();
  foo();
  foo();   
  balance = r - n;
  foo();   
}
};

int main ()
{ 
  Account* a = new Account(10); 
  a->deposit(1);
  a->withdraw(2);  
  delete a; 
}

其中foo()可能会像得到当前系统时间或增加一个计数器..等任何功能。

where foo() may be any function like get the current system time or increment a counter .. so on.

请给我的例子(来源$ C ​​$ C,教程等)和步骤如何运行它。我已阅读关于如何做一个合格LLVM在 http://llvm.org/docs/WritingAnLLVMPass.html 给出的教程,但无法弄清楚如何写上述问题一通。

Please give me examples (source code, tutorials etc) and steps on how to run it. I have read the tutorial on how make a LLVM Pass given on http://llvm.org/docs/WritingAnLLVMPass.html, but couldn't figure out how write a pass for the above problem.

推荐答案

尝试是这样的:(你需要填补空白,使这个循环工作,尽管被插入的项目)

Try something like this: ( you need to fill in the blanks and make the iterator loop work despite the fact that items are being inserted )

class ThePass : public llvm::BasicBlockPass {
  public:
  ThePass() : BasicBlockPass() {}
  virtual bool runOnBasicBlock(llvm::BasicBlock &bb);
};
bool ThePass::runOnBasicBlock(BasicBlock &bb) {
  bool retval = false;
  for (BasicBlock::iterator bbit = bb.begin(), bbie = bb.end(); bbit != bbie;
   ++bbit) { // Make loop work given updates
   Instruction *i = bbit;

   CallInst * beforeCall = // INSERT THIS
   beforeCall->insertBefore(i);

   if (!i->isTerminator()) {
      CallInst * afterCall = // INSERT THIS
      afterCall->insertAfter(i);
   }
  }
  return retval;
}

希望这有助于!

这篇关于插装LLVM使用C / C ++ code的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆