首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用BCEL在现有方法中注入代码

使用BCEL在现有方法中注入代码
EN

Stack Overflow用户
提问于 2013-10-01 15:05:28
回答 1查看 4.5K关注 0票数 5

为了我的论文研究,我需要将一段代码注入到我没有源代码的测试套件中的一个可定义的方法中(在本例中是DaCapo基准测试套件,http://dacapobench.org/ )。之前的研究,这部分是我的论文的基础上,使用字节码注入这一点,这使我也这样做。

我使用Apache的BCEL库( http://commons.apache.org/proper/commons-bcel/ )构建了一个小程序,它使我能够在方法体(在其他语句之前)中注入fibonacci算法。

现在,我已经做了这个,但它不能正常工作。我注入的一些方法工作得很好(因为fibonacci代码它们运行得更慢),运行DaCapo框架很好,而其他注入方法破坏了代码。

问题是,我不知道为什么,即使我知道哪些方法崩溃了,哪些方法成功了,但我无法在这些破碎的方法中找到一个反复出现的模式。

  • 字节码似乎很好,因为到目前为止,我可以看到,但我远不是一个专家。当我比较注入前后的字节码时,我看到fibonacci algoritm后面跟着剩下的方法,只是增加的堆栈位置不同(因为注入的代码也使用堆栈空间)。
  • 成功的方法既有公共的,也有私人的。不管有没有参数。
  • 一些失败的方法包含异常,另一些没有。有些方法尝试捕获,其他方法没有,等等。

我可以粘贴一些失败的方法,但这将使这篇文章比现在更长。所以我在想,是不是有什么事情我没想过或者忽略了?

下面是一个java文件示例,它是我编写的结果和BCEL程序。

一个简单的例子是,我有一个名为DemoClass.java的java文件:

代码语言:javascript
复制
public class DemoClass {

    public static void main(String[] argv) {
        System.out.println("Demo body");
        test();
    }

    public static void test() {
        System.out.println("Demo test");
    }
}

在我的shell中调用以下java命令之后:

javac DemoClass.java; java -cp bcel-5.2.jar:. InjectCodeBCEL DemoClass test 123456789 ; java DemoClass

( bcel-5.2.jar文件可以在前面提到的apache网站上找到)

程序将如下所示:

代码语言:javascript
复制
public class DemoClass {

    public static void main(String[] argv) {
        System.out.println("Demo body");
        test();
    }

    public static void test() {
        int[] fibNumbers = new int[100]; 
        for (int i = 0; i < 123456789; i++) { 
            int j = i % 100; 
            if (i == 0) { 
                fibNumbers[i] = 0; 
            } 
            else if (i == 1) { 
                fibNumbers[i] = 1; 
            } 
            else { 
                int k = (i - 1) % 100; 
                int m = (i - 2) % 100; 
                int n = fibNumbers[k] + fibNumbers[m]; 
                fibNumbers[j] = n; 
            }  
        } 
        System.out.println("Demo test");
    }
}

这是InjectCodeBCEL.java的代码:

代码语言:javascript
复制
import java.io.IOException;
import org.apache.bcel.classfile.*;
import org.apache.bcel.generic.*;
import org.apache.bcel.*;

public class InjectCodeBCEL {

    static public void main(String args[]) {
        //Get class to modify from program argument
        JavaClass mod = null;
        String methodName = (args.length >= 2) ? args[1] : "";
        int loopsize = (args.length >= 3) ? Integer.parseInt(args[2]) : 1;
        try {
            mod = Repository.lookupClass(args[0]);
        }
        catch (Exception e) {
            System.err.println("Could not get class " + args[0]);
            return;
        }

        //Create a generic class to modify
        ClassGen modClass = new ClassGen(mod);
        //Create a generic constantpool to modify
        ConstantPoolGen cp = modClass.getConstantPool();
        boolean methodEdited = false;

        Method[] methods = mod.getMethods();
        for (int i = 0; i < methods.length; i++) {
            if (methods[i].getName().equals(methodName)) {

                System.out.println("Method: " + methods[i]);
                // System.out.println("before:\n" + methods[i].getCode());
                modClass.removeMethod(methods[i]);
                Method newMethod = insertCodeInMethod(mod, methods[i], cp, loopsize);
                // System.out.println("after:\n" + newMethod.getCode());
                modClass.addMethod(newMethod);

                methodEdited = true;
            }
        }
        if (methodEdited) {
            modClass.update();
            try {
                //Write modified class
                JavaClass newClass = modClass.getJavaClass();
                String classname = args[0].replace(".","/");
                newClass.dump(classname + ".class");
                System.out.println("Class " + classname + " modified");
            }
            catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public static Method insertCodeInMethod(JavaClass mod, Method method, ConstantPoolGen cp, int loopsize) {
        MethodGen mg = new MethodGen(method, mod.getClassName(), cp);

        InstructionList il = mg.getInstructionList();
        InstructionHandle ihs = il.getStart();
        InstructionList ils = new InstructionList();
        InstructionFactory f = new InstructionFactory(cp);

        String CLASS_NAME = mod.getClassName();

        int ARRAY_SIZE = 100;
        int LOOP_SIZE = loopsize;

        int INCREASE_ID = mg.isStatic() ? 0 : 1; // if not static, this has position 0 on the stack
        Type[] types = mg.getArgumentTypes();
        // Increase the stack location(?) so they don't collide with the methods parameters.
        for (int i = 0; i < types.length; i++) {
            INCREASE_ID += types[i].getSize();
        }

        int VAR_ARRAY = 0 + INCREASE_ID;
        int VAR_I = 1 + INCREASE_ID;
        int VAR_II = 2 + INCREASE_ID;
        int VAR_I_MIN_1 = 3 + INCREASE_ID;
        int VAR_I_MIN_2 = 4 + INCREASE_ID;
        int VAR_SUM = 5 + INCREASE_ID;
        int VAR_JUMPTO = 6 + INCREASE_ID;

        // init array
        ils.append(new PUSH(cp, ARRAY_SIZE));
        ils.append(new NEWARRAY(Type.INT));
        ils.append(new ASTORE(VAR_ARRAY));

        // create iterator = 0 for while 
        ils.append(new PUSH(cp, 0));
        ils.append(new ISTORE(VAR_I));

        // Main while loop:
        InstructionHandle beforeWhile = ils.append(new ILOAD(VAR_I));
        ils.append(new PUSH(cp, LOOP_SIZE));
        // While condition:
        BranchHandle whileCondition = ils.append(new IF_ICMPLT(null)); // if (VAR_I < LOOP_SIZE): jump to "whileBody"
        BranchHandle whileConditionFalseGoto = ils.append(new GOTO(null)); // if not: jump to "afterWhile"

            // While body:
            InstructionHandle whileBody = ils.append(new ILOAD(VAR_I));
            ils.append(new PUSH(cp, ARRAY_SIZE));
            ils.append(new IREM());
            ils.append(new ISTORE(VAR_II)); // create int ii = i % ARRAY_SIZE;

            // if (i == 0)
            ils.append(new ILOAD(VAR_I));
            ils.append(new PUSH(cp, 0));
            BranchHandle ifIteratorIs0 = ils.append(new IF_ICMPEQ(null));
            BranchHandle ifIteratorIs0FalseGoto = ils.append(new GOTO(null));
                // If true body
                InstructionHandle ifIteratorIs0Body = ils.append(new ALOAD(VAR_ARRAY));
                ils.append(new ILOAD(VAR_I));
                ils.append(new PUSH(cp, 0));
                ils.append(new IASTORE());
                BranchHandle ifIteratorIs0Done = ils.append(new GOTO(null));

            // "else" if (i != 1)
            InstructionHandle beginIfIteratorIsNot1 = ils.append(new ILOAD(VAR_I));
            ils.append(new PUSH(cp, 1));
            BranchHandle ifIteratorIsNot1 = ils.append(new IF_ICMPNE(null));
                // false: else: so in this case: if (!(i != 1)): 
                ils.append(new ALOAD(VAR_ARRAY));
                ils.append(new ILOAD(VAR_I));
                ils.append(new PUSH(cp, 1));
                ils.append(new IASTORE());
                // done, go to i++;
                BranchHandle ifIteratorIsNot1FalseGoto = ils.append(new GOTO(null));

                // If true body (so if i != 1)..
                // create variable VAR_I_MIN_1 for array index (i-1)
                InstructionHandle ifIteratorIsNot1Body = ils.append(new ILOAD(VAR_I));
                ils.append(new PUSH(cp, 1));
                ils.append(new ISUB());
                ils.append(new PUSH(cp, ARRAY_SIZE));
                ils.append(new IREM());
                ils.append(new ISTORE(VAR_I_MIN_1)); // create int i_min_1 = (i - 1) % ARRAY_SIZE;
                // create variable VAR_I_MIN_2 for array index (i-2)
                ils.append(new ILOAD(VAR_I));
                ils.append(new PUSH(cp, 2));
                ils.append(new ISUB());
                ils.append(new PUSH(cp, ARRAY_SIZE));
                ils.append(new IREM());
                ils.append(new ISTORE(VAR_I_MIN_2)); // create int i_min_2 = (i - 2) % ARRAY_SIZE;
                // load the array values:
                ils.append(new ALOAD(VAR_ARRAY));
                ils.append(new ILOAD(VAR_I_MIN_1));
                ils.append(new IALOAD());
                ils.append(new ALOAD(VAR_ARRAY));
                ils.append(new ILOAD(VAR_I_MIN_2));
                ils.append(new IALOAD());
                // add the two values, and save them
                ils.append(new IADD());
                ils.append(new ISTORE(VAR_SUM));
                // add the new calculated number to the array
                ils.append(new ALOAD(VAR_ARRAY));
                ils.append(new ILOAD(VAR_II));
                ils.append(new ILOAD(VAR_SUM));
                ils.append(new IASTORE());
                // Done; go to i++;
                BranchHandle ifIteratorIsNot1Done = ils.append(new GOTO(null));

            // Increment i with 1
            InstructionHandle generalIfDoneGoto = ils.append(new IINC(VAR_I,1));

            // Goto that whil restart this loop:
            BranchHandle whileGotoBegin = ils.append(new GOTO(null)); // jumps to "beforeWhile"

        // We need something to jump to when done with the outer loop.
        InstructionHandle afterWhile = ils.append(new PUSH(cp, 0));
        ils.append(new ISTORE(VAR_JUMPTO));

        // While targets:
        whileCondition.setTarget(whileBody);
        whileConditionFalseGoto.setTarget(afterWhile);
        whileGotoBegin.setTarget(beforeWhile);
        // if (i == 0)
        ifIteratorIs0.setTarget(ifIteratorIs0Body);
        ifIteratorIs0FalseGoto.setTarget(beginIfIteratorIsNot1);
        ifIteratorIs0Done.setTarget(generalIfDoneGoto);
        // if (i == 1)
        ifIteratorIsNot1.setTarget(ifIteratorIsNot1Body);
        ifIteratorIsNot1FalseGoto.setTarget(generalIfDoneGoto);
        ifIteratorIsNot1Done.setTarget(generalIfDoneGoto);

        InstructionHandle ihss = il.insert(ihs,ils);
        il.redirectBranches(ihs, ihss);
        il.update();

        mg.setMaxStack();
        mg.setMaxLocals();
        mg.update();
        return mg.getMethod();
    }
}

更新

下面可以看到visitAll方法在net.sourceforge.pmd.AbstractRuleChainVisitor中注入失败后的完全错误

代码语言:javascript
复制
===== DaCapo 9.12 pmd starting =====
java.lang.reflect.InvocationTargetException
java.lang.reflect.InvocationTargetException
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    at java.lang.reflect.Method.invoke(Method.java:597)
    at org.dacapo.harness.Pmd.iterate(Pmd.java:58)
    at org.dacapo.harness.Benchmark.run(Benchmark.java:166)
    at org.dacapo.harness.TestHarness.runBenchmark(TestHarness.java:218)
    at org.dacapo.harness.TestHarness.main(TestHarness.java:171)
    at Harness.main(Harness.java:17)
Caused by: java.lang.ClassFormatError: LVTT entry for 'nodes' in class file net/sourceforge/pmd/AbstractRuleChainVisitor does not match any LVT entry
    at java.lang.ClassLoader.defineClass1(Native Method)
    at java.lang.ClassLoader.defineClassCond(ClassLoader.java:631)
    at java.lang.ClassLoader.defineClass(ClassLoader.java:615)
    at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:141)
    at java.net.URLClassLoader.defineClass(URLClassLoader.java:283)
    at java.net.URLClassLoader.access$000(URLClassLoader.java:58)
    at java.net.URLClassLoader$1.run(URLClassLoader.java:197)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(URLClassLoader.java:190)
    at org.dacapo.harness.DacapoClassLoader.loadClass(DacapoClassLoader.java:124)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:247)
    at java.lang.ClassLoader.defineClass1(Native Method)
    at java.lang.ClassLoader.defineClassCond(ClassLoader.java:631)
    at java.lang.ClassLoader.defineClass(ClassLoader.java:615)
    at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:141)
    at java.net.URLClassLoader.defineClass(URLClassLoader.java:283)
    at java.net.URLClassLoader.access$000(URLClassLoader.java:58)
    at java.net.URLClassLoader$1.run(URLClassLoader.java:197)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(URLClassLoader.java:190)
    at org.dacapo.harness.DacapoClassLoader.loadClass(DacapoClassLoader.java:124)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:247)
    at net.sourceforge.pmd.RuleSets.<init>(RuleSets.java:27)
    at net.sourceforge.pmd.RuleSetFactory.createRuleSets(RuleSetFactory.java:82)
    at net.sourceforge.pmd.RuleSetFactory.createRuleSets(RuleSetFactory.java:70)
    at net.sourceforge.pmd.PMD.doPMD(PMD.java:359)
    at net.sourceforge.pmd.PMD.main(PMD.java:415)
    ... 9 more

此方法的代码(由JD生成):

代码语言:javascript
复制
  public void visitAll(List<CompilationUnit> astCompilationUnits, RuleContext ctx)
  {
    initialize();
    clear();

    long start = System.nanoTime();
    indexNodes(astCompilationUnits, ctx);
    long end = System.nanoTime();
    Benchmark.mark(8, end - start, 1L);

    for (RuleSet ruleSet : this.ruleSetRules.keySet())
      if (ruleSet.applies(ctx.getSourceCodeFile()))
      {
        visits = 0;
        start = System.nanoTime();
        for (Rule rule : (List)this.ruleSetRules.get(ruleSet)) {
          List nodeNames = rule.getRuleChainVisits();
          for (int j = 0; j < nodeNames.size(); j++) {
            List nodes = (List)this.nodeNameToNodes.get(nodeNames.get(j));
            for (SimpleNode node : nodes)
            {
              while ((rule instanceof RuleReference)) {
                rule = ((RuleReference)rule).getRule();
              }
              visit(rule, node, ctx);
            }
            visits += nodes.size();
          }
          end = System.nanoTime();
          Benchmark.mark(1, rule.getName(), end - start, visits);
          start = end;
        }
      }
    int visits;
  }

这是一个可比较的错误,因为我的代码在“插入insertCodeInMethod”中忽略了堆栈位置增加的部分。这会导致参数在不静态的情况下与fibonacci代码中定义的变量发生冲突。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2013-10-07 08:06:01

LVTT代表LocalVariableTypeTableLVT代表LocalVariableTable。这些是在更改方法时必须调整或删除的调试信息。

顺便说一句,它并不是成功地将大量代码注入方法的好方法,因为它会创建各种错误来源,意味着重新发明轮子(构建编译器),并导致转换类中的代码重复。大多数使用代码注入/类文件转换的应用程序只会注入预编译方法的少量调用。

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/19119702

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档