2013-03-02 44 views
1

我正在尝试使用soot来测量特定类中每个函数的执行时间。我曾试着阅读Eric Bodden的Soot Framework的所有教程。使用Soot运行函数

我已经想出到目前为止是这样的,

package test; 

import java.util.Map; 

import soot.Body; 
import soot.BodyTransformer; 
import soot.PackManager; 
import soot.Scene; 
import soot.SootClass; 
import soot.SootMethod; 
import soot.Transform; 

public class MyMain { 
    public static void main(String[] args) { 

     PackManager 
       .v() 
       .getPack("jtp") 
       .add(new Transform("jtp.GotoInstrumenter", GotoInstrumenter.v())); 

     System.out.println(Scene.v().defaultClassPath()); 
     SootClass sootClass = Scene.v().loadClassAndSupport("test.TestClass"); 


     if (sootClass == null || !(sootClass instanceof SootClass)) { 
      System.out.println("sootClass not initialized"); 
      System.exit(0); 
     } else { 
      System.out.println(sootClass.getMethodCount()); 
     } 
     sootClass.setApplicationClass(); 
     for (SootMethod m : sootClass.getMethods()) { 

      try { 
       new Transform("jtp.GotoInstrumenter", GotoInstrumenter.v()) 
         .apply(m.retrieveActiveBody()); 
      } catch (Exception e) { 
       System.out.println("Exeception in for loop : " + e); 
      } 
     } 

    } 

} 

@SuppressWarnings("all") 
class GotoInstrumenter extends BodyTransformer { 
    private static GotoInstrumenter instance = new GotoInstrumenter(); 

    private GotoInstrumenter() { 
    } 

    public static GotoInstrumenter v() { 
     return instance; 
    } 

    protected void internalTransform(Body body, String phaseName, Map options) { 

     System.out.println("Processing method : " 
       + body.getMethod().getSignature()); 
    } 
} 

这里是我的TestClass

package test; 

public class TestClass { 
    public static void main(String[] args) { 
     System.out.println("I am in test class"); 
    } 
    public void f1(){ 
     System.out.println(Math.pow(2, 10)); 
    } 
} 

我已经用在Eclipse中添加变量,就像一个Java应用程序执行它添加sootclasses 。

这是我的程序输出:

C:\Users\Aks\Java\soot-2.5.0.jar;C:\Users\Aks\workspace\SootAnalysis\bin;D:\Installs\eclipse\plugins\ca.mcgill.sable.soot.lib_2.5.2\lib\sootclasses.jar;;C:\Program Files\Java\jre7\lib\rt.jar 
3 
Processing method : <test.TestClass: void <init>()> 
Processing method : <test.TestClass: void main(java.lang.String[])> 
Processing method : <test.TestClass: void f1()> 

现在我明白了烟尘已经阅读字节码,并通过所有方法步进。我想要做的是,运行它们中的每一个。这可能使用烟灰框架?

回答

2

可能这不是人们想要使用烟灰的原因。我不知道是否有任何优雅的方式来使用烟灰。但是,当然,你可以在这里利用反思的力量。添加在internalTransform结束以下行()方法应该工作:

TestClass.class.getMethod(body.getMethod().getName()).invoke(new TestClass());

当然,有没有像类的TestClass的init()方法。所以,你不想调用这个方法。另外,对于main()方法,您需要根据反射语法指定正确的参数。否则,会有例外。

希望它会有所帮助。谢谢。

+1

这是真的没有烟灰支持(甚至应该支持)。因此使用Reflection或仅使用shell脚本似乎是合适的。 – Eric 2013-03-03 10:58:25

+0

谢谢Eric和Mainul。很久以后我才意识到Soot只做静态分析。对不起这是我的错 – 2013-03-03 15:02:06