我的目标是在每个基本代码块的开头插入一点工具代码。 Javaassist的ControlFlow.Block和CtMethod.insertAt()似乎是一个相当简单的任务。下面是代码中的相关块到目前为止(它位于转换功能):Javassist的CtMethod.insertAt(line,src)工具代码位于错误的字节码位置
ControlFlow flow=new ControlFlow(m); //m is the CtMethod currently being instrumented
Block[] blockArray=flow.basicBlocks();
for(Block thisbb : blockArray){
//Dynamically Update Method Statistics
String blockUpdate=new String();
String thisbbIndex=Integer.toString(thisbb.index());
blockUpdate+=mse+".setBlockIndex("+thisbbIndex+"); ";
blockUpdate="{ " + blockUpdate + "} ";
//Insert
int pos=m.getMethodInfo().getLineNumber(thisbb.position()); //Source code line position from binary line position
System.out.print("At "+pos+": "+blockUpdate);
int n=m.insertAt(pos, blockUpdate);
System.out.println(" -> "+n);
}
注意,在CtMethod.insertAt(line,srcCode)的“行”参数是源代码线位置,而不是字节码线位置。在源代码中,一些基本块报告相同的行号!下面是输出:
At 6: { _JDA_mse.setBlockIndex(0); } -> 6
At 8: { _JDA_mse.setBlockIndex(1); } -> 8
At 8: { _JDA_mse.setBlockIndex(2); } -> 8
At 8: { _JDA_mse.setBlockIndex(3); } -> 8
At 8: { _JDA_mse.setBlockIndex(4); } -> 8
At 8: { _JDA_mse.setBlockIndex(5); } -> 8
At 8: { _JDA_mse.setBlockIndex(6); } -> 8
At #代表我要求被放置在代码中的位置,以及-> #表示,这实际上是插在源代码中的位置(如果一切顺利,他们应该是一样)。 { ... }中的所有内容都是我想要放置的代码(_JDA_mse是我用Javassist方法添加到函数中的局部变量,因此使用它时没有问题)。
问题是for(int i=0; i