Search in sources :

Example 1 with DavaBody

use of soot.dava.DavaBody in project soot by Sable.

the class ConstantFieldValueFinder method computeFieldToValuesAssignedList.

/*
	 * Go through all the methods in the application and make a mapping of className+methodName ---> values assigned
	 * There can obviously be more than one value assigned to each field
	 */
private void computeFieldToValuesAssignedList() {
    // go through all the classes
    Iterator classIt = appClasses.iterator();
    while (classIt.hasNext()) {
        SootClass s = (SootClass) classIt.next();
        debug("\ncomputeMethodSummaries", "Processing class " + s.getName());
        // go though all the methods
        Iterator methodIt = s.methodIterator();
        while (methodIt.hasNext()) {
            SootMethod m = (SootMethod) methodIt.next();
            DavaBody body = null;
            if (m.hasActiveBody()) {
                /*
					 * Added to try to fix the no active body found exception
					 */
                body = (DavaBody) m.getActiveBody();
            } else {
                continue;
            }
            ASTNode AST = (ASTNode) body.getUnits().getFirst();
            // find all definitions in the program
            AllDefinitionsFinder defFinder = new AllDefinitionsFinder();
            AST.apply(defFinder);
            Iterator<DefinitionStmt> allDefIt = defFinder.getAllDefs().iterator();
            // go through each definition
            while (allDefIt.hasNext()) {
                DefinitionStmt stmt = allDefIt.next();
                // debug("DefinitionStmt")
                Value left = stmt.getLeftOp();
                /*
					 * Only care if we have fieldRef on the left
					 */
                if (!(left instanceof FieldRef)) {
                    continue;
                }
                // we know definition is to a field
                debug("computeMethodSummaries method: " + m.getName(), "Field ref is: " + left);
                // Information we want to store is class of field and name of field and the right op
                FieldRef ref = (FieldRef) left;
                SootField field = ref.getField();
                /*
					 * Only care about fields with primtype
					 */
                if (!(field.getType() instanceof PrimType))
                    continue;
                String fieldName = field.getName();
                String declaringClass = field.getDeclaringClass().getName();
                debug("\tField Name: " + fieldName);
                debug("\tField DeclaringClass: " + declaringClass);
                // get the valueList for this class+field combo
                String combined = declaringClass + combiner + fieldName;
                Object temp = fieldToValues.get(combined);
                ArrayList valueList;
                if (temp == null) {
                    // no value of this field was yet assigned
                    valueList = new ArrayList();
                    fieldToValues.put(combined, valueList);
                } else {
                    valueList = (ArrayList) temp;
                }
                valueList.add(stmt.getRightOp());
            }
        // going through all the definitions
        }
    // going through methods of class s
    }
// going through  classes
}
Also used : AllDefinitionsFinder(soot.dava.toolkits.base.AST.traversals.AllDefinitionsFinder) FieldRef(soot.jimple.FieldRef) ArrayList(java.util.ArrayList) SootClass(soot.SootClass) DavaBody(soot.dava.DavaBody) Iterator(java.util.Iterator) ASTNode(soot.dava.internal.AST.ASTNode) Value(soot.Value) SootMethod(soot.SootMethod) PrimType(soot.PrimType) SootField(soot.SootField) DefinitionStmt(soot.jimple.DefinitionStmt)

Example 2 with DavaBody

use of soot.dava.DavaBody in project soot by Sable.

the class InterProceduralAnalyses method applyInterProceduralAnalyses.

/*
	 * Method is invoked by postProcessDava in PackManager
	 * if the transformations flag is true
	 * 
	 * All interproceduralAnalyses should be applied in here
	 */
public static void applyInterProceduralAnalyses() {
    Chain classes = Scene.v().getApplicationClasses();
    if (DEBUG)
        System.out.println("\n\nInvoking redundantFielduseEliminator");
    ConstantFieldValueFinder finder = new ConstantFieldValueFinder(classes);
    HashMap<String, Object> constantValueFields = finder.getFieldsWithConstantValues();
    if (DEBUG)
        finder.printConstantValueFields();
    /*
		 * The code above this gathers interprocedural information
		 * the code below this USES the interprocedural results
		 */
    Iterator it = classes.iterator();
    while (it.hasNext()) {
        // go though all the methods
        SootClass s = (SootClass) it.next();
        Iterator methodIt = s.methodIterator();
        while (methodIt.hasNext()) {
            SootMethod m = (SootMethod) methodIt.next();
            /*
				 * Adding try block to handle RuntimeException no active body found
				 */
            DavaBody body = null;
            if (m.hasActiveBody()) {
                body = (DavaBody) m.getActiveBody();
            } else {
                continue;
            }
            ASTNode AST = (ASTNode) body.getUnits().getFirst();
            if (!(AST instanceof ASTMethodNode))
                continue;
            Map options = PhaseOptions.v().getPhaseOptions("db.deobfuscate");
            boolean deobfuscate = PhaseOptions.getBoolean(options, "enabled");
            // System.out.println("force is "+force);
            if (deobfuscate) {
                if (DEBUG)
                    System.out.println("\nSTART CP Class:" + s.getName() + " Method: " + m.getName());
                CPApplication CPApp = new CPApplication((ASTMethodNode) AST, constantValueFields, finder.getClassNameFieldNameToSootFieldMapping());
                AST.apply(CPApp);
                if (DEBUG)
                    System.out.println("DONE CP for " + m.getName());
            }
            // expression simplification
            // SimplifyExpressions.DEBUG=true;
            AST.apply(new SimplifyExpressions());
            // SimplifyConditions.DEBUG=true;
            AST.apply(new SimplifyConditions());
            // condition elimination
            // EliminateConditions.DEBUG=true;
            AST.apply(new EliminateConditions((ASTMethodNode) AST));
            // the above should ALWAYS be followed by an unreachable code eliminator
            AST.apply(new UnreachableCodeEliminator(AST));
            // local variable cleanup
            AST.apply(new LocalVariableCleaner(AST));
            // VERY EXPENSIVE STAGE of redoing all analyses!!!!
            if (deobfuscate) {
                if (DEBUG)
                    System.out.println("reinvoking analyzeAST");
                UselessLabelFinder.DEBUG = false;
                body.analyzeAST();
            }
            // renaming should be applied as the last stage
            options = PhaseOptions.v().getPhaseOptions("db.renamer");
            boolean renamer = PhaseOptions.getBoolean(options, "enabled");
            // System.out.println("renaming is"+renamer);
            if (renamer) {
                applyRenamerAnalyses(AST, body);
            }
            // remove returns from void methods
            VoidReturnRemover.cleanClass(s);
        }
    }
}
Also used : Chain(soot.util.Chain) EliminateConditions(soot.dava.toolkits.base.AST.transformations.EliminateConditions) SootClass(soot.SootClass) UnreachableCodeEliminator(soot.dava.toolkits.base.AST.transformations.UnreachableCodeEliminator) DavaBody(soot.dava.DavaBody) SimplifyConditions(soot.dava.toolkits.base.AST.transformations.SimplifyConditions) Iterator(java.util.Iterator) ASTNode(soot.dava.internal.AST.ASTNode) SootMethod(soot.SootMethod) LocalVariableCleaner(soot.dava.toolkits.base.AST.transformations.LocalVariableCleaner) ASTMethodNode(soot.dava.internal.AST.ASTMethodNode) HashMap(java.util.HashMap) Map(java.util.Map) SimplifyExpressions(soot.dava.toolkits.base.AST.transformations.SimplifyExpressions) CPApplication(soot.dava.toolkits.base.AST.transformations.CPApplication)

Example 3 with DavaBody

use of soot.dava.DavaBody in project soot by Sable.

the class PackManager method postProcessDAVA.

/* post process for DAVA */
private void postProcessDAVA() {
    Chain<SootClass> appClasses = Scene.v().getApplicationClasses();
    Map<String, String> options = PhaseOptions.v().getPhaseOptions("db.transformations");
    boolean transformations = PhaseOptions.getBoolean(options, "enabled");
    /*
		 * apply analyses etc
		 */
    for (SootClass s : appClasses) {
        String fileName = SourceLocator.v().getFileNameFor(s, Options.v().output_format());
        /*
			 * Nomair A. Naeem 5-Jun-2005 Added to remove the *final* bug in
			 * Dava (often seen in AspectJ programs)
			 */
        DavaStaticBlockCleaner.v().staticBlockInlining(s);
        // remove returns from void methods
        VoidReturnRemover.cleanClass(s);
        // remove the default constructor if this is the only one present
        RemoveEmptyBodyDefaultConstructor.checkAndRemoveDefault(s);
        /*
			 * Nomair A. Naeem 1st March 2006 Check if we want to apply
			 * transformations one reason we might not want to do this is when
			 * gathering old metrics data!!
			 */
        // debug("analyzeAST","Advanced Analyses ALL DISABLED");
        logger.debug("Analyzing " + fileName + "... ");
        /*
			 * Nomair A. Naeem 29th Jan 2006 Added hook into going through each
			 * decompiled method again Need it for all the implemented AST
			 * analyses
			 */
        for (SootMethod m : s.getMethods()) {
            /*
				 * 3rd April 2006 Fixing RuntimeException caused when you
				 * retrieve an active body when one is not present
				 *
				 */
            if (m.hasActiveBody()) {
                DavaBody body = (DavaBody) m.getActiveBody();
                // System.out.println("body"+body.toString());
                if (transformations) {
                    body.analyzeAST();
                } else // if tansformations are enabled
                {
                    body.applyBugFixes();
                }
            } else
                continue;
        }
    }
    /*
		 * Nomair A. Naeem March 6th, 2006
		 *
		 * SHOULD BE INVOKED ONLY ONCE!!! If interprocedural analyses are turned
		 * off they are checked within this method.
		 *
		 * HAVE TO invoke this analysis since this invokes the renamer!!
		 */
    if (transformations) {
        InterProceduralAnalyses.applyInterProceduralAnalyses();
    }
    outputDava();
}
Also used : DavaBody(soot.dava.DavaBody)

Example 4 with DavaBody

use of soot.dava.DavaBody in project soot by Sable.

the class PackManager method runBodyPacks.

@SuppressWarnings("fallthrough")
private void runBodyPacks(SootClass c) {
    final int format = Options.v().output_format();
    if (format == Options.output_format_dava) {
        logger.debug("Decompiling {}...", c.getName());
        // January 13th, 2006 SootMethodAddedByDava is set to false for
        // SuperFirstStmtHandler
        G.v().SootMethodAddedByDava = false;
    } else {
        logger.debug("Transforming {}...", c.getName());
    }
    boolean produceBaf = false, produceGrimp = false, produceDava = false, produceJimple = true, produceShimple = false;
    switch(format) {
        case Options.output_format_none:
        case Options.output_format_xml:
        case Options.output_format_jimple:
        case Options.output_format_jimp:
        case Options.output_format_template:
        case Options.output_format_dex:
        case Options.output_format_force_dex:
            break;
        case Options.output_format_shimp:
        case Options.output_format_shimple:
            produceShimple = true;
            // FLIP produceJimple
            produceJimple = false;
            break;
        case Options.output_format_dava:
            produceDava = true;
        // FALL THROUGH
        case Options.output_format_grimp:
        case Options.output_format_grimple:
            produceGrimp = true;
            break;
        case Options.output_format_baf:
        case Options.output_format_b:
            produceBaf = true;
            break;
        case Options.output_format_jasmin:
        case Options.output_format_class:
        case Options.output_format_asm:
            produceGrimp = Options.v().via_grimp();
            produceBaf = !produceGrimp;
            break;
        default:
            throw new RuntimeException();
    }
    soot.xml.TagCollector tc = new soot.xml.TagCollector();
    boolean wholeShimple = Options.v().whole_shimple();
    if (Options.v().via_shimple())
        produceShimple = true;
    // here we create a copy of the methods so that transformers are able
    // to add method bodies during the following iteration;
    // such adding of methods happens in rare occasions: for instance when
    // resolving a method reference to a non-existing method, then this
    // method is created as a phantom method when phantom-refs are enabled
    ArrayList<SootMethod> methodsCopy = new ArrayList<SootMethod>(c.getMethods());
    for (SootMethod m : methodsCopy) {
        if (DEBUG) {
            if (m.getExceptions().size() != 0)
                System.out.println("PackManager printing out jimple body exceptions for method " + m.toString() + " " + m.getExceptions().toString());
        }
        if (!m.isConcrete())
            continue;
        if (produceShimple || wholeShimple) {
            ShimpleBody sBody = null;
            // whole shimple or not?
            {
                Body body = m.retrieveActiveBody();
                if (body instanceof ShimpleBody) {
                    sBody = (ShimpleBody) body;
                    if (!sBody.isSSA())
                        sBody.rebuild();
                } else {
                    sBody = Shimple.v().newBody(body);
                }
            }
            m.setActiveBody(sBody);
            PackManager.v().getPack("stp").apply(sBody);
            PackManager.v().getPack("sop").apply(sBody);
            if (produceJimple || (wholeShimple && !produceShimple))
                m.setActiveBody(sBody.toJimpleBody());
        }
        if (produceJimple) {
            Body body = m.retrieveActiveBody();
            // Change
            CopyPropagator.v().transform(body);
            ConditionalBranchFolder.v().transform(body);
            UnreachableCodeEliminator.v().transform(body);
            DeadAssignmentEliminator.v().transform(body);
            UnusedLocalEliminator.v().transform(body);
            PackManager.v().getPack("jtp").apply(body);
            if (Options.v().validate()) {
                body.validate();
            }
            PackManager.v().getPack("jop").apply(body);
            PackManager.v().getPack("jap").apply(body);
            if (Options.v().xml_attributes() && Options.v().output_format() != Options.output_format_jimple) {
                // System.out.println("collecting body tags");
                tc.collectBodyTags(body);
            }
        }
        if (produceGrimp) {
            m.setActiveBody(Grimp.v().newBody(m.getActiveBody(), "gb"));
            PackManager.v().getPack("gop").apply(m.getActiveBody());
        } else if (produceBaf) {
            m.setActiveBody(convertJimpleBodyToBaf(m));
        }
    }
    if (Options.v().xml_attributes() && Options.v().output_format() != Options.output_format_jimple) {
        processXMLForClass(c, tc);
    // System.out.println("processed xml for class");
    }
    if (produceDava) {
        for (SootMethod m : c.getMethods()) {
            if (!m.isConcrete())
                continue;
            // all the work done in decompilation is done in DavaBody which
            // is invoked from within newBody
            m.setActiveBody(Dava.v().newBody(m.getActiveBody()));
        }
        // could use G to add new method...................
        if (G.v().SootMethodAddedByDava) {
            // System.out.println("PACKMANAGER SAYS:----------------Have to
            // add the new method(s)");
            ArrayList<SootMethod> sootMethodsAdded = G.v().SootMethodsAdded;
            Iterator<SootMethod> it = sootMethodsAdded.iterator();
            while (it.hasNext()) {
                c.addMethod(it.next());
            }
            G.v().SootMethodsAdded = new ArrayList<SootMethod>();
            G.v().SootMethodAddedByDava = false;
        }
    }
// end if produceDava
}
Also used : TagCollector(soot.xml.TagCollector) TagCollector(soot.xml.TagCollector) ArrayList(java.util.ArrayList) ShimpleBody(soot.shimple.ShimpleBody) JimpleBody(soot.jimple.JimpleBody) ShimpleBody(soot.shimple.ShimpleBody) DavaBody(soot.dava.DavaBody) BafBody(soot.baf.BafBody)

Example 5 with DavaBody

use of soot.dava.DavaBody in project soot by Sable.

the class RemoveEmptyBodyDefaultConstructor method checkAndRemoveDefault.

public static void checkAndRemoveDefault(SootClass s) {
    debug("\n\nRemoveEmptyBodyDefaultConstructor----" + s.getName());
    List methods = s.getMethods();
    Iterator it = methods.iterator();
    List<SootMethod> constructors = new ArrayList<SootMethod>();
    while (it.hasNext()) {
        SootMethod method = (SootMethod) it.next();
        debug("method name is" + method.getName());
        if (method.getName().indexOf("<init>") > -1) {
            // constructor add to constructor list
            constructors.add(method);
        }
    }
    if (constructors.size() != 1) {
        // cant do anything since there are more than one constructors
        debug("class has more than one constructors cant do anything");
        return;
    }
    // only one constructor check its default (no arguments)
    SootMethod constructor = constructors.get(0);
    if (constructor.getParameterCount() != 0) {
        // can only deal with default constructors
        debug("constructor is not the default constructor");
        return;
    }
    debug("Check that the body is empty....and call to super contains no arguments and delete");
    if (!constructor.hasActiveBody()) {
        debug("No active body found for the default constructor");
        return;
    }
    Body body = constructor.getActiveBody();
    Chain units = ((DavaBody) body).getUnits();
    if (units.size() != 1) {
        debug(" DavaBody AST does not have single root");
        return;
    }
    ASTNode AST = (ASTNode) units.getFirst();
    if (!(AST instanceof ASTMethodNode))
        throw new RuntimeException("Starting node of DavaBody AST is not an ASTMethodNode");
    ASTMethodNode methodNode = (ASTMethodNode) AST;
    debug("got methodnode check body is empty and super has nothing in it");
    List<Object> subBodies = methodNode.get_SubBodies();
    if (subBodies.size() != 1) {
        debug("Method node does not have one subBody!!!");
        return;
    }
    List methodBody = (List) subBodies.get(0);
    if (methodBody.size() != 0) {
        debug("Method body size is greater than 1 so cant do nothing");
        return;
    }
    debug("Method body is empty...check super call is empty");
    if (((DavaBody) body).get_ConstructorExpr().getArgCount() != 0) {
        debug("call to super not empty");
        return;
    }
    debug("REMOVE METHOD");
    s.removeMethod(constructor);
}
Also used : Chain(soot.util.Chain) ArrayList(java.util.ArrayList) DavaBody(soot.dava.DavaBody) Iterator(java.util.Iterator) ASTNode(soot.dava.internal.AST.ASTNode) SootMethod(soot.SootMethod) List(java.util.List) ArrayList(java.util.ArrayList) ASTMethodNode(soot.dava.internal.AST.ASTMethodNode) Body(soot.Body) DavaBody(soot.dava.DavaBody)

Aggregations

DavaBody (soot.dava.DavaBody)7 ArrayList (java.util.ArrayList)3 Iterator (java.util.Iterator)3 SootMethod (soot.SootMethod)3 ASTNode (soot.dava.internal.AST.ASTNode)3 SootClass (soot.SootClass)2 ASTMethodNode (soot.dava.internal.AST.ASTMethodNode)2 Chain (soot.util.Chain)2 HashMap (java.util.HashMap)1 List (java.util.List)1 Map (java.util.Map)1 StringTokenizer (java.util.StringTokenizer)1 Body (soot.Body)1 PrimType (soot.PrimType)1 SootField (soot.SootField)1 Value (soot.Value)1 BafBody (soot.baf.BafBody)1 DecompilationException (soot.dava.DecompilationException)1 CPApplication (soot.dava.toolkits.base.AST.transformations.CPApplication)1 EliminateConditions (soot.dava.toolkits.base.AST.transformations.EliminateConditions)1