Search in sources :

Example 81 with SootMethod

use of soot.SootMethod in project soot by Sable.

the class DexMethod method createMethodSource.

protected MethodSource createMethodSource(final Method method) {
    return new MethodSource() {

        @Override
        public Body getBody(SootMethod m, String phaseName) {
            Body b = Jimple.v().newBody(m);
            try {
                // add the body of this code item
                DexBody dexBody = new DexBody(dexFile, method, declaringClass.getType());
                dexBody.jimplify(b, m);
            } catch (InvalidDalvikBytecodeException e) {
                String msg = "Warning: Invalid bytecode in method " + m + ": " + e;
                logger.debug("" + msg);
                Util.emptyBody(b);
                Util.addExceptionAfterUnit(b, "java.lang.RuntimeException", b.getUnits().getLast(), "Soot has detected that this method contains invalid Dalvik bytecode which would have throw an exception at runtime. [" + msg + "]");
                TypeAssigner.v().transform(b);
            }
            m.setActiveBody(b);
            return m.getActiveBody();
        }
    };
}
Also used : MethodSource(soot.MethodSource) SootMethod(soot.SootMethod) Body(soot.Body)

Example 82 with SootMethod

use of soot.SootMethod 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)

Example 83 with SootMethod

use of soot.SootMethod in project soot by Sable.

the class TemplatePrinter method printTo.

private void printTo(SootClass c) {
    String templateClassName = c.getName().replace('.', '_') + "_Maker";
    // imports
    println("import java.util.*;");
    println("import soot.*;");
    println("import soot.jimple.*;");
    println("import soot.util.*;");
    println("");
    // open class
    print("public class ");
    print(templateClassName);
    println(" {");
    println("private static Local localByName(Body b, String name) {");
    println("	for(Local l: b.getLocals()) {");
    println("		if(l.getName().equals(name))");
    println("			return l;");
    println("	}");
    println("	throw new IllegalArgumentException(\"No such local: \"+name);");
    println("}");
    // open main method
    indent();
    println("public void create() {");
    indent();
    println("SootClass c = new SootClass(\"" + c.getName() + "\");");
    println("c.setApplicationClass();");
    // todo modifiers, extends etc.
    println("Scene.v().addClass(c);");
    for (int i = 0; i < c.getMethodCount(); i++) {
        println("createMethod" + i + "(c);");
    }
    // close main method
    closeMethod();
    int i = 0;
    for (SootMethod m : c.getMethods()) {
        newMethod("createMethod" + i);
        // TODO modifiers, types
        println("SootMethod m = new SootMethod(\"" + m.getName() + "\",null,null);");
        println("Body b = Jimple.v().newBody(m);");
        println("m.setActiveBody(b);");
        if (!m.hasActiveBody())
            continue;
        Body b = m.getActiveBody();
        println("Chain<Local> locals = b.getLocals();");
        for (Local l : b.getLocals()) {
            // TODO properly treat primitive types
            println("locals.add(Jimple.v().newLocal(\"" + l.getName() + "\", RefType.v(\"" + l.getType() + "\")));");
        }
        println("Chain<Unit> units = b.getUnits();");
        StmtTemplatePrinter sw = new StmtTemplatePrinter(this, b.getUnits());
        for (Unit u : b.getUnits()) {
            u.apply(sw);
        }
        // TODO print traps
        closeMethod();
        i++;
    }
    // close class
    println("}");
}
Also used : SootMethod(soot.SootMethod) Local(soot.Local) Unit(soot.Unit) Body(soot.Body)

Example 84 with SootMethod

use of soot.SootMethod in project soot by Sable.

the class DavaPrinter method printTo.

public void printTo(SootClass cl, PrintWriter out) {
    // IterableSet packagesUsed = new IterableSet();
    IterableSet importList = new IterableSet();
    {
        String curPackage = cl.getJavaPackageName();
        if (!curPackage.equals("")) {
            out.println("package " + curPackage + ";");
            out.println();
        }
        if (cl.hasSuperclass()) {
            SootClass superClass = cl.getSuperclass();
            importList.add(superClass.toString());
        // packagesUsed.add(superClass.getJavaPackageName());
        }
        Iterator<SootClass> interfaceIt = cl.getInterfaces().iterator();
        while (interfaceIt.hasNext()) {
            String interfacePackage = ((SootClass) interfaceIt.next()).toString();
            if (!importList.contains(interfacePackage))
                importList.add(interfacePackage);
        // if (!packagesUsed.contains(interfacePackage))
        // packagesUsed.add(interfacePackage);
        }
        Iterator<SootMethod> methodIt = cl.methodIterator();
        while (methodIt.hasNext()) {
            SootMethod dm = (SootMethod) methodIt.next();
            if (dm.hasActiveBody()) {
                // packagesUsed = packagesUsed.union(((DavaBody) dm.getActiveBody()).get_PackagesUsed());
                importList = importList.union(((DavaBody) dm.getActiveBody()).getImportList());
            }
            Iterator<SootClass> eit = dm.getExceptions().iterator();
            while (eit.hasNext()) {
                String thrownPackage = eit.next().toString();
                if (!importList.contains(thrownPackage))
                    importList.add(thrownPackage);
            // if (!packagesUsed.contains(thrownPackage))
            // packagesUsed.add(thrownPackage);
            }
            Iterator<Type> pit = dm.getParameterTypes().iterator();
            while (pit.hasNext()) {
                Type t = (Type) pit.next();
                if (t instanceof RefType) {
                    String paramPackage = ((RefType) t).getSootClass().toString();
                    if (!importList.contains(paramPackage))
                        importList.add(paramPackage);
                // if (packagesUsed.contains(paramPackage) == false)
                // packagesUsed.add(paramPackage);
                }
            }
            Type t = dm.getReturnType();
            if (t instanceof RefType) {
                String returnPackage = ((RefType) t).getSootClass().toString();
                if (!importList.contains(returnPackage))
                    importList.add(returnPackage);
            // if (packagesUsed.contains(returnPackage) == false)
            // packagesUsed.add(returnPackage);
            }
        }
        Iterator<SootField> fieldIt = cl.getFields().iterator();
        while (fieldIt.hasNext()) {
            SootField f = (SootField) fieldIt.next();
            if (f.isPhantom())
                continue;
            Type t = f.getType();
            if (t instanceof RefType) {
                String fieldPackage = ((RefType) t).getSootClass().toString();
                if (!importList.contains(fieldPackage))
                    importList.add(fieldPackage);
            }
        }
        Iterator<String> pit = importList.iterator();
        List<String> toImport = new ArrayList<String>();
        while (pit.hasNext()) {
            /*
            	 * dont import any file which has currentPackage.className
            	 * dont import any file which starts with java.lang
            	 */
            String temp = (String) pit.next();
            // System.out.println("temp is "+temp);
            if (temp.indexOf("java.lang") > -1) {
                // problem is that we need to import sub packages java.lang.ref
                // for instance if the type is java.lang.ref.WeakReference
                String tempClassName = RemoveFullyQualifiedName.getClassName(temp);
                if (temp.equals("java.lang." + tempClassName)) {
                    // System.out.println("temp was not printed as it belongs to java.lang");
                    continue;
                }
            }
            if (curPackage.length() > 0 && temp.indexOf(curPackage) > -1) {
                // System.out.println("here  "+temp);
                continue;
            }
            if (cl.toString().equals(temp))
                continue;
            // System.out.println("printing"+);
            toImport.add(temp);
        }
        /*
             * Check that we are not importing two classes with the same last name
             * If yes then remove explicit import and import the whole package
             * else output explicit import statement
             */
        Iterator it = toImport.iterator();
        while (it.hasNext()) {
            String temp = (String) it.next();
            if (RemoveFullyQualifiedName.containsMultiple(toImport.iterator(), temp, null)) {
                // import package add *
                if (temp.lastIndexOf('.') > -1) {
                    temp = temp.substring(0, temp.lastIndexOf('.'));
                    out.println("import " + temp + ".*;");
                } else
                    throw new DecompilationException("Cant find the DOT . for fullyqualified name");
            } else {
                if (temp.lastIndexOf('.') == -1) {
                // dot not found this is a class belonging to this package so dont add
                } else
                    out.println("import " + temp + ";");
            }
        }
        boolean addNewLine = false;
        addNewLine = true;
        if (addNewLine)
            out.println();
        /*if (!packagesUsed.isEmpty())
                out.println();

            packagesUsed.add("java.lang");
            packagesUsed.add(curPackage);
            */
        Dava.v().set_CurrentPackageContext(importList);
        // Dava.v().set_CurrentPackageContext(packagesUsed);
        Dava.v().set_CurrentPackage(curPackage);
    }
    // Print class name + modifiers
    {
        String classPrefix = "";
        classPrefix = classPrefix + " " + Modifier.toString(cl.getModifiers());
        classPrefix = classPrefix.trim();
        if (!cl.isInterface()) {
            classPrefix = classPrefix + " class";
            classPrefix = classPrefix.trim();
        }
        out.print(classPrefix + " " + cl.getShortJavaStyleName());
    }
    // Print extension
    if (cl.hasSuperclass() && !(cl.getSuperclass().getName().equals("java.lang.Object"))) {
        String superClassName = cl.getSuperclass().getName();
        // Nomair Naeem 8th Feb 2006
        // also check if the super class name is not a fully qualified
        // name. in which case if the package is imported no need for
        // the long name
        superClassName = RemoveFullyQualifiedName.getReducedName(importList, superClassName, cl.getType());
        out.print(" extends " + superClassName + "");
    }
    // Print interfaces
    {
        Iterator<SootClass> interfaceIt = cl.getInterfaces().iterator();
        if (interfaceIt.hasNext()) {
            if (cl.isInterface())
                out.print(" extends ");
            else
                out.print(" implements ");
            out.print("" + (interfaceIt.next()).getName() + "");
            while (interfaceIt.hasNext()) out.print(", " + (interfaceIt.next()).getName() + "");
        }
    }
    out.println();
    out.println("{");
    // Print fields
    {
        Iterator<SootField> fieldIt = cl.getFields().iterator();
        if (fieldIt.hasNext()) {
            while (fieldIt.hasNext()) {
                SootField f = fieldIt.next();
                if (f.isPhantom())
                    continue;
                String declaration = null;
                Type fieldType = f.getType();
                String qualifiers = Modifier.toString(f.getModifiers()) + " ";
                qualifiers += RemoveFullyQualifiedName.getReducedName(importList, fieldType.toString(), fieldType);
                qualifiers = qualifiers.trim();
                if (qualifiers.equals(""))
                    declaration = Scene.v().quotedNameOf(f.getName());
                else
                    declaration = qualifiers + " " + Scene.v().quotedNameOf(f.getName()) + "";
                if (f.isFinal() && f.isStatic()) {
                    if (fieldType instanceof DoubleType && f.hasTag("DoubleConstantValueTag")) {
                        double val = ((DoubleConstantValueTag) f.getTag("DoubleConstantValueTag")).getDoubleValue();
                        out.println("    " + declaration + " = " + val + ";");
                    } else if (fieldType instanceof FloatType && f.hasTag("FloatConstantValueTag")) {
                        float val = ((FloatConstantValueTag) f.getTag("FloatConstantValueTag")).getFloatValue();
                        out.println("    " + declaration + " = " + val + "f;");
                    } else if (fieldType instanceof LongType && f.hasTag("LongConstantValueTag")) {
                        long val = ((LongConstantValueTag) f.getTag("LongConstantValueTag")).getLongValue();
                        out.println("    " + declaration + " = " + val + "l;");
                    } else if (fieldType instanceof CharType && f.hasTag("IntegerConstantValueTag")) {
                        int val = ((IntegerConstantValueTag) f.getTag("IntegerConstantValueTag")).getIntValue();
                        out.println("    " + declaration + " = '" + ((char) val) + "';");
                    } else if (fieldType instanceof BooleanType && f.hasTag("IntegerConstantValueTag")) {
                        int val = ((IntegerConstantValueTag) f.getTag("IntegerConstantValueTag")).getIntValue();
                        if (val == 0)
                            out.println("    " + declaration + " = false;");
                        else
                            out.println("    " + declaration + " = true;");
                    } else if ((fieldType instanceof IntType || fieldType instanceof ByteType || fieldType instanceof ShortType) && f.hasTag("IntegerConstantValueTag")) {
                        int val = ((IntegerConstantValueTag) f.getTag("IntegerConstantValueTag")).getIntValue();
                        out.println("    " + declaration + " = " + val + ";");
                    } else if (f.hasTag("StringConstantValueTag")) {
                        String val = ((StringConstantValueTag) f.getTag("StringConstantValueTag")).getStringValue();
                        out.println("    " + declaration + " = \"" + val + "\";");
                    } else {
                        // System.out.println("Couldnt find type of
                        // field"+f.getDeclaration());
                        out.println("    " + declaration + ";");
                    }
                } else // field is static final
                {
                    out.println("    " + declaration + ";");
                }
            }
        }
    }
    // Print methods
    {
        Iterator<SootMethod> methodIt = cl.methodIterator();
        if (methodIt.hasNext()) {
            if (cl.getMethodCount() != 0)
                out.println();
            while (methodIt.hasNext()) {
                SootMethod method = (SootMethod) methodIt.next();
                if (method.isPhantom())
                    continue;
                if (!Modifier.isAbstract(method.getModifiers()) && !Modifier.isNative(method.getModifiers())) {
                    if (!method.hasActiveBody())
                        throw new RuntimeException("method " + method.getName() + " has no active body!");
                    else
                        printTo(method.getActiveBody(), out);
                    if (methodIt.hasNext())
                        out.println();
                } else {
                    // if method is abstract then print the declaration
                    out.print("    ");
                    out.print(method.getDavaDeclaration());
                    out.println(";");
                    if (methodIt.hasNext())
                        out.println();
                }
            }
        }
    }
    if (G.v().SootClassNeedsDavaSuperHandlerClass.contains(cl)) {
        out.println("\n    private static class DavaSuperHandler{");
        out.println("         java.util.Vector myVector = new java.util.Vector();");
        out.println("\n         public Object get(int pos){");
        out.println("            return myVector.elementAt(pos);");
        out.println("         }");
        out.println("\n         public void store(Object obj){");
        out.println("            myVector.add(obj);");
        out.println("         }");
        out.println("    }");
    }
    out.println("}");
}
Also used : LongType(soot.LongType) ShortType(soot.ShortType) BooleanType(soot.BooleanType) IntegerConstantValueTag(soot.tagkit.IntegerConstantValueTag) ByteType(soot.ByteType) IterableSet(soot.util.IterableSet) SootClass(soot.SootClass) FloatType(soot.FloatType) IntType(soot.IntType) RefType(soot.RefType) RefType(soot.RefType) DoubleType(soot.DoubleType) FloatType(soot.FloatType) IntType(soot.IntType) ShortType(soot.ShortType) CharType(soot.CharType) LongType(soot.LongType) BooleanType(soot.BooleanType) ByteType(soot.ByteType) Type(soot.Type) DoubleType(soot.DoubleType) Iterator(java.util.Iterator) SootMethod(soot.SootMethod) SootField(soot.SootField) ArrayList(java.util.ArrayList) List(java.util.List) CharType(soot.CharType) FloatConstantValueTag(soot.tagkit.FloatConstantValueTag)

Example 85 with SootMethod

use of soot.SootMethod in project soot by Sable.

the class AbstractInterproceduralAnalysis method drawAsOneDot.

/**
 * Dump the interprocedural analysis result as a graph. One node / subgraph
 * for each analysed method that contains the method summary, and call-to
 * edges.
 *
 * Note: this graph does not show filtered-out methods for which a
 * conservative summary was asked via summaryOfUnanalysedMethod.
 *
 * @param name output filename
 *
 * @see fillDotGraph
 */
public void drawAsOneDot(String name) {
    DotGraph dot = new DotGraph(name);
    dot.setGraphLabel(name);
    dot.setGraphAttribute("compound", "true");
    // dot.setGraphAttribute("rankdir","LR");
    int id = 0;
    Map<SootMethod, Integer> idmap = new HashMap<SootMethod, Integer>();
    // draw sub-graph cluster
    for (SootMethod m : dg) {
        DotGraph sub = dot.createSubGraph("cluster" + id);
        DotGraphNode label = sub.drawNode("head" + id);
        idmap.put(m, id);
        sub.setGraphLabel("");
        label.setLabel("(" + order.get(m) + ") " + m.toString());
        label.setAttribute("fontsize", "18");
        label.setShape("box");
        if (data.containsKey(m)) {
            fillDotGraph("X" + id, data.get(m), sub);
        }
        id++;
    }
    // connect edges
    for (SootMethod m : dg) {
        for (SootMethod mm : dg.getSuccsOf(m)) {
            DotGraphEdge edge = dot.drawEdge("head" + idmap.get(m), "head" + idmap.get(mm));
            edge.setAttribute("ltail", "cluster" + idmap.get(m));
            edge.setAttribute("lhead", "cluster" + idmap.get(mm));
        }
    }
    File f = new File(SourceLocator.v().getOutputDir(), name + DotGraph.DOT_EXTENSION);
    dot.plot(f.getPath());
}
Also used : DotGraphEdge(soot.util.dot.DotGraphEdge) DotGraph(soot.util.dot.DotGraph) SootMethod(soot.SootMethod) DotGraphNode(soot.util.dot.DotGraphNode) File(java.io.File)

Aggregations

SootMethod (soot.SootMethod)237 SootClass (soot.SootClass)95 RefType (soot.RefType)56 ArrayList (java.util.ArrayList)49 Type (soot.Type)47 Unit (soot.Unit)47 Value (soot.Value)36 Stmt (soot.jimple.Stmt)35 Test (org.junit.Test)34 Local (soot.Local)34 Body (soot.Body)32 VoidType (soot.VoidType)31 PrimType (soot.PrimType)28 SootField (soot.SootField)28 BooleanType (soot.BooleanType)26 Iterator (java.util.Iterator)23 DoubleType (soot.DoubleType)23 FloatType (soot.FloatType)23 LongType (soot.LongType)23 InvokeExpr (soot.jimple.InvokeExpr)23