Search code examples
javaapistatic-analysissoot

Is it Possible to Use the Soot Analyses Without Calling soot.Main.main(...)?


I want to use Soot to do a static analysis of Java programs, including for example the control flow graph.

The various tutorials say that the "standard way" to use Soot is to create a main method where one adds custom transforms to the Soot pipeline and then call soot.Main.main(...):

public static void main(String[] args) {        
    PackManager.v().getPack("jtp").add(
         new Transform("jtp.gotoinstrumenter", GotoInstrumenter.v()));
    soot.Main.main(args);
}

Of course, this has some serious limitations if you want to use Soot in something else than a command line tool. For example, it is unclear to me whether it is even legal to call Soot's main method more than once in a program.

So does anyone know a possibility to use the Soot analysis tools directly through an API that is a bit more sophisticated?


Solution

  • The answer is yes. In your main you can set up the class that you working with:

    configure("../yourClasspath/");
    SootClass sootClass = Scene.v().loadClassAndSupport("className");
    sootClass.setApplicationClass();
    
    // Retrieve the method and its body
    SootMethod m = c.getMethodByName("methodName");
    Body b = m.retrieveActiveBody();
    
    // Instruments bytecode
    new YourTransform().transform(b);
    

    After that, you might build the CFG and run some analysis.

    It follows the configure method:

    public static void configure(String classpath) {
    
            Options.v().set_verbose(false);
            Options.v().set_keep_line_number(true);
            Options.v().set_src_prec(Options.src_prec_class);
            Options.v().set_soot_classpath(classpath);
            Options.v().set_prepend_classpath(true);
    
            PhaseOptions.v().setPhaseOption("bb", "off");
            PhaseOptions.v().setPhaseOption("tag.ln", "on");
            PhaseOptions.v().setPhaseOption("jj.a", "on");
            PhaseOptions.v().setPhaseOption("jj.ule", "on");
    
            Options.v().set_whole_program(true);
        }