Search in sources :

Example 41 with Unit

use of soot.Unit in project soot by Sable.

the class DalvikTyper method assignType.

@Override
public void assignType(final Body b) {
    // Debug.printDbg("assignTypes: before: \n", b);
    constraints.clear();
    localObjList.clear();
    final Set<Unit> todoUnits = new HashSet<Unit>();
    // put constraints:
    for (Unit u : b.getUnits()) {
        StmtSwitch ss = new StmtSwitch() {

            @Override
            public void caseBreakpointStmt(BreakpointStmt stmt) {
            // nothing
            }

            @Override
            public void caseInvokeStmt(InvokeStmt stmt) {
                // add constraint
                DalvikTyper.v().setInvokeType(stmt.getInvokeExpr());
            }

            @Override
            public void caseAssignStmt(AssignStmt stmt) {
                // add constraint
                Value l = stmt.getLeftOp();
                Value r = stmt.getRightOp();
                // size in new array expression is of tye integer
                if (r instanceof NewArrayExpr) {
                    NewArrayExpr nae = (NewArrayExpr) r;
                    ValueBox sb = nae.getSizeBox();
                    if (sb.getValue() instanceof Local) {
                        DalvikTyper.v().setType(sb, IntType.v(), true);
                    }
                }
                // array index is of type integer
                if (stmt.containsArrayRef()) {
                    ArrayRef ar = stmt.getArrayRef();
                    ValueBox sb = ar.getIndexBox();
                    if (sb.getValue() instanceof Local) {
                        DalvikTyper.v().setType(sb, IntType.v(), true);
                    }
                }
                if (l instanceof Local && r instanceof Local) {
                    DalvikTyper.v().addConstraint(stmt.getLeftOpBox(), stmt.getRightOpBox());
                    return;
                }
                if (stmt.containsInvokeExpr()) {
                    DalvikTyper.v().setInvokeType(stmt.getInvokeExpr());
                }
                if (r instanceof Local) {
                    // l NOT local
                    Type leftType = stmt.getLeftOp().getType();
                    if (l instanceof ArrayRef && leftType instanceof UnknownType) {
                        // find type later
                        todoUnits.add(stmt);
                        return;
                    }
                    DalvikTyper.v().setType(stmt.getRightOpBox(), leftType, true);
                    return;
                }
                if (l instanceof Local) {
                    if (r instanceof UntypedConstant)
                        return;
                    for (Tag t : stmt.getTags()) {
                        if (r instanceof CastExpr) {
                            // do not check tag, since the tag is for the operand of the cast
                            break;
                        }
                        // Debug.printDbg("assign stmt tag: ", stmt, t);
                        if (t instanceof IntOpTag) {
                            checkExpr(r, IntType.v());
                            DalvikTyper.v().setType(stmt.getLeftOpBox(), IntType.v(), false);
                            return;
                        } else if (t instanceof FloatOpTag) {
                            checkExpr(r, FloatType.v());
                            DalvikTyper.v().setType(stmt.getLeftOpBox(), FloatType.v(), false);
                            return;
                        } else if (t instanceof DoubleOpTag) {
                            checkExpr(r, DoubleType.v());
                            DalvikTyper.v().setType(stmt.getLeftOpBox(), DoubleType.v(), false);
                            return;
                        } else if (t instanceof LongOpTag) {
                            checkExpr(r, LongType.v());
                            DalvikTyper.v().setType(stmt.getLeftOpBox(), LongType.v(), false);
                            return;
                        }
                    }
                    Type rightType = stmt.getRightOp().getType();
                    if (r instanceof ArrayRef && rightType instanceof UnknownType) {
                        // find type later
                        todoUnits.add(stmt);
                        return;
                    } else if (r instanceof CastExpr) {
                        CastExpr ce = (CastExpr) r;
                        Type castType = ce.getCastType();
                        if (castType instanceof PrimType) {
                            // check incoming primitive type
                            for (Tag t : stmt.getTags()) {
                                // Debug.printDbg("assign primitive type from stmt tag: ", stmt, t);
                                if (t instanceof IntOpTag) {
                                    DalvikTyper.v().setType(ce.getOpBox(), IntType.v(), false);
                                    return;
                                } else if (t instanceof FloatOpTag) {
                                    DalvikTyper.v().setType(ce.getOpBox(), FloatType.v(), false);
                                    return;
                                } else if (t instanceof DoubleOpTag) {
                                    DalvikTyper.v().setType(ce.getOpBox(), DoubleType.v(), false);
                                    return;
                                } else if (t instanceof LongOpTag) {
                                    DalvikTyper.v().setType(ce.getOpBox(), LongType.v(), false);
                                    return;
                                }
                            }
                        } else {
                            // incoming type is object
                            DalvikTyper.v().setType(ce.getOpBox(), RefType.v("java.lang.Object"), false);
                        }
                    }
                    DalvikTyper.v().setType(stmt.getLeftOpBox(), rightType, false);
                    return;
                }
            }

            @Override
            public void caseIdentityStmt(IdentityStmt stmt) {
                DalvikTyper.v().setType(stmt.getLeftOpBox(), stmt.getRightOp().getType(), false);
            }

            @Override
            public void caseEnterMonitorStmt(EnterMonitorStmt stmt) {
                // add constraint
                DalvikTyper.v().setType(stmt.getOpBox(), RefType.v("java.lang.Object"), true);
            }

            @Override
            public void caseExitMonitorStmt(ExitMonitorStmt stmt) {
                // add constraint
                DalvikTyper.v().setType(stmt.getOpBox(), RefType.v("java.lang.Object"), true);
            }

            @Override
            public void caseGotoStmt(GotoStmt stmt) {
            // nothing
            }

            @Override
            public void caseIfStmt(IfStmt stmt) {
                // add constraint
                Value c = stmt.getCondition();
                if (c instanceof BinopExpr) {
                    BinopExpr bo = (BinopExpr) c;
                    Value op1 = bo.getOp1();
                    Value op2 = bo.getOp2();
                    if (op1 instanceof Local && op2 instanceof Local) {
                        DalvikTyper.v().addConstraint(bo.getOp1Box(), bo.getOp2Box());
                    }
                }
            }

            @Override
            public void caseLookupSwitchStmt(LookupSwitchStmt stmt) {
                // add constraint
                DalvikTyper.v().setType(stmt.getKeyBox(), IntType.v(), true);
            }

            @Override
            public void caseNopStmt(NopStmt stmt) {
            // nothing
            }

            @Override
            public void caseRetStmt(RetStmt stmt) {
            // nothing
            }

            @Override
            public void caseReturnStmt(ReturnStmt stmt) {
                // add constraint
                DalvikTyper.v().setType(stmt.getOpBox(), b.getMethod().getReturnType(), true);
            }

            @Override
            public void caseReturnVoidStmt(ReturnVoidStmt stmt) {
            // nothing
            }

            @Override
            public void caseTableSwitchStmt(TableSwitchStmt stmt) {
                // add constraint
                DalvikTyper.v().setType(stmt.getKeyBox(), IntType.v(), true);
            }

            @Override
            public void caseThrowStmt(ThrowStmt stmt) {
                // add constraint
                DalvikTyper.v().setType(stmt.getOpBox(), RefType.v("java.lang.Object"), true);
            }

            @Override
            public void defaultCase(Object obj) {
                throw new RuntimeException("error: unknown statement: " + obj);
            }
        };
        u.apply(ss);
    }
    // <com.admob.android.ads.q: void a(android.os.Bundle,java.lang.String,java.lang.Object)>
    if (!todoUnits.isEmpty()) {
        // propagate array types
        UnitGraph ug = new ExceptionalUnitGraph(b);
        SimpleLocalDefs sld = new SimpleLocalDefs(ug);
        SimpleLocalUses slu = new SimpleLocalUses(b, sld);
        for (Unit u : b.getUnits()) {
            if (u instanceof DefinitionStmt) {
                // Debug.printDbg("U: ", u);
                DefinitionStmt ass = (DefinitionStmt) u;
                Value r = ass.getRightOp();
                if (r instanceof UntypedConstant)
                    continue;
                Type rType = r.getType();
                if (rType instanceof ArrayType && ass.getLeftOp() instanceof Local) {
                    // Debug.printDbg("propagate-array: checking ", u);
                    // propagate array type through aliases
                    Set<Unit> done = new HashSet<Unit>();
                    Set<DefinitionStmt> toDo = new HashSet<DefinitionStmt>();
                    toDo.add(ass);
                    while (!toDo.isEmpty()) {
                        DefinitionStmt currentUnit = toDo.iterator().next();
                        if (done.contains(currentUnit)) {
                            toDo.remove(currentUnit);
                            continue;
                        }
                        done.add(currentUnit);
                        for (UnitValueBoxPair uvbp : slu.getUsesOf(currentUnit)) {
                            Unit use = uvbp.unit;
                            Value l2 = null;
                            Value r2 = null;
                            if (use instanceof AssignStmt) {
                                AssignStmt ass2 = (AssignStmt) use;
                                l2 = ass2.getLeftOp();
                                r2 = ass2.getRightOp();
                                if (!(l2 instanceof Local) || !(r2 instanceof Local || r2 instanceof ArrayRef)) {
                                    // Debug.printDbg("propagate-array: skipping ", use);
                                    continue;
                                }
                                Type newType = null;
                                if (r2 instanceof Local) {
                                    List<LocalObj> lobjs = local2Obj.get(r2);
                                    newType = lobjs.get(0).t;
                                } else if (r2 instanceof ArrayRef) {
                                    ArrayRef ar = (ArrayRef) r2;
                                    // skip if use is in index
                                    if (ar.getIndex() == currentUnit.getLeftOp()) {
                                        // Debug.printDbg("skipping since local is used as index...");
                                        continue;
                                    }
                                    Local arBase = (Local) ar.getBase();
                                    List<LocalObj> lobjs = local2Obj.get(arBase);
                                    Type baseT = lobjs.get(0).t;
                                    if (baseT.toString().equals(("java.lang.Object"))) {
                                        // look for an array type, because an TTT[] is also an Object...
                                        ArrayType aTypeOtherThanObject = null;
                                        for (LocalObj lo : local2Obj.get(arBase)) {
                                            if (lo.t instanceof ArrayType) {
                                                aTypeOtherThanObject = (ArrayType) lo.t;
                                            }
                                        }
                                        if (aTypeOtherThanObject == null) {
                                            throw new RuntimeException("error: did not found array type for base " + arBase + " " + local2Obj.get(arBase) + " \n " + b);
                                        }
                                        baseT = aTypeOtherThanObject;
                                    }
                                    ArrayType at = (ArrayType) baseT;
                                    newType = at.getElementType();
                                } else {
                                    throw new RuntimeException("error: expected Local or ArrayRef. Got " + r2);
                                }
                                toDo.add((DefinitionStmt) use);
                                DalvikTyper.v().setType(ass2.getLeftOpBox(), newType, true);
                            }
                        }
                    }
                }
            }
        }
        for (Unit u : todoUnits) {
        // Debug.printDbg("todo unit: ", u);
        }
        while (!todoUnits.isEmpty()) {
            Unit u = todoUnits.iterator().next();
            if (!(u instanceof AssignStmt)) {
                throw new RuntimeException("error: expecting assign stmt. Got " + u);
            }
            AssignStmt ass = (AssignStmt) u;
            Value l = ass.getLeftOp();
            Value r = ass.getRightOp();
            ArrayRef ar = null;
            Local loc = null;
            if (l instanceof ArrayRef) {
                ar = (ArrayRef) l;
                loc = (Local) r;
            } else if (r instanceof ArrayRef) {
                ar = (ArrayRef) r;
                loc = (Local) l;
            } else {
                throw new RuntimeException("error: expecting an array ref. Got " + u);
            }
            Local baselocal = (Local) ar.getBase();
            if (!local2Obj.containsKey(baselocal)) {
                // Debug.printDbg("b: ", b.getMethod(), " \n", b);
                throw new RuntimeException("oups");
            }
            Type baseT = local2Obj.get(baselocal).get(0).t;
            if (baseT.toString().equals(("java.lang.Object"))) {
                // look for an array type, because an TTT[] is also an Object...
                ArrayType aTypeOtherThanObject = null;
                for (LocalObj lo : local2Obj.get(baselocal)) {
                    if (lo.t instanceof ArrayType) {
                        aTypeOtherThanObject = (ArrayType) lo.t;
                    }
                }
                if (aTypeOtherThanObject == null) {
                    throw new RuntimeException("did not found array type for base " + baselocal + " " + local2Obj.get(baselocal) + " \n " + b);
                }
                baseT = aTypeOtherThanObject;
            }
            ArrayType basetype = (ArrayType) baseT;
            // Debug.printDbg("v: ", ar, " base:", ar.getBase(), " base type: ", basetype, " type: ", ar.getType());
            Type t = basetype.getElementType();
            if (t instanceof UnknownType) {
                todoUnits.add(u);
                continue;
            } else {
                DalvikTyper.v().setType(ar == l ? ass.getRightOpBox() : ass.getLeftOpBox(), t, true);
                todoUnits.remove(u);
            }
        }
    // throw new RuntimeException("ouppppp");
    }
    // Debug.printDbg(IDalvikTyper.DEBUG, "list of constraints:");
    List<ValueBox> vbList = b.getUseAndDefBoxes();
    // clear constraints after local splitting and dead code eliminator
    List<Constraint> toRemove = new ArrayList<Constraint>();
    for (Constraint c : constraints) {
        if (!vbList.contains(c.l)) {
            // Debug.printDbg(IDalvikTyper.DEBUG, "warning: ", c.l, " not in locals! removing...");
            toRemove.add(c);
            continue;
        }
        if (!vbList.contains(c.r)) {
            // Debug.printDbg(IDalvikTyper.DEBUG, "warning: ", c.r, " not in locals! removing...");
            toRemove.add(c);
            continue;
        }
    }
    for (Constraint c : toRemove) constraints.remove(c);
    // keep only valid locals
    for (LocalObj lo : localObjList) {
        if (!vbList.contains(lo.vb)) {
            // Debug.printDbg(IDalvikTyper.DEBUG, "  -- removing vb: ", lo.vb, " with type ", lo.t);
            continue;
        }
        Local l = lo.getLocal();
        Type t = lo.t;
        if (localTemp.contains(l) && lo.isUse) {
        // Debug.printDbg(IDalvikTyper.DEBUG, "  /!\\ def already added for local ", l, "! for vb: ", lo.vb);
        } else {
            // Debug.printDbg(IDalvikTyper.DEBUG, "  * add type ", t, " to local ", l, " for vb: ", lo.vb);
            localTemp.add(l);
            typed.put(lo.vb, t);
        }
    }
    for (ValueBox vb : typed.keySet()) {
        if (vb.getValue() instanceof Local) {
            Local l = (Local) vb.getValue();
            localTyped.put(l, typed.get(vb));
        }
    }
    for (Constraint c : constraints) // Debug.printDbg(IDalvikTyper.DEBUG, "  -> constraint: ", c);
    for (ValueBox vb : typed.keySet()) {
    // Debug.printDbg(IDalvikTyper.DEBUG, "    typed: ", vb, " -> ", typed.get(vb));
    }
    for (Local l : localTyped.keySet()) {
    // Debug.printDbg(IDalvikTyper.DEBUG, "    localTyped: ", l, " -> ", localTyped.get(l));
    }
    while (!constraints.isEmpty()) {
        boolean update = false;
        for (Constraint c : constraints) {
            // Debug.printDbg(IDalvikTyper.DEBUG, "current constraint: ", c);
            Value l = c.l.getValue();
            Value r = c.r.getValue();
            if (l instanceof Local && r instanceof Constant) {
                Constant cst = (Constant) r;
                if (!localTyped.containsKey(l))
                    continue;
                Type lt = localTyped.get(l);
                // Debug.printDbg(IDalvikTyper.DEBUG, "would like to set type ", lt, " to constant: ", c);
                Value newValue = null;
                if (lt instanceof IntType || lt instanceof BooleanType || lt instanceof ShortType || lt instanceof CharType || lt instanceof ByteType) {
                    UntypedIntOrFloatConstant uf = (UntypedIntOrFloatConstant) cst;
                    newValue = uf.toIntConstant();
                } else if (lt instanceof FloatType) {
                    UntypedIntOrFloatConstant uf = (UntypedIntOrFloatConstant) cst;
                    newValue = uf.toFloatConstant();
                } else if (lt instanceof DoubleType) {
                    UntypedLongOrDoubleConstant ud = (UntypedLongOrDoubleConstant) cst;
                    newValue = ud.toDoubleConstant();
                } else if (lt instanceof LongType) {
                    UntypedLongOrDoubleConstant ud = (UntypedLongOrDoubleConstant) cst;
                    newValue = ud.toLongConstant();
                } else {
                    if (cst instanceof UntypedIntOrFloatConstant && ((UntypedIntOrFloatConstant) cst).value == 0) {
                        newValue = NullConstant.v();
                    // Debug.printDbg("new null constant for constraint ", c, " with l type: ", localTyped.get(l));
                    } else {
                        throw new RuntimeException("unknow type for constance: " + lt);
                    }
                }
                c.r.setValue(newValue);
                // Debug.printDbg(IDalvikTyper.DEBUG, "remove constraint: ", c);
                constraints.remove(c);
                update = true;
                break;
            } else if (l instanceof Local && r instanceof Local) {
                Local leftLocal = (Local) l;
                Local rightLocal = (Local) r;
                if (localTyped.containsKey(leftLocal)) {
                    Type leftLocalType = localTyped.get(leftLocal);
                    if (!localTyped.containsKey(rightLocal)) {
                        // Debug.printDbg(IDalvikTyper.DEBUG, "set type ", leftLocalType, " to local ", rightLocal);
                        rightLocal.setType(leftLocalType);
                        setLocalTyped(rightLocal, leftLocalType);
                    }
                    // Debug.printDbg(IDalvikTyper.DEBUG, "remove constraint: ", c);
                    constraints.remove(c);
                    update = true;
                    break;
                } else if (localTyped.containsKey(rightLocal)) {
                    Type rightLocalType = localTyped.get(rightLocal);
                    if (!localTyped.containsKey(leftLocal)) {
                        // Debug.printDbg(IDalvikTyper.DEBUG, "set type ", rightLocalType, " to local ", leftLocal);
                        leftLocal.setType(rightLocalType);
                        setLocalTyped(leftLocal, rightLocalType);
                    }
                    // Debug.printDbg(IDalvikTyper.DEBUG, "remove constraint: ", c);
                    constraints.remove(c);
                    update = true;
                    break;
                }
            } else if (l instanceof ArrayRef && r instanceof Local) {
                Local rightLocal = (Local) r;
                ArrayRef ar = (ArrayRef) l;
                Local base = (Local) ar.getBase();
                // Debug.printDbg(IDalvikTyper.DEBUG, "index: ", ar.getIndex());
                if (localTyped.containsKey(base)) {
                    Type t = localTyped.get(base);
                    // Debug.printDbg(IDalvikTyper.DEBUG, "type of local1: ", t, " ", t.getClass());
                    Type elementType = null;
                    if (t instanceof ArrayType) {
                        ArrayType at = (ArrayType) t;
                        elementType = at.getArrayElementType();
                    } else {
                        continue;
                    }
                    if (!localTyped.containsKey(rightLocal)) {
                        // Debug.printDbg(IDalvikTyper.DEBUG, "set type ", elementType, " to local ", r);
                        rightLocal.setType(elementType);
                        setLocalTyped(rightLocal, elementType);
                    }
                    // Debug.printDbg(IDalvikTyper.DEBUG, "remove constraint: ", c);
                    constraints.remove(c);
                    update = true;
                    break;
                }
            } else if (l instanceof Local && r instanceof ArrayRef) {
                Local leftLocal = (Local) l;
                ArrayRef ar = (ArrayRef) r;
                Local base = (Local) ar.getBase();
                if (localTyped.containsKey(base)) {
                    Type t = localTyped.get(base);
                    // Debug.printDbg(IDalvikTyper.DEBUG, "type of local2: ", t, " ", t.getClass());
                    Type elementType = null;
                    if (t instanceof ArrayType) {
                        ArrayType at = (ArrayType) t;
                        elementType = at.getArrayElementType();
                    } else {
                        continue;
                    }
                    if (!localTyped.containsKey(leftLocal)) {
                        // Debug.printDbg(IDalvikTyper.DEBUG, "set type ", elementType, " to local ", l);
                        leftLocal.setType(elementType);
                        setLocalTyped(leftLocal, elementType);
                    }
                    // Debug.printDbg(IDalvikTyper.DEBUG, "remove constraint: ", c);
                    constraints.remove(c);
                    update = true;
                    break;
                }
            } else {
                throw new RuntimeException("error: do not handling this kind of constraint: " + c);
            }
        }
        if (!update)
            break;
    }
    for (Unit u : b.getUnits()) {
        if (!(u instanceof AssignStmt))
            continue;
        AssignStmt ass = (AssignStmt) u;
        if (!(ass.getLeftOp() instanceof Local))
            continue;
        if (!(ass.getRightOp() instanceof UntypedConstant))
            continue;
        UntypedConstant uc = (UntypedConstant) ass.getRightOp();
        ass.setRightOp(uc.defineType(localTyped.get(ass.getLeftOp())));
    }
    // 
    for (Constraint c : constraints) {
        // Debug.printDbg(IDalvikTyper.DEBUG, "current constraint: ", c);
        Value l = c.l.getValue();
        Value r = c.r.getValue();
        if (l instanceof Local && r instanceof Constant) {
            if (r instanceof UntypedIntOrFloatConstant) {
                UntypedIntOrFloatConstant cst = (UntypedIntOrFloatConstant) r;
                Value newValue = null;
                if (cst.value != 0) {
                    // Debug.printDbg(IDalvikTyper.DEBUG, "[untyped constaints] set type int to non zero constant: ", c, " = ", cst.value);
                    newValue = cst.toIntConstant();
                } else {
                    // check if used in cast, just in case...
                    for (Unit u : b.getUnits()) {
                        for (ValueBox vb1 : u.getUseBoxes()) {
                            Value v1 = vb1.getValue();
                            if (v1 == l) {
                                // Debug.printDbg("local used in ", u);
                                if (u instanceof AssignStmt) {
                                    AssignStmt a = (AssignStmt) u;
                                    Value right = a.getRightOp();
                                    if (right instanceof CastExpr) {
                                        newValue = NullConstant.v();
                                    } else {
                                        newValue = cst.toIntConstant();
                                    }
                                } else if (u instanceof IfStmt) {
                                    // TODO check this better
                                    newValue = cst.toIntConstant();
                                }
                            }
                        }
                    }
                }
                if (newValue == null) {
                    throw new RuntimeException("error: no type found for local: " + l);
                }
                c.r.setValue(newValue);
            } else if (r instanceof UntypedLongOrDoubleConstant) {
                // Debug.printDbg(IDalvikTyper.DEBUG, "[untyped constaints] set type long to constant: ", c);
                Value newValue = ((UntypedLongOrDoubleConstant) r).toLongConstant();
                c.r.setValue(newValue);
            }
        }
    }
    // fix untypedconstants which have flown to an array index
    for (Unit u : b.getUnits()) {
        StmtSwitch sw = new StmtSwitch() {

            @Override
            public void caseBreakpointStmt(BreakpointStmt stmt) {
            // TODO Auto-generated method stub
            }

            @Override
            public void caseInvokeStmt(InvokeStmt stmt) {
                changeUntypedConstantsInInvoke(stmt.getInvokeExpr());
            }

            @Override
            public void caseAssignStmt(AssignStmt stmt) {
                if (stmt.getRightOp() instanceof NewArrayExpr) {
                    NewArrayExpr nae = (NewArrayExpr) stmt.getRightOp();
                    if (nae.getSize() instanceof UntypedConstant) {
                        UntypedIntOrFloatConstant uc = (UntypedIntOrFloatConstant) nae.getSize();
                        nae.setSize(uc.defineType(IntType.v()));
                    }
                } else if (stmt.getRightOp() instanceof UntypedConstant) {
                    UntypedConstant uc = (UntypedConstant) stmt.getRightOp();
                    Value l = stmt.getLeftOp();
                    Type lType = null;
                    if (l instanceof ArrayRef) {
                        ArrayRef ar = (ArrayRef) l;
                        Local baseLocal = (Local) ar.getBase();
                        ArrayType arrayType = (ArrayType) localTyped.get(baseLocal);
                        lType = arrayType.getElementType();
                    } else {
                        lType = l.getType();
                    }
                    stmt.setRightOp(uc.defineType(lType));
                } else if (stmt.getRightOp() instanceof InvokeExpr) {
                    changeUntypedConstantsInInvoke((InvokeExpr) stmt.getRightOp());
                }
                if (!stmt.containsArrayRef()) {
                    return;
                }
                ArrayRef ar = stmt.getArrayRef();
                if ((ar.getIndex() instanceof UntypedConstant)) {
                    UntypedIntOrFloatConstant uc = (UntypedIntOrFloatConstant) ar.getIndex();
                    ar.setIndex(uc.toIntConstant());
                }
                if (stmt.getLeftOp() instanceof ArrayRef && stmt.getRightOp() instanceof UntypedConstant) {
                    UntypedConstant uc = (UntypedConstant) stmt.getRightOp();
                    Local baseLocal = (Local) stmt.getArrayRef().getBase();
                    ArrayType lType = (ArrayType) localTyped.get(baseLocal);
                    Type elemType = lType.getElementType();
                    stmt.setRightOp(uc.defineType(elemType));
                }
            }

            @Override
            public void caseIdentityStmt(IdentityStmt stmt) {
            // TODO Auto-generated method stub
            }

            @Override
            public void caseEnterMonitorStmt(EnterMonitorStmt stmt) {
            // TODO Auto-generated method stub
            }

            @Override
            public void caseExitMonitorStmt(ExitMonitorStmt stmt) {
            // TODO Auto-generated method stub
            }

            @Override
            public void caseGotoStmt(GotoStmt stmt) {
            // TODO Auto-generated method stub
            }

            @Override
            public void caseIfStmt(IfStmt stmt) {
                Value c = stmt.getCondition();
                if (c instanceof BinopExpr) {
                    BinopExpr be = (BinopExpr) c;
                    Value op1 = be.getOp1();
                    Value op2 = be.getOp2();
                    if (op1 instanceof UntypedConstant || op2 instanceof UntypedConstant) {
                        if (op1 instanceof Local) {
                            Type t = localTyped.get(op1);
                            // Debug.printDbg("if op1 type: ", t);
                            UntypedConstant uc = (UntypedConstant) op2;
                            be.setOp2(uc.defineType(t));
                        } else if (op2 instanceof Local) {
                            Type t = localTyped.get(op2);
                            // Debug.printDbg("if op2 type: ", t);
                            UntypedConstant uc = (UntypedConstant) op1;
                            be.setOp1(uc.defineType(t));
                        } else if (op1 instanceof UntypedConstant && op2 instanceof UntypedConstant) {
                            if (op1 instanceof UntypedIntOrFloatConstant && op2 instanceof UntypedIntOrFloatConstant) {
                                UntypedIntOrFloatConstant uc1 = (UntypedIntOrFloatConstant) op1;
                                UntypedIntOrFloatConstant uc2 = (UntypedIntOrFloatConstant) op2;
                                // to int or float, it does not matter
                                be.setOp1(uc1.toIntConstant());
                                be.setOp2(uc2.toIntConstant());
                            } else if (op1 instanceof UntypedLongOrDoubleConstant && op2 instanceof UntypedLongOrDoubleConstant) {
                                UntypedLongOrDoubleConstant uc1 = (UntypedLongOrDoubleConstant) op1;
                                UntypedLongOrDoubleConstant uc2 = (UntypedLongOrDoubleConstant) op2;
                                // to long or double, it does not matter
                                be.setOp1(uc1.toLongConstant());
                                be.setOp2(uc2.toLongConstant());
                            } else {
                                throw new RuntimeException("error: expected same type of untyped constants. Got " + stmt);
                            }
                        } else if (op1 instanceof UntypedConstant || op2 instanceof UntypedConstant) {
                            if (op1 instanceof UntypedConstant) {
                                UntypedConstant uc = (UntypedConstant) op1;
                                be.setOp1(uc.defineType(op2.getType()));
                            } else if (op2 instanceof UntypedConstant) {
                                UntypedConstant uc = (UntypedConstant) op2;
                                be.setOp2(uc.defineType(op1.getType()));
                            }
                        } else {
                            throw new RuntimeException("error: expected local/untyped untyped/local or untyped/untyped. Got " + stmt);
                        }
                    }
                } else if (c instanceof UnopExpr) {
                } else {
                    throw new RuntimeException("error: expected binop or unop. Got " + stmt);
                }
            }

            @Override
            public void caseLookupSwitchStmt(LookupSwitchStmt stmt) {
            // TODO Auto-generated method stub
            }

            @Override
            public void caseNopStmt(NopStmt stmt) {
            // TODO Auto-generated method stub
            }

            @Override
            public void caseRetStmt(RetStmt stmt) {
            // TODO Auto-generated method stub
            }

            @Override
            public void caseReturnStmt(ReturnStmt stmt) {
                if (stmt.getOp() instanceof UntypedConstant) {
                    UntypedConstant uc = (UntypedConstant) stmt.getOp();
                    Type type = b.getMethod().getReturnType();
                    stmt.setOp(uc.defineType(type));
                }
            }

            @Override
            public void caseReturnVoidStmt(ReturnVoidStmt stmt) {
            // TODO Auto-generated method stub
            }

            @Override
            public void caseTableSwitchStmt(TableSwitchStmt stmt) {
            // TODO Auto-generated method stub
            }

            @Override
            public void caseThrowStmt(ThrowStmt stmt) {
            // TODO Auto-generated method stub
            }

            @Override
            public void defaultCase(Object obj) {
            // TODO Auto-generated method stub
            }
        };
        u.apply(sw);
    }
// fix untyped constants remaining
// Debug.printDbg("assignTypes: after: \n", b);
}
Also used : AssignStmt(soot.jimple.AssignStmt) ArrayList(java.util.ArrayList) UnopExpr(soot.jimple.UnopExpr) SimpleLocalUses(soot.toolkits.scalar.SimpleLocalUses) ByteType(soot.ByteType) Unit(soot.Unit) LongOpTag(soot.dexpler.tags.LongOpTag) FloatType(soot.FloatType) ArrayType(soot.ArrayType) DoubleOpTag(soot.dexpler.tags.DoubleOpTag) TableSwitchStmt(soot.jimple.TableSwitchStmt) InstanceInvokeExpr(soot.jimple.InstanceInvokeExpr) DynamicInvokeExpr(soot.jimple.DynamicInvokeExpr) InvokeExpr(soot.jimple.InvokeExpr) StaticInvokeExpr(soot.jimple.StaticInvokeExpr) GotoStmt(soot.jimple.GotoStmt) CastExpr(soot.jimple.CastExpr) PrimType(soot.PrimType) List(java.util.List) ArrayList(java.util.ArrayList) EnterMonitorStmt(soot.jimple.EnterMonitorStmt) HashSet(java.util.HashSet) ShortType(soot.ShortType) Local(soot.Local) NewArrayExpr(soot.jimple.NewArrayExpr) Value(soot.Value) CharType(soot.CharType) ReturnStmt(soot.jimple.ReturnStmt) ThrowStmt(soot.jimple.ThrowStmt) DefinitionStmt(soot.jimple.DefinitionStmt) BinopExpr(soot.jimple.BinopExpr) SimpleLocalDefs(soot.toolkits.scalar.SimpleLocalDefs) ExitMonitorStmt(soot.jimple.ExitMonitorStmt) LongType(soot.LongType) InvokeStmt(soot.jimple.InvokeStmt) NullConstant(soot.jimple.NullConstant) Constant(soot.jimple.Constant) ReturnVoidStmt(soot.jimple.ReturnVoidStmt) IntOpTag(soot.dexpler.tags.IntOpTag) RetStmt(soot.jimple.RetStmt) BreakpointStmt(soot.jimple.BreakpointStmt) FloatOpTag(soot.dexpler.tags.FloatOpTag) IntType(soot.IntType) ArrayRef(soot.jimple.ArrayRef) ExceptionalUnitGraph(soot.toolkits.graph.ExceptionalUnitGraph) StmtSwitch(soot.jimple.StmtSwitch) UnitValueBoxPair(soot.toolkits.scalar.UnitValueBoxPair) IdentityStmt(soot.jimple.IdentityStmt) BooleanType(soot.BooleanType) LookupSwitchStmt(soot.jimple.LookupSwitchStmt) UnknownType(soot.UnknownType) RefType(soot.RefType) ShortType(soot.ShortType) BooleanType(soot.BooleanType) ByteType(soot.ByteType) Type(soot.Type) UnknownType(soot.UnknownType) DoubleType(soot.DoubleType) FloatType(soot.FloatType) IntType(soot.IntType) CharType(soot.CharType) LongType(soot.LongType) ArrayType(soot.ArrayType) PrimType(soot.PrimType) ExceptionalUnitGraph(soot.toolkits.graph.ExceptionalUnitGraph) UnitGraph(soot.toolkits.graph.UnitGraph) IfStmt(soot.jimple.IfStmt) ValueBox(soot.ValueBox) NopStmt(soot.jimple.NopStmt) DoubleType(soot.DoubleType) LongOpTag(soot.dexpler.tags.LongOpTag) Tag(soot.tagkit.Tag) DoubleOpTag(soot.dexpler.tags.DoubleOpTag) IntOpTag(soot.dexpler.tags.IntOpTag) FloatOpTag(soot.dexpler.tags.FloatOpTag)

Example 42 with Unit

use of soot.Unit in project soot by Sable.

the class Validate method validateArrays.

public static void validateArrays(Body b) {
    Set<DefinitionStmt> definitions = new HashSet<DefinitionStmt>();
    Set<Unit> unitWithArrayRef = new HashSet<Unit>();
    for (Unit u : b.getUnits()) {
        if (u instanceof DefinitionStmt) {
            DefinitionStmt s = (DefinitionStmt) u;
            definitions.add(s);
        }
        List<ValueBox> uses = u.getUseBoxes();
        for (ValueBox vb : uses) {
            Value v = vb.getValue();
            if (v instanceof ArrayRef) {
                unitWithArrayRef.add(u);
            }
        }
    }
    final LocalDefs localDefs = LocalDefs.Factory.newLocalDefs(b, true);
    Set<Unit> toReplace = new HashSet<Unit>();
    for (Unit u : unitWithArrayRef) {
        boolean ok = false;
        List<ValueBox> uses = u.getUseBoxes();
        for (ValueBox vb : uses) {
            Value v = vb.getValue();
            if (v instanceof ArrayRef) {
                ArrayRef ar = (ArrayRef) v;
                Local base = (Local) ar.getBase();
                List<Unit> defs = localDefs.getDefsOfAt(base, u);
                // add aliases
                Set<Unit> alreadyHandled = new HashSet<Unit>();
                while (true) {
                    boolean isMore = false;
                    for (Unit d : defs) {
                        if (alreadyHandled.contains(d))
                            continue;
                        if (d instanceof AssignStmt) {
                            AssignStmt ass = (AssignStmt) d;
                            Value r = ass.getRightOp();
                            if (r instanceof Local) {
                                defs.addAll(localDefs.getDefsOfAt((Local) r, d));
                                alreadyHandled.add(d);
                                isMore = true;
                                break;
                            } else if (r instanceof ArrayRef) {
                                ArrayRef arrayRef = (ArrayRef) r;
                                Local l = (Local) arrayRef.getBase();
                                defs.addAll(localDefs.getDefsOfAt(l, d));
                                alreadyHandled.add(d);
                                isMore = true;
                                break;
                            }
                        }
                    }
                    if (!isMore)
                        break;
                }
                // System.out.println("def size "+ defs.size());
                for (Unit def : defs) {
                    // System.out.println("def u "+ def);
                    Value r = null;
                    if (def instanceof IdentityStmt) {
                        IdentityStmt idstmt = (IdentityStmt) def;
                        r = idstmt.getRightOp();
                    } else if (def instanceof AssignStmt) {
                        AssignStmt assStmt = (AssignStmt) def;
                        r = assStmt.getRightOp();
                    } else {
                        throw new RuntimeException("error: definition statement not an IdentityStmt nor an AssignStmt! " + def);
                    }
                    Type t = null;
                    if (r instanceof InvokeExpr) {
                        InvokeExpr ie = (InvokeExpr) r;
                        t = ie.getType();
                        // System.out.println("ie type: "+ t +" "+ t.getClass());
                        if (t instanceof ArrayType)
                            ok = true;
                    } else if (r instanceof FieldRef) {
                        FieldRef ref = (FieldRef) r;
                        t = ref.getType();
                        // System.out.println("fr type: "+ t +" "+ t.getClass());
                        if (t instanceof ArrayType)
                            ok = true;
                    } else if (r instanceof IdentityRef) {
                        IdentityRef ir = (IdentityRef) r;
                        t = ir.getType();
                        if (t instanceof ArrayType)
                            ok = true;
                    } else if (r instanceof CastExpr) {
                        CastExpr c = (CastExpr) r;
                        t = c.getType();
                        if (t instanceof ArrayType)
                            ok = true;
                    } else if (r instanceof ArrayRef) {
                    // we also check that this arrayref is correctly defined
                    } else if (r instanceof NewArrayExpr) {
                        ok = true;
                    } else if (r instanceof Local) {
                    } else if (r instanceof Constant) {
                    } else {
                        throw new RuntimeException("error: unknown right hand side of definition stmt " + def);
                    }
                    if (ok)
                        break;
                }
                if (ok)
                    break;
            }
        }
        if (!ok) {
            toReplace.add(u);
        }
    }
    int i = 0;
    for (Unit u : toReplace) {
        System.out.println("warning: incorrect array def, replacing unit " + u);
        // new object
        RefType throwableType = RefType.v("java.lang.Throwable");
        Local ttt = Jimple.v().newLocal("ttt_" + ++i, throwableType);
        b.getLocals().add(ttt);
        Value r = Jimple.v().newNewExpr(throwableType);
        Unit initLocalUnit = Jimple.v().newAssignStmt(ttt, r);
        // call <init> method with a string parameter for message
        List<String> pTypes = new ArrayList<String>();
        pTypes.add("java.lang.String");
        boolean isStatic = false;
        SootMethodRef mRef = Validate.makeMethodRef("java.lang.Throwable", "<init>", "", pTypes, isStatic);
        List<Value> parameters = new ArrayList<Value>();
        parameters.add(StringConstant.v("Soot updated this instruction"));
        InvokeExpr ie = Jimple.v().newSpecialInvokeExpr(ttt, mRef, parameters);
        Unit initMethod = Jimple.v().newInvokeStmt(ie);
        // throw exception
        Unit newUnit = Jimple.v().newThrowStmt(ttt);
        // change instruction in body
        b.getUnits().swapWith(u, newUnit);
        b.getUnits().insertBefore(initMethod, newUnit);
        b.getUnits().insertBefore(initLocalUnit, initMethod);
    // Exception a = throw new Exception();
    }
    DeadAssignmentEliminator.v().transform(b);
    UnusedLocalEliminator.v().transform(b);
    NopEliminator.v().transform(b);
    UnreachableCodeEliminator.v().transform(b);
}
Also used : AssignStmt(soot.jimple.AssignStmt) Constant(soot.jimple.Constant) StringConstant(soot.jimple.StringConstant) ArrayList(java.util.ArrayList) Unit(soot.Unit) ArrayRef(soot.jimple.ArrayRef) ArrayType(soot.ArrayType) RefType(soot.RefType) InvokeExpr(soot.jimple.InvokeExpr) IdentityRef(soot.jimple.IdentityRef) CastExpr(soot.jimple.CastExpr) IdentityStmt(soot.jimple.IdentityStmt) HashSet(java.util.HashSet) FieldRef(soot.jimple.FieldRef) SootMethodRef(soot.SootMethodRef) Local(soot.Local) LocalDefs(soot.toolkits.scalar.LocalDefs) RefType(soot.RefType) ArrayType(soot.ArrayType) Type(soot.Type) VoidType(soot.VoidType) NewArrayExpr(soot.jimple.NewArrayExpr) ValueBox(soot.ValueBox) Value(soot.Value) DefinitionStmt(soot.jimple.DefinitionStmt)

Example 43 with Unit

use of soot.Unit in project soot by Sable.

the class DavaBody method copy_Body.

/*
	 *  Copy and patch a GrimpBody so that it can be used to output Java.
	 */
private void copy_Body(Body body) {
    if (!(body instanceof GrimpBody))
        throw new RuntimeException("You can only create a DavaBody from a GrimpBody!");
    GrimpBody grimpBody = (GrimpBody) body;
    /*
		 *  Import body contents from Grimp.
		 */
    {
        HashMap<Switchable, Switchable> bindings = new HashMap<Switchable, Switchable>();
        HashMap<Unit, Unit> reverse_binding = new HashMap<Unit, Unit>();
        // Clone units in body's statement list
        for (Unit original : grimpBody.getUnits()) {
            Unit copy = (Unit) original.clone();
            // Add cloned unit to our unitChain.
            getUnits().addLast(copy);
            // Build old <-> new map to be able to patch up references to other units
            // within the cloned units. (these are still refering to the original
            // unit objects).
            bindings.put(original, copy);
            reverse_binding.put(copy, original);
        }
        // patch up the switch statments
        for (Unit u : getUnits()) {
            Stmt s = (Stmt) u;
            if (s instanceof TableSwitchStmt) {
                TableSwitchStmt ts = (TableSwitchStmt) s;
                TableSwitchStmt original_switch = (TableSwitchStmt) reverse_binding.get(u);
                ts.setDefaultTarget((Unit) bindings.get(original_switch.getDefaultTarget()));
                LinkedList<Unit> new_target_list = new LinkedList<Unit>();
                int target_count = ts.getHighIndex() - ts.getLowIndex() + 1;
                for (int i = 0; i < target_count; i++) new_target_list.add((Unit) bindings.get(original_switch.getTarget(i)));
                ts.setTargets(new_target_list);
            }
            if (s instanceof LookupSwitchStmt) {
                LookupSwitchStmt ls = (LookupSwitchStmt) s;
                LookupSwitchStmt original_switch = (LookupSwitchStmt) reverse_binding.get(u);
                ls.setDefaultTarget((Unit) bindings.get(original_switch.getDefaultTarget()));
                Unit[] new_target_list = new Unit[original_switch.getTargetCount()];
                for (int i = 0; i < original_switch.getTargetCount(); i++) new_target_list[i] = (Unit) (bindings.get(original_switch.getTarget(i)));
                ls.setTargets(new_target_list);
                ls.setLookupValues(original_switch.getLookupValues());
            }
        }
        // Clone locals.
        for (Local original : grimpBody.getLocals()) {
            Local copy = Dava.v().newLocal(original.getName(), original.getType());
            getLocals().add(copy);
            // Build old <-> new mapping.
            bindings.put(original, copy);
        }
        // Patch up references within units using our (old <-> new) map.
        for (UnitBox box : getAllUnitBoxes()) {
            Unit newObject, oldObject = box.getUnit();
            // it's clone.
            if ((newObject = (Unit) bindings.get(oldObject)) != null)
                box.setUnit(newObject);
        }
        // backpatch all local variables.
        for (ValueBox vb : getUseAndDefBoxes()) {
            if (vb.getValue() instanceof Local)
                vb.setValue((Value) bindings.get(vb.getValue()));
        }
        // clone the traps
        for (Trap originalTrap : grimpBody.getTraps()) {
            Trap cloneTrap = (Trap) originalTrap.clone();
            Unit handlerUnit = (Unit) bindings.get(originalTrap.getHandlerUnit());
            cloneTrap.setHandlerUnit(handlerUnit);
            cloneTrap.setBeginUnit((Unit) bindings.get(originalTrap.getBeginUnit()));
            cloneTrap.setEndUnit((Unit) bindings.get(originalTrap.getEndUnit()));
            getTraps().add(cloneTrap);
        }
    }
    /*
		 *  Add one level of indirection to "if", "switch", and exceptional control flow.
		 *  This allows for easy handling of breaks, continues and exceptional loops.
		 */
    {
        PatchingChain<Unit> units = getUnits();
        Iterator<Unit> it = units.snapshotIterator();
        while (it.hasNext()) {
            Unit u = it.next();
            Stmt s = (Stmt) u;
            if (s instanceof IfStmt) {
                IfStmt ifs = (IfStmt) s;
                JGotoStmt jgs = new JGotoStmt((Unit) units.getSuccOf(u));
                units.insertAfter(jgs, u);
                JGotoStmt jumper = new JGotoStmt((Unit) ifs.getTarget());
                units.insertAfter(jumper, jgs);
                ifs.setTarget((Unit) jumper);
            } else if (s instanceof TableSwitchStmt) {
                TableSwitchStmt tss = (TableSwitchStmt) s;
                int targetCount = tss.getHighIndex() - tss.getLowIndex() + 1;
                for (int i = 0; i < targetCount; i++) {
                    JGotoStmt jgs = new JGotoStmt((Unit) tss.getTarget(i));
                    units.insertAfter(jgs, tss);
                    tss.setTarget(i, (Unit) jgs);
                }
                JGotoStmt jgs = new JGotoStmt((Unit) tss.getDefaultTarget());
                units.insertAfter(jgs, tss);
                tss.setDefaultTarget((Unit) jgs);
            } else if (s instanceof LookupSwitchStmt) {
                LookupSwitchStmt lss = (LookupSwitchStmt) s;
                for (int i = 0; i < lss.getTargetCount(); i++) {
                    JGotoStmt jgs = new JGotoStmt((Unit) lss.getTarget(i));
                    units.insertAfter(jgs, lss);
                    lss.setTarget(i, (Unit) jgs);
                }
                JGotoStmt jgs = new JGotoStmt((Unit) lss.getDefaultTarget());
                units.insertAfter(jgs, lss);
                lss.setDefaultTarget((Unit) jgs);
            }
        }
        for (Trap t : getTraps()) {
            JGotoStmt jgs = new JGotoStmt((Unit) t.getHandlerUnit());
            units.addLast(jgs);
            t.setHandlerUnit((Unit) jgs);
        }
    }
    /*
		 *  Fix up the grimp representations of statements so they can be compiled as java.
		 */
    {
        for (Local l : getLocals()) {
            Type t = l.getType();
            if (t instanceof RefType) {
                RefType rt = (RefType) t;
                String className = rt.getSootClass().toString();
                String packageName = rt.getSootClass().getJavaPackageName();
                String classPackageName = packageName;
                if (className.lastIndexOf('.') > 0) {
                    // 0 doesnt make sense
                    classPackageName = className.substring(0, className.lastIndexOf('.'));
                }
                if (!packageName.equals(classPackageName))
                    throw new DecompilationException("Unable to retrieve package name for identifier. Please report to developer.");
                addToImportList(className);
            // addPackage(rt.getSootClass().getJavaPackageName());
            }
        }
        for (Unit u : getUnits()) {
            Stmt s = (Stmt) u;
            if (s instanceof IfStmt)
                javafy(((IfStmt) s).getConditionBox());
            else if (s instanceof ThrowStmt)
                javafy(((ThrowStmt) s).getOpBox());
            else if (s instanceof TableSwitchStmt)
                javafy(((TableSwitchStmt) s).getKeyBox());
            else if (s instanceof LookupSwitchStmt)
                javafy(((LookupSwitchStmt) s).getKeyBox());
            else if (s instanceof MonitorStmt)
                javafy(((MonitorStmt) s).getOpBox());
            else if (s instanceof DefinitionStmt) {
                DefinitionStmt ds = (DefinitionStmt) s;
                javafy(ds.getRightOpBox());
                javafy(ds.getLeftOpBox());
                if (ds.getRightOp() instanceof IntConstant)
                    ds.getRightOpBox().setValue(DIntConstant.v(((IntConstant) ds.getRightOp()).value, ds.getLeftOp().getType()));
            } else if (s instanceof ReturnStmt) {
                ReturnStmt rs = (ReturnStmt) s;
                if (rs.getOp() instanceof IntConstant)
                    rs.getOpBox().setValue(DIntConstant.v(((IntConstant) rs.getOp()).value, body.getMethod().getReturnType()));
                else
                    javafy(rs.getOpBox());
            } else if (s instanceof InvokeStmt)
                javafy(((InvokeStmt) s).getInvokeExprBox());
        }
    }
    /*
		 *  Convert references to "this" and parameters.
		 */
    {
        for (Unit u : getUnits()) {
            Stmt s = (Stmt) u;
            if (s instanceof IdentityStmt) {
                IdentityStmt ids = (IdentityStmt) s;
                Value ids_rightOp = ids.getRightOp();
                Value ids_leftOp = ids.getLeftOp();
                if ((ids_leftOp instanceof Local) && (ids_rightOp instanceof ThisRef)) {
                    Local thisLocal = (Local) ids_leftOp;
                    thisLocals.add(thisLocal);
                    thisLocal.setName("this");
                }
            }
            if (s instanceof DefinitionStmt) {
                DefinitionStmt ds = (DefinitionStmt) s;
                Value rightOp = ds.getRightOp();
                if (rightOp instanceof ParameterRef)
                    pMap.put(((ParameterRef) rightOp).getIndex(), ds.getLeftOp());
                if (rightOp instanceof CaughtExceptionRef)
                    caughtrefs.add((CaughtExceptionRef) rightOp);
            }
        }
    }
    /*
		 *  Fix up the calls to other constructors.  Note, this is seriously underbuilt.
		 */
    {
        for (Unit u : getUnits()) {
            Stmt s = (Stmt) u;
            if (s instanceof InvokeStmt) {
                InvokeStmt ivs = (InvokeStmt) s;
                Value ie = ivs.getInvokeExpr();
                if (ie instanceof InstanceInvokeExpr) {
                    InstanceInvokeExpr iie = (InstanceInvokeExpr) ie;
                    Value base = iie.getBase();
                    if ((base instanceof Local) && (((Local) base).getName().equals("this"))) {
                        SootMethodRef m = iie.getMethodRef();
                        String name = m.name();
                        if ((name.equals(SootMethod.constructorName)) || (name.equals(SootMethod.staticInitializerName))) {
                            if (constructorUnit != null)
                                throw new RuntimeException("More than one candidate for constructor found.");
                            constructorExpr = iie;
                            constructorUnit = (Unit) s;
                        }
                    }
                }
            }
        }
    }
}
Also used : InvokeStmt(soot.jimple.InvokeStmt) CaughtExceptionRef(soot.jimple.CaughtExceptionRef) HashMap(java.util.HashMap) Switchable(soot.util.Switchable) Unit(soot.Unit) AugmentedStmt(soot.dava.internal.asg.AugmentedStmt) JGotoStmt(soot.jimple.internal.JGotoStmt) IfStmt(soot.jimple.IfStmt) LookupSwitchStmt(soot.jimple.LookupSwitchStmt) Stmt(soot.jimple.Stmt) DefinitionStmt(soot.jimple.DefinitionStmt) InvokeStmt(soot.jimple.InvokeStmt) ThrowStmt(soot.jimple.ThrowStmt) IdentityStmt(soot.jimple.IdentityStmt) TableSwitchStmt(soot.jimple.TableSwitchStmt) MonitorStmt(soot.jimple.MonitorStmt) ReturnStmt(soot.jimple.ReturnStmt) RefType(soot.RefType) TableSwitchStmt(soot.jimple.TableSwitchStmt) Iterator(java.util.Iterator) IntConstant(soot.jimple.IntConstant) DIntConstant(soot.dava.internal.javaRep.DIntConstant) GrimpBody(soot.grimp.GrimpBody) IdentityStmt(soot.jimple.IdentityStmt) UnitBox(soot.UnitBox) PatchingChain(soot.PatchingChain) SootMethodRef(soot.SootMethodRef) JimpleLocal(soot.jimple.internal.JimpleLocal) Local(soot.Local) InstanceInvokeExpr(soot.jimple.InstanceInvokeExpr) LookupSwitchStmt(soot.jimple.LookupSwitchStmt) Trap(soot.Trap) MonitorStmt(soot.jimple.MonitorStmt) LinkedList(java.util.LinkedList) JGotoStmt(soot.jimple.internal.JGotoStmt) Type(soot.Type) RefType(soot.RefType) IntType(soot.IntType) IfStmt(soot.jimple.IfStmt) ParameterRef(soot.jimple.ParameterRef) DThisRef(soot.dava.internal.javaRep.DThisRef) ThisRef(soot.jimple.ThisRef) ValueBox(soot.ValueBox) Value(soot.Value) ThrowStmt(soot.jimple.ThrowStmt) DefinitionStmt(soot.jimple.DefinitionStmt) ReturnStmt(soot.jimple.ReturnStmt)

Example 44 with Unit

use of soot.Unit in project soot by Sable.

the class ConstructorFolder method internalTransform.

/**
 * This method change all new Obj/<init>(args) pairs to new Obj(args) idioms.
 */
protected void internalTransform(Body b, String phaseName, Map options) {
    GrimpBody body = (GrimpBody) b;
    if (Options.v().verbose())
        logger.debug("[" + body.getMethod().getName() + "] Folding constructors...");
    Chain units = body.getUnits();
    List<Unit> stmtList = new ArrayList<Unit>();
    stmtList.addAll(units);
    Iterator<Unit> it = stmtList.iterator();
    LocalUses localUses = LocalUses.Factory.newLocalUses(b);
    /* fold in NewExpr's with specialinvoke's */
    while (it.hasNext()) {
        Stmt s = (Stmt) it.next();
        if (!(s instanceof AssignStmt))
            continue;
        /* this should be generalized to ArrayRefs */
        Value lhs = ((AssignStmt) s).getLeftOp();
        if (!(lhs instanceof Local))
            continue;
        Value rhs = ((AssignStmt) s).getRightOp();
        if (!(rhs instanceof NewExpr))
            continue;
        /* TO BE IMPLEMENTED LATER: move any copy of the object reference
             for lhs down beyond the NewInvokeExpr, with the rationale
             being that you can't modify the object before the constructor
             call in any case.

             Also, do note that any new's (object creation) without
             corresponding constructors must be dead. */
        List lu = localUses.getUsesOf(s);
        Iterator luIter = lu.iterator();
        boolean MadeNewInvokeExpr = false;
        while (luIter.hasNext()) {
            Unit use = ((UnitValueBoxPair) (luIter.next())).unit;
            if (!(use instanceof InvokeStmt))
                continue;
            InvokeStmt is = (InvokeStmt) use;
            if (!(is.getInvokeExpr() instanceof SpecialInvokeExpr) || lhs != ((SpecialInvokeExpr) is.getInvokeExpr()).getBase())
                continue;
            SpecialInvokeExpr oldInvoke = ((SpecialInvokeExpr) is.getInvokeExpr());
            LinkedList invokeArgs = new LinkedList();
            for (int i = 0; i < oldInvoke.getArgCount(); i++) invokeArgs.add(oldInvoke.getArg(i));
            AssignStmt constructStmt = Grimp.v().newAssignStmt((AssignStmt) s);
            constructStmt.setRightOp(Grimp.v().newNewInvokeExpr(((NewExpr) rhs).getBaseType(), oldInvoke.getMethodRef(), invokeArgs));
            MadeNewInvokeExpr = true;
            use.redirectJumpsToThisTo(constructStmt);
            units.insertBefore(constructStmt, use);
            units.remove(use);
        }
        if (MadeNewInvokeExpr) {
            units.remove(s);
        }
    }
}
Also used : Chain(soot.util.Chain) InvokeStmt(soot.jimple.InvokeStmt) AssignStmt(soot.jimple.AssignStmt) SpecialInvokeExpr(soot.jimple.SpecialInvokeExpr) ArrayList(java.util.ArrayList) Local(soot.Local) SimpleLocalUses(soot.toolkits.scalar.SimpleLocalUses) LocalUses(soot.toolkits.scalar.LocalUses) Unit(soot.Unit) LinkedList(java.util.LinkedList) InvokeStmt(soot.jimple.InvokeStmt) Stmt(soot.jimple.Stmt) AssignStmt(soot.jimple.AssignStmt) Value(soot.Value) NewExpr(soot.jimple.NewExpr) Iterator(java.util.Iterator) UnitValueBoxPair(soot.toolkits.scalar.UnitValueBoxPair) GrimpBody(soot.grimp.GrimpBody) ArrayList(java.util.ArrayList) LinkedList(java.util.LinkedList) List(java.util.List)

Example 45 with Unit

use of soot.Unit in project soot by Sable.

the class PackedSwitchInstruction method switchStatement.

@Override
protected Stmt switchStatement(DexBody body, Instruction targetData, Local key) {
    PackedSwitchPayload i = (PackedSwitchPayload) targetData;
    List<? extends SwitchElement> seList = i.getSwitchElements();
    // the default target always follows the switch statement
    int defaultTargetAddress = codeAddress + instruction.getCodeUnits();
    Unit defaultTarget = body.instructionAtAddress(defaultTargetAddress).getUnit();
    List<IntConstant> lookupValues = new ArrayList<IntConstant>();
    List<Unit> targets = new ArrayList<Unit>();
    for (SwitchElement se : seList) {
        lookupValues.add(IntConstant.v(se.getKey()));
        int offset = se.getOffset();
        targets.add(body.instructionAtAddress(codeAddress + offset).getUnit());
    }
    LookupSwitchStmt switchStmt = Jimple.v().newLookupSwitchStmt(key, lookupValues, targets, defaultTarget);
    setUnit(switchStmt);
    if (IDalvikTyper.ENABLE_DVKTYPER) {
        DalvikTyper.v().setType(switchStmt.getKeyBox(), IntType.v(), true);
    }
    return switchStmt;
}
Also used : PackedSwitchPayload(org.jf.dexlib2.iface.instruction.formats.PackedSwitchPayload) ArrayList(java.util.ArrayList) SwitchElement(org.jf.dexlib2.iface.instruction.SwitchElement) IntConstant(soot.jimple.IntConstant) LookupSwitchStmt(soot.jimple.LookupSwitchStmt) Unit(soot.Unit)

Aggregations

Unit (soot.Unit)240 Local (soot.Local)77 Stmt (soot.jimple.Stmt)77 Value (soot.Value)74 ArrayList (java.util.ArrayList)65 AssignStmt (soot.jimple.AssignStmt)58 SootMethod (soot.SootMethod)47 Body (soot.Body)37 InvokeStmt (soot.jimple.InvokeStmt)35 Type (soot.Type)34 HashSet (java.util.HashSet)33 ValueBox (soot.ValueBox)33 InvokeExpr (soot.jimple.InvokeExpr)33 Trap (soot.Trap)32 RefType (soot.RefType)30 IdentityStmt (soot.jimple.IdentityStmt)28 HashMap (java.util.HashMap)27 IfStmt (soot.jimple.IfStmt)27 DefinitionStmt (soot.jimple.DefinitionStmt)25 List (java.util.List)23