public static Pair<Value, List<Unit>> generateParameterArray(List<Value> parameterList, Body body){ List<Unit> generated = new ArrayList<Unit>(); NewArrayExpr arrayExpr = Jimple.v().newNewArrayExpr(RefType.v("java.lang.Object"), IntConstant.v(parameterList.size())); Value newArrayLocal = generateFreshLocal(body, getParameterArrayType()); Unit newAssignStmt = Jimple.v().newAssignStmt(newArrayLocal, arrayExpr); generated.add(newAssignStmt); for(int i = 0; i < parameterList.size(); i++){ Value index = IntConstant.v(i); ArrayRef leftSide = Jimple.v().newArrayRef(newArrayLocal, index); Value rightSide = generateCorrectObject(body, parameterList.get(i), generated); Unit parameterInArray = Jimple.v().newAssignStmt(leftSide, rightSide); generated.add(parameterInArray); } return new Pair<Value, List<Unit>>(newArrayLocal, generated); }
private void prepareAlarmManagerSet(Body body, InvokeStmt setStmt, SootMethodRef reportRef) { Value oldVal = setStmt.getInvokeExpr().getArg(1); Local longLocal = UtilInstrumenter.generateFreshLocal(body, LongType.v()); SootMethod currentTimeMillis = Scene.v().getMethod("<java.lang.System: long currentTimeMillis()>"); StaticInvokeExpr timeInvoke = Jimple.v().newStaticInvokeExpr(currentTimeMillis.makeRef()); AssignStmt timeInitalize = Jimple.v().newAssignStmt(longLocal, timeInvoke); AddExpr addTime = Jimple.v().newAddExpr(longLocal, LongConstant.v(2000L)); AssignStmt timeAssign = Jimple.v().newAssignStmt(longLocal, addTime); body.getUnits().insertBefore(timeInitalize, setStmt); body.getUnits().insertBefore(timeAssign, setStmt); InvokeExpr expr = setStmt.getInvokeExpr(); expr.setArg(0, IntConstant.v(0)); expr.setArg(1, longLocal); // Report the change InvokeStmt reportStmt = Jimple.v().newInvokeStmt(Jimple.v().newStaticInvokeExpr( reportRef, oldVal, longLocal)); reportStmt.addTag(new InstrumentedCodeTag()); body.getUnits().insertAfter(reportStmt, setStmt); }
private boolean hasConstantIndexAtArrayForSplitDataFlow(Stmt[] dataflow) { Stmt firstAssign = dataflow[0]; if(firstAssign instanceof AssignStmt) { AssignStmt ass = (AssignStmt)firstAssign; Value value = ass.getRightOp(); if(value instanceof ArrayRef) { ArrayRef aRef = (ArrayRef)value; Value index = aRef.getIndex(); if(index instanceof IntConstant) return true; } } else throw new RuntimeException("this should not happen - wrong assumption"); return false; }
private int getConstantArrayIndexForSplitDataFlow(Stmt[] dataflow) { Stmt firstAssign = dataflow[0]; if(firstAssign instanceof AssignStmt) { AssignStmt ass = (AssignStmt)firstAssign; Value value = ass.getRightOp(); if(value instanceof ArrayRef) { ArrayRef aRef = (ArrayRef)value; Value index = aRef.getIndex(); if(index instanceof IntConstant) return ((IntConstant) index).value; } } else throw new RuntimeException("this should not happen - wrong assumption"); return -1; }
/** * Constructs an array of the given type with a single element of this type * in the given method * @param body The body of the method in which to create the array * @param gen The local generator * @param tp The type of which to create the array * @param constructionStack Set of classes currently being built to avoid * constructor loops * @param parentClasses If a requested type is compatible with one of the * types in this list, the already-created object is used instead of * creating a new one. * @return The local referencing the newly created array, or null if the * array generation failed */ private Value buildArrayOfType(Body body, LocalGenerator gen, ArrayType tp, Set<SootClass> constructionStack, Set<SootClass> parentClasses) { Local local = gen.generateLocal(tp); // Generate a new single-element array NewArrayExpr newArrayExpr = Jimple.v().newNewArrayExpr(tp.getElementType(), IntConstant.v(1)); AssignStmt assignArray = Jimple.v().newAssignStmt(local, newArrayExpr); body.getUnits().add(assignArray); // Generate a single element in the array AssignStmt assign = Jimple.v().newAssignStmt (Jimple.v().newArrayRef(local, IntConstant.v(0)), getValueForType(body, gen, tp.getElementType(), constructionStack, parentClasses)); body.getUnits().add(assign); return local; }
protected Value getSimpleDefaultValue(String t) { if (t.equals("java.lang.String")) return StringConstant.v(""); if (t.equals("char")) return DIntConstant.v(0, CharType.v()); if (t.equals("byte")) return DIntConstant.v(0, ByteType.v()); if (t.equals("short")) return DIntConstant.v(0, ShortType.v()); if (t.equals("int")) return IntConstant.v(0); if (t.equals("float")) return FloatConstant.v(0); if (t.equals("long")) return LongConstant.v(0); if (t.equals("double")) return DoubleConstant.v(0); if (t.equals("boolean")) return DIntConstant.v(0, BooleanType.v()); //also for arrays etc. return G.v().soot_jimple_NullConstant(); }
public static PushInst getPushInitializer(Local l, Type t) { if (t instanceof IntegerType) { return Baf.v().newPushInst(IntConstant.v(soot.jbco.util.Rand.getInt())); } else if (t instanceof RefLikeType || t instanceof StmtAddressType) { return Baf.v().newPushInst(NullConstant.v()); } else if (t instanceof LongType) { return Baf.v().newPushInst(LongConstant.v(soot.jbco.util.Rand.getLong())); } else if (t instanceof FloatType) { return Baf.v().newPushInst( FloatConstant.v(soot.jbco.util.Rand.getFloat())); } else if (t instanceof DoubleType) { return Baf.v().newPushInst( DoubleConstant.v(soot.jbco.util.Rand.getDouble())); } return null; }
/** * Returns a needed constant given a type and val */ protected soot.jimple.Constant getConstant(soot.Type type, int val) { if (type instanceof soot.DoubleType) { return soot.jimple.DoubleConstant.v(val); } else if (type instanceof soot.FloatType) { return soot.jimple.FloatConstant.v(val); } else if (type instanceof soot.LongType) { return soot.jimple.LongConstant.v(val); } else { return soot.jimple.IntConstant.v(val); } }
public void outAIntegerConstant(AIntegerConstant node) { String s = (String) mProductions.removeLast(); StringBuffer buf = new StringBuffer(); if(node.getMinus() != null) buf.append('-'); buf.append(s); s = buf.toString(); if(s.endsWith("L")) { mProductions.addLast(LongConstant.v(Long.parseLong(s.substring(0, s.length()-1)))); } else if (s.equals("2147483648")) mProductions.addLast(IntConstant.v(Integer.MIN_VALUE)); else mProductions.addLast(IntConstant.v(Integer.parseInt(s))); }
@Override public void caseLookupSwitchStmt(LookupSwitchStmt stmt) { exprV.setOrigStmt(stmt); constantV.setOrigStmt(stmt); // create payload that references the switch's targets List<IntConstant> keyValues = stmt.getLookupValues(); int[] keys = new int[keyValues.size()]; for (int i = 0; i < keys.length; i++) { keys[i] = keyValues.get(i).value; } List<Unit> targets = stmt.getTargets(); SparseSwitchPayload payload = new SparseSwitchPayload(keys, targets); switchPayloads.add(payload); // create sparse-switch instruction that references the payload Value key = stmt.getKey(); Stmt defaultTarget = (Stmt) stmt.getDefaultTarget(); if (defaultTarget == stmt) throw new RuntimeException("Looping switch block detected"); addInsn(buildSwitchInsn(Opcode.SPARSE_SWITCH, key, defaultTarget, payload, stmt), stmt); }
/** * Collect all the locals which are assigned a IntConstant(0) or are used * within a zero comparison. * * @param body * the body to analyze */ private Set<Local> getNumCandidates(Body body) { Set<Local> candidates = new HashSet<Local>(); for (Unit u : body.getUnits()) { if (u instanceof AssignStmt) { AssignStmt a = (AssignStmt) u; if (!(a.getLeftOp() instanceof Local)) continue; Local l = (Local) a.getLeftOp(); Value r = a.getRightOp(); if ((r instanceof IntConstant || r instanceof LongConstant)) { candidates.add(l); Debug.printDbg("[add null candidate: ", u); } } } return candidates; }
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()); } switchStmt = Jimple.v().newLookupSwitchStmt(key, lookupValues, targets, defaultTarget); setUnit(switchStmt); if (IDalvikTyper.ENABLE_DVKTYPER) { Debug.printDbg(IDalvikTyper.DEBUG, "constraint: "+ switchStmt); DalvikTyper.v().setType(switchStmt.getKeyBox(), IntType.v(), true); } return switchStmt; }
protected Stmt switchStatement(DexBody body, Instruction targetData, Local key) { SparseSwitchPayload i = (SparseSwitchPayload) 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()); } switchStmt = Jimple.v().newLookupSwitchStmt(key, lookupValues, targets, defaultTarget); setUnit(switchStmt); if (IDalvikTyper.ENABLE_DVKTYPER) { Debug.printDbg(IDalvikTyper.DEBUG, "constraint: "+ switchStmt); DalvikTyper.v().setType(switchStmt.getKeyBox(), IntType.v(), true); } return switchStmt; }
@Override protected void internalTransform(Body b, String phaseName, Map<String, String> options) { LocalCreation lc = new LocalCreation(b.getLocals(), "ex"); for (Iterator<Unit> unitIt = b.getUnits().snapshotIterator(); unitIt.hasNext(); ) { Unit u = unitIt.next(); // Check for a null exception if (u instanceof ThrowStmt) { ThrowStmt throwStmt = (ThrowStmt) u; if (throwStmt.getOp() == NullConstant.v() || throwStmt.getOp().equals(IntConstant.v(0)) || throwStmt.getOp().equals(LongConstant.v(0))) { createThrowStmt(b, throwStmt, lc); } } } }
public static Object isAConstantValue(Value toCheck){ Object value=null; if(toCheck instanceof LongConstant){ value = new Long(((LongConstant)toCheck).value); } else if(toCheck instanceof DoubleConstant){ value = new Double(((DoubleConstant)toCheck).value); } else if(toCheck instanceof FloatConstant){ value = new Float(((FloatConstant)toCheck).value); } else if(toCheck instanceof IntConstant){ int val = ((IntConstant)toCheck).value; value = new Integer(val); } return value; }
public static Value createConstant(Object toConvert){ if(toConvert instanceof Long){ return LongConstant.v( ((Long)toConvert).longValue() ); } else if(toConvert instanceof Double){ return DoubleConstant.v( ((Double)toConvert).doubleValue()); } else if(toConvert instanceof Boolean){ boolean val = ((Boolean)toConvert).booleanValue(); if(val) return DIntConstant.v(1,BooleanType.v()); else return DIntConstant.v(0,BooleanType.v()); } else if(toConvert instanceof Float){ return FloatConstant.v( ((Float)toConvert).floatValue()); } else if(toConvert instanceof Integer){ return IntConstant.v( ((Integer)toConvert).intValue()); } else return null; }
private Value toSootValue(Object val) throws AssertionError { Value v; if (val instanceof Integer) v = IntConstant.v((Integer) val); else if (val instanceof Float) v = FloatConstant.v((Float) val); else if (val instanceof Long) v = LongConstant.v((Long) val); else if (val instanceof Double) v = DoubleConstant.v((Double) val); else if (val instanceof String) v = StringConstant.v(val.toString()); else if (val instanceof org.objectweb.asm.Type) v = ClassConstant.v(((org.objectweb.asm.Type) val).getInternalName()); else if (val instanceof Handle) v = MethodHandle.v(toSootMethodRef((Handle) val), ((Handle)val).getTag()); else throw new AssertionError("Unknown constant type: " + val.getClass()); return v; }
private void caseBinopDivExpr(BinopExpr expr) { // Factors out code common to caseDivExpr and caseRemExpr. // The checks against constant divisors would perhaps be // better performed in a later pass, post-constant-propagation. Value divisor = expr.getOp2(); Type divisorType = divisor.getType(); if (divisorType instanceof UnknownType) { result = result.add(mgr.ARITHMETIC_EXCEPTION); } else if ((divisorType instanceof IntegerType) && ((! (divisor instanceof IntConstant)) || (((IntConstant) divisor).equals(INT_CONSTANT_ZERO)))) { result = result.add(mgr.ARITHMETIC_EXCEPTION); } else if ((divisorType == LongType.v()) && ((! (divisor instanceof LongConstant)) || (((LongConstant) divisor).equals(LONG_CONSTANT_ZERO)))) { result = result.add(mgr.ARITHMETIC_EXCEPTION); } caseBinopExpr(expr); }
@Test public void testGLookupSwitchStmt() { Stmt target = Grimp.v().newAssignStmt(Grimp.v().newLocal("local0", IntType.v()), IntConstant.v(0)); Stmt s = Grimp.v().newLookupSwitchStmt(IntConstant.v(1), Arrays.asList(new Value[] { IntConstant.v(1) }), Arrays.asList(new Unit[] { target }), target); assertTrue(ExceptionTestUtility.sameMembers(utility.VM_ERRORS, Collections.EMPTY_SET, unitAnalysis.mightThrow(s))); assertEquals(utility.VM_ERRORS_PLUS_SUPERTYPES, utility.catchableSubset(unitAnalysis.mightThrow(s))); }
@Ignore("Fails") @Test public void testJReturnStmt() { Stmt s = Jimple.v().newReturnStmt(IntConstant.v(1)); Set expectedRep = new ExceptionHashSet(utility.VM_ERRORS); expectedRep.add(utility.ILLEGAL_MONITOR_STATE_EXCEPTION); assertTrue(ExceptionTestUtility.sameMembers(expectedRep, Collections.EMPTY_SET, unitAnalysis.mightThrow(s))); Set expectedCatch = new ExceptionHashSet(utility.VM_ERRORS_PLUS_SUPERTYPES); expectedCatch.add(utility.ILLEGAL_MONITOR_STATE_EXCEPTION); expectedCatch.add(utility.RUNTIME_EXCEPTION); expectedCatch.add(utility.EXCEPTION); assertEquals(expectedCatch, utility.catchableSubset(unitAnalysis.mightThrow(s))); }
@Ignore("Fails") @Test public void testGReturnStmt() { Stmt s = Grimp.v().newReturnStmt(IntConstant.v(1)); Set expectedRep = new ExceptionHashSet(utility.VM_ERRORS); expectedRep.add(utility.ILLEGAL_MONITOR_STATE_EXCEPTION); assertTrue(ExceptionTestUtility.sameMembers(expectedRep, Collections.EMPTY_SET, unitAnalysis.mightThrow(s))); Set expectedCatch = new ExceptionHashSet(utility.VM_ERRORS_PLUS_SUPERTYPES); expectedCatch.add(utility.ILLEGAL_MONITOR_STATE_EXCEPTION); expectedCatch.add(utility.RUNTIME_EXCEPTION); expectedCatch.add(utility.EXCEPTION); assertEquals(expectedCatch, utility.catchableSubset(unitAnalysis.mightThrow(s))); }
@Test public void testJArrayRef() { ArrayRef arrayRef = Jimple.v().newArrayRef( Jimple.v().newLocal("local1", ArrayType.v(RefType.v("java.lang.Object"), 1)), IntConstant.v(0)); Set expectedRep = new ExceptionHashSet(utility.VM_ERRORS); expectedRep.add(utility.NULL_POINTER_EXCEPTION); expectedRep.add(utility.ARRAY_INDEX_OUT_OF_BOUNDS_EXCEPTION); assertTrue(ExceptionTestUtility.sameMembers(expectedRep, Collections.EMPTY_SET, unitAnalysis.mightThrow(arrayRef))); Set expectedCatch = new ExceptionHashSet(utility.VM_ERRORS_PLUS_SUPERTYPES); expectedCatch.add(utility.NULL_POINTER_EXCEPTION); expectedCatch.add(utility.ARRAY_INDEX_OUT_OF_BOUNDS_EXCEPTION); expectedCatch.add(utility.INDEX_OUT_OF_BOUNDS_EXCEPTION); expectedCatch.add(utility.RUNTIME_EXCEPTION); expectedCatch.add(utility.EXCEPTION); assertEquals(expectedCatch, utility.catchableSubset(unitAnalysis.mightThrow(arrayRef))); }
@Test public void testGArrayRef() { ArrayRef arrayRef = Grimp.v().newArrayRef( Grimp.v().newLocal("local1", ArrayType.v(RefType.v("java.lang.Object"), 1)), IntConstant.v(0)); Set expectedRep = new ExceptionHashSet(utility.VM_ERRORS); expectedRep.add(utility.NULL_POINTER_EXCEPTION); expectedRep.add(utility.ARRAY_INDEX_OUT_OF_BOUNDS_EXCEPTION); assertTrue(ExceptionTestUtility.sameMembers(expectedRep, Collections.EMPTY_SET, unitAnalysis.mightThrow(arrayRef))); Set expectedCatch = new ExceptionHashSet(utility.VM_ERRORS_PLUS_SUPERTYPES); expectedCatch.add(utility.NULL_POINTER_EXCEPTION); expectedCatch.add(utility.ARRAY_INDEX_OUT_OF_BOUNDS_EXCEPTION); expectedCatch.add(utility.INDEX_OUT_OF_BOUNDS_EXCEPTION); expectedCatch.add(utility.RUNTIME_EXCEPTION); expectedCatch.add(utility.EXCEPTION); assertEquals(expectedCatch, utility.catchableSubset(unitAnalysis.mightThrow(arrayRef))); }
/** * Construct the appropriate NEW expression depending on the given Soot * type. It handles RefType and ArrayType types. * * @param type * @return */ public AnyNewExpr getNewExpression(Type type) { if (type instanceof RefType) { return Jimple.v().newNewExpr((RefType) type); } else if (type instanceof ArrayType) { ArrayType arrayType = (ArrayType) type; if (arrayType.numDimensions <= 1) { return Jimple.v().newNewArrayExpr(arrayType.baseType, IntConstant.v(1)); } else { // Create the list of sizes for the array dimensions List<Value> sizes = new ArrayList<Value>(); for (int i = 0; i < arrayType.numDimensions; i++) { sizes.add(IntConstant.v(1)); } return Jimple.v().newNewMultiArrayExpr(arrayType, sizes); } } throw new IllegalArgumentException("Type " + type + " cannot be instantiated."); }
public SootMethod generateFuzzyMethod(SootClass sootClass) { String name = "fuzzyMe"; List<Type> parameters = new ArrayList<Type>(); Type returnType = IntType.v(); int modifiers = Modifier.PUBLIC; SootMethod fuzzyMeMethod = new SootMethod(name, parameters, returnType, modifiers); sootClass.addMethod(fuzzyMeMethod); { Body b = Jimple.v().newBody(fuzzyMeMethod); fuzzyMeMethod.setActiveBody(b); LocalGenerator lg = new LocalGenerator(b); Local thisLocal = lg.generateLocal(sootClass.getType()); Unit thisU = Jimple.v().newIdentityStmt(thisLocal, Jimple.v().newThisRef(sootClass.getType())); Unit returnU = Jimple.v().newReturnStmt(IntConstant.v(1)); b.getUnits().add(thisU); b.getUnits().add(returnU); } return fuzzyMeMethod; }
@Override public ConditionExpr instantitate(Value var) { ConditionExpr ret = null; IntConstant valInt = IntConstant.v(Integer.parseInt(val)); switch(op){ case "=": ret = new GEqExpr(var,valInt); break; case ">=" : ret = new GGeExpr(var, valInt); break; case ">" : ret = new GGtExpr(var, valInt); break; case "<=" : ret = new GLeExpr(var, valInt); break; case "<" : ret = new GLtExpr(var, valInt); break; case "!=" : ret = new GNeExpr(var, valInt); break; } if(ret == null){ System.out.println("Cannot initialize interval predicate"); System.exit(2); } return ret; }
/** * Constructs an array of the given type with a single element of this type * in the given method * @param body The body of the method in which to create the array * @param gen The local generator * @param tp The type of which to create the array * @param constructionStack Set of classes currently being built to avoid * constructor loops * @param parentClasses If a requested type is compatible with one of the * types in this list, the already-created object is used instead of * creating a new one. * @return The local referencing the newly created array, or null if the * array generation failed */ private Value buildArrayOfType(JimpleBody body, LocalGenerator gen, ArrayType tp, Set<SootClass> constructionStack, Set<SootClass> parentClasses) { Local local = gen.generateLocal(tp); // Generate a new single-element array NewArrayExpr newArrayExpr = Jimple.v().newNewArrayExpr(tp.getElementType(), IntConstant.v(1)); AssignStmt assignArray = Jimple.v().newAssignStmt(local, newArrayExpr); body.getUnits().add(assignArray); // Generate a single element in the array AssignStmt assign = Jimple.v().newAssignStmt (Jimple.v().newArrayRef(local, IntConstant.v(19)), getValueForType(body, gen, tp.getElementType(), constructionStack, parentClasses)); body.getUnits().add(assign); return local; }
void getIntConstantsFromLocal(SimpleLocalDefs sld, Local l, Unit u, List<String> whats) throws IOException { Iterator<Unit> iter = sld.getDefsOfAt(l, u).iterator(); while (iter.hasNext()) { Unit def = iter.next(); if (! (def instanceof DefinitionStmt)) continue; DefinitionStmt assign = (DefinitionStmt) def; Value rightOp = assign.getRightOp(); if (rightOp instanceof IntConstant) { whats.add(rightOp.toString()); } else if (rightOp instanceof ParameterRef){ whats.add(rightOp.toString()); } else if (rightOp instanceof Local) { getIntConstantsFromLocal(sld, (Local)rightOp, def, whats); print("getIntConstantsFromLocal -> local"); } else { print("???"+def.toString()); } } }
/** * * @param parameter * @param body * @return */ private Pair<Value, List<Unit>> generateParameterArray(List<Value> parameter, Body body){ List<Unit> generated = new ArrayList<Unit>(); NewArrayExpr arrayExpr = Jimple.v().newNewArrayExpr(RefType.v("java.lang.Object"), IntConstant.v(parameter.size())); Value newArrayLocal = generateFreshLocal(body, getParameterArrayType()); Unit newAssignStmt = Jimple.v().newAssignStmt(newArrayLocal, arrayExpr); generated.add(newAssignStmt); for(int i = 0; i < parameter.size(); i++){ Value index = IntConstant.v(i); ArrayRef leftSide = Jimple.v().newArrayRef(newArrayLocal, index); Value rightSide = generateCorrectObject(body, parameter.get(i), generated); Unit parameterInArray = Jimple.v().newAssignStmt(leftSide, rightSide); generated.add(parameterInArray); } return new Pair<Value, List<Unit>>(newArrayLocal, generated); }
public static Value getDefaultValue(Type type) { if ((type instanceof BooleanType) || (type instanceof ByteType) || (type instanceof CharType) || (type instanceof DoubleType) || (type instanceof FloatType) || (type instanceof IntType) || (type instanceof LongType) || (type instanceof ShortType)) { return IntConstant.v(0); } else { return NullConstant.v(); } }
/** * @param posInArgList * @param local * @param actualPos */ public static void assignArgumentToLocal(int posInArgList, Local local, Unit actualPos) { logger.log(Level.INFO, "Assign argument level to local " + local.toString()); ArrayList<Type> parameterTypes = new ArrayList<Type>(); parameterTypes.add(IntType.v()); parameterTypes.add(RefType.v("java.lang.String")); Expr assignArg = Jimple.v().newVirtualInvokeExpr( hs, Scene.v().makeMethodRef( Scene.v().getSootClass(HANDLE_CLASS), "assignArgumentToLocal", parameterTypes, Scene.v().getObjectType(), false), IntConstant.v(posInArgList), StringConstant.v(getSignatureForLocal(local)) ); Unit assignExpr = Jimple.v().newInvokeStmt(assignArg); unitStore_After.insertElement(unitStore_After.new Element(assignExpr, lastPos)); lastPos = assignExpr; }
public SootMethod makeMultipleReturns() { Unit returnX = j.newReturnStmt(code.localX); Unit returnZ = j.newReturnStmt(code.localZ); Unit ifY = j.newIfStmt(j.newEqExpr(code.localY, code.localY), returnX); Unit ifO = j.newIfStmt(j.newEqExpr(code.localO, code.localO), ifY); Unit returnZero = j.newReturnStmt(IntConstant.v(0)); IntType i = IntType.v(); SootMethod m = code.makeMethod(Modifier.STATIC, "multipleReturns", asList(code.localX, code.localY, code.localZ, code.localO), IntType.v(), asList(ifO, returnZ, ifY, returnZero, returnX )); return m; }
/** * Returns a points-to graph with the locals of main initialised to * <tt>null</tt>, except the command-line arguments which are * initialised to an array of strings. */ @Override public PointsToGraph boundaryValue(SootMethod entryPoint) { // For now we only support entry to the main method assert(entryPoint == Scene.v().getMainMethod()); // Ok, start setting up entry value PointsToGraph entryValue = new PointsToGraph(); // Locals of main... (only reference types) SootMethod mainMethod = Scene.v().getMainMethod(); for (Local local : mainMethod.getActiveBody().getLocals()) { if (local.getType() instanceof RefLikeType) { entryValue.assign(local, null); } } // Command-line arguments to main... Local argsLocal = mainMethod.getActiveBody().getParameterLocal(0); NewArrayExpr argsExpr = new JNewArrayExpr(Scene.v().getRefType("java.lang.String"), IntConstant.v(0)); entryValue.assignNew(argsLocal, argsExpr); entryValue.setFieldConstant(argsLocal, PointsToGraph.ARRAY_FIELD, PointsToGraph.STRING_CONST); return entryValue; }
@Override protected void internalTransform(Body b, String phaseName, Map<String, String> options) { // Do not instrument methods in framework classes if (!canInstrumentMethod(b.getMethod())) return; // Make a reference to the tracker method SootMethodRef ref = Scene.v().makeMethodRef( Scene.v().getSootClass(UtilInstrumenter.JAVA_CLASS_FOR_CODE_POSITIONS), "setLastExecutedStatement", Collections.<Type>singletonList(IntType.v()), VoidType.v(), true); final String methodSig = b.getMethod().getSignature(); // Iterate over all the units and add a unit that sets the current // execution pointer int curLineNum = 0; for (Iterator<Unit> unitIt = b.getUnits().snapshotIterator(); unitIt.hasNext(); ) { Unit curUnit = unitIt.next(); // If we're still inside the IdentityStmt block, there's nothing to // instrument if (curUnit instanceof IdentityStmt || // If this unit was instrumented by another transformer, there's nothing to instrument curUnit.hasTag(InstrumentedCodeTag.name)) continue; // Get the current code positions CodePosition codePos = codePositionManager.getCodePositionForUnit(curUnit, methodSig, curLineNum++, ((Stmt) curUnit).getJavaSourceStartLineNumber()); Stmt setCodePosStmt = Jimple.v().newInvokeStmt( Jimple.v().newStaticInvokeExpr(ref, IntConstant.v(codePos.getID()))); setCodePosStmt.addTag(new InstrumentedCodeTag()); b.getUnits().insertAfter(setCodePosStmt, curUnit); } }
private void instrumentEachBranchAccess(Body body, Unit unit){ SootClass sootClass = Scene.v().getSootClass( UtilInstrumenter.JAVA_CLASS_FOR_PATH_INSTRUMENTATION); // Create the method invocation SootMethod createAndAdd = sootClass.getMethod("reportConditionOutcomeSynchronous", Collections.<Type>singletonList(BooleanType.v())); StaticInvokeExpr sieThen = Jimple.v().newStaticInvokeExpr( createAndAdd.makeRef(), IntConstant.v(1)); StaticInvokeExpr sieElse = Jimple.v().newStaticInvokeExpr( createAndAdd.makeRef(), IntConstant.v(0)); Unit sieThenUnit = Jimple.v().newInvokeStmt(sieThen); sieThenUnit.addTag(new InstrumentedCodeTag()); Unit sieElseUnit = Jimple.v().newInvokeStmt(sieElse); sieElseUnit.addTag(new InstrumentedCodeTag()); //treatment of target statement ("true"-branch) IfStmt ifStmt = (IfStmt)unit; Stmt targetStmt = ifStmt.getTarget(); if(!branchTargetStmt.contains(targetStmt.toString())) { branchTargetStmt.add(sieThenUnit.toString()); body.getUnits().insertBefore(sieThenUnit, targetStmt); NopStmt nop = Jimple.v().newNopStmt(); GotoStmt gotoNop = Jimple.v().newGotoStmt(nop); body.getUnits().insertBeforeNoRedirect(nop, targetStmt); body.getUnits().insertBeforeNoRedirect(gotoNop, sieThenUnit); } //treatment of "else"-branch body.getUnits().insertAfter(sieElseUnit, unit); }
private int findMaxIndexOfArray(InvokeExpr invokeExpr) { Value array = null; int maxIndex = -1; for(Stmt stmt : stmtVisitor.getJimpleDataFlowStatements()) { if(stmt instanceof AssignStmt) { AssignStmt assign = (AssignStmt)stmt; if(array == null) { if(assign.getRightOp().equals(invokeExpr)) { array = assign.getLeftOp(); } } else{ Value rhs = assign.getRightOp(); if(rhs instanceof ArrayRef) { ArrayRef arrayRef = (ArrayRef)rhs; if(arrayRef.getBase().equals(array)) { Value index = arrayRef.getIndex(); if(index instanceof IntConstant) { IntConstant constant = (IntConstant)index; maxIndex = constant.value; } } } } } } return maxIndex; }
private void constructNewObject(Body b, Type localType, SootMethod constructor) { // "new" statement Value lvalue = getLocalWithName(b, makeLocalName(localType), localType); Value rvalue = Jimple.v().newNewExpr( constructor.getDeclaringClass().getType()); AssignStmt ass = Jimple.v().newAssignStmt(lvalue, rvalue); b.getUnits().add(ass); // <init> invocation statement List<Value> args = new ArrayList<Value>(); for (Type argt : (List<Type>) constructor.getParameterTypes()) { if (argt instanceof PrimType) { args.add(IntConstant.v(0)); } else { args.add(getLocalWithName(b, makeLocalName(argt), argt)); } } Value invokeExpr = null; Unit u = null; if (constructor.isStatic()) { invokeExpr = Jimple.v().newStaticInvokeExpr(constructor.makeRef(), args); u = Jimple.v().newAssignStmt(lvalue, invokeExpr); } else { invokeExpr = Jimple.v().newSpecialInvokeExpr((Local) lvalue, constructor.makeRef(), args); u = Jimple.v().newInvokeStmt(invokeExpr); } b.getUnits().add(u); }
/** * Finds the mappings between classes and their respective layout files */ private void findClassLayoutMappings() { Iterator<MethodOrMethodContext> rmIterator = Scene.v().getReachableMethods().listener(); while (rmIterator.hasNext()) { SootMethod sm = rmIterator.next().method(); if (!sm.isConcrete()) continue; for (Unit u : sm.retrieveActiveBody().getUnits()) if (u instanceof Stmt) { Stmt stmt = (Stmt) u; if (stmt.containsInvokeExpr()) { InvokeExpr inv = stmt.getInvokeExpr(); if (invokesSetContentView(inv)) { for (Value val : inv.getArgs()) if (val instanceof IntConstant) { IntConstant constVal = (IntConstant) val; Set<Integer> layoutIDs = this.layoutClasses.get(sm.getDeclaringClass().getName()); if (layoutIDs == null) { layoutIDs = new HashSet<Integer>(); this.layoutClasses.put(sm.getDeclaringClass().getName(), layoutIDs); } layoutIDs.add(constVal.value); } } } } } }