@Override protected void internalTransform(Body body, String phaseName, Map<String, String> options) { // Do not instrument methods in framework classes if (!canInstrumentMethod(body.getMethod())) return; instrumentInfoAboutNonAPICall(body); //important to use snapshotIterator here Iterator<Unit> iterator = body.getUnits().snapshotIterator(); while(iterator.hasNext()){ Unit unit = iterator.next(); if(unit instanceof ReturnStmt || unit instanceof ReturnVoidStmt) instrumentInfoAboutReturnStmt(body, unit); else if(unit instanceof DefinitionStmt || unit instanceof InvokeStmt) instrumentInfoAboutNonApiCaller(body, unit); else if(unit instanceof IfStmt) instrumentEachBranchAccess(body, (IfStmt)unit); } }
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); }
@Override protected void internalTransform(Body body, String phaseName, Map<String, String> options) { if (!canInstrumentMethod(body.getMethod())) return; // Get a reference to the reporter method SootMethodRef reporterRef = Scene.v().getMethod("<de.tu_darmstadt.sse.additionalappclasses.tracing.BytecodeLogger: " + "void reportTimingBomb(long,long)>").makeRef(); for (Iterator<Unit> unitIt = body.getUnits().snapshotIterator(); unitIt.hasNext(); ) { Unit curUnit = unitIt.next(); if(curUnit instanceof InvokeStmt) { InvokeStmt invokeStmt = (InvokeStmt) curUnit; InvokeExpr expr = invokeStmt.getInvokeExpr(); String methodSig = expr.getMethod().getSignature(); if(methodSig.equals("<android.app.AlarmManager: void set(int,long,android.app.PendingIntent)>")) prepareAlarmManagerSet(body, invokeStmt, reporterRef); else if(methodSig.equals("<android.os.Handler: boolean postDelayed(java.lang.Runnable,long)>")) prepareHandlerPostDelayed(body, invokeStmt, reporterRef); } } }
private void prepareHandlerPostDelayed(Body body, Stmt invokeStmt, SootMethodRef reportRef) { InvokeExpr expr = invokeStmt.getInvokeExpr(); Value oldValue = expr.getArg(1); Value newValue = LongConstant.v(2000L); expr.setArg(1, newValue); // Report the change InvokeStmt reportStmt = Jimple.v().newInvokeStmt(Jimple.v().newStaticInvokeExpr( reportRef, oldValue, newValue)); reportStmt.addTag(new InstrumentedCodeTag()); body.getUnits().insertAfter(reportStmt, invokeStmt); }
@Override public String format(Unit u, int maxLength) { InvokeStmt invoke = (InvokeStmt) u; String s = ValueFormatter.format(invoke.getInvokeExpr()); if(s.length() > maxLength) { s = s.substring(0, maxLength) + "\u2026"; } return s; }
public static UnitFormatter createFormatter(Unit u) { if(u instanceof AssignStmt) { return new AssignStmtFormatter(); } else if (u instanceof InvokeStmt) { return new InvokeStmtFormatter(); } // no special formatter found, return the default one return new DefaultFormatter(); }
/** * Checks whether the given method is a library stub method * @param method The method to check * @return True if the given method is an Android library stub, false * otherwise */ private boolean methodIsAndroidStub(SootMethod method) { if (!(Options.v().src_prec() == Options.src_prec_apk && method.getDeclaringClass().isLibraryClass() && SystemClassHandler.isClassInSystemPackage( method.getDeclaringClass().getName()))) return false; // Check whether there is only a single throw statement for (Unit u : method.getActiveBody().getUnits()) { if (u instanceof DefinitionStmt) { DefinitionStmt defStmt = (DefinitionStmt) u; if (!(defStmt.getRightOp() instanceof ThisRef) && !(defStmt.getRightOp() instanceof ParameterRef) && !(defStmt.getRightOp() instanceof NewExpr)) return false; } else if (u instanceof InvokeStmt) { InvokeStmt stmt = (InvokeStmt) u; // Check for exception constructor invocations SootMethod callee = stmt.getInvokeExpr().getMethod(); if (!callee.getSubSignature().equals("void <init>(java.lang.String)")) // Check for super class constructor invocation if (!(method.getDeclaringClass().hasSuperclass() && callee.getDeclaringClass() == method.getDeclaringClass().getSuperclass() && callee.getName().equals("<init>"))) return false; } else if (!(u instanceof ThrowStmt)) return false; } return true; }
private InvokeStmt getFirstSpecialInvoke(Body b){ for (Unit u : b.getUnits()) { Stmt s = (Stmt)u; if (!(s instanceof InvokeStmt)) continue; InvokeExpr invokeExpr = ((InvokeStmt)s).getInvokeExpr(); if (!(invokeExpr instanceof SpecialInvokeExpr)) continue; return (InvokeStmt)s; } // but there will always be either a call to this() or to super() // from the constructor return null; }
public void finalize(DexBody body, DexlibAbstractInstruction successor) { // defer final jimplification to move result if (successor instanceof MoveResultInstruction) { // MoveResultInstruction i = (MoveResultInstruction)successor; // i.setExpr(invocation); // if (lineNumber != -1) // i.setTag(new SourceLineNumberTag(lineNumber)); assign = Jimple.v().newAssignStmt(body.getStoreResultLocal(), invocation); setUnit(assign); addTags(assign); body.add(assign); unit = assign; // this is a invoke statement (the MoveResult had to be the direct successor for an expression) } else { InvokeStmt invoke = Jimple.v().newInvokeStmt(invocation); setUnit(invoke); addTags(invoke); body.add(invoke); unit = invoke; } if (IDalvikTyper.ENABLE_DVKTYPER) { Debug.printDbg(IDalvikTyper.DEBUG, "constraint special invoke: "+ assign); if (invocation instanceof InstanceInvokeExpr) { Type t = invocation.getMethodRef().declaringClass().getType(); DalvikTyper.v().setType(((InstanceInvokeExpr) invocation).getBaseBox(), t, true); //DalvikTyper.v().setObjectType(assign.getLeftOpBox()); } int i = 0; for (Type pt: (List<Type>)invocation.getMethodRef().parameterTypes()) { DalvikTyper.v().setType(invocation.getArgBox(i++), pt, true); } int op = (int)instruction.getOpcode().value; if (assign != null) { DalvikTyper.v().setType(assign.getLeftOpBox(), invocation.getType(), false); } } }
@Override public void propagateTaint(UnitGraph graph, Set<Unit> input, Unit node, Set<Unit> output, Set<Value> taintedValues, Queue<MethodAnalysis> queue, Set<MethodAnalysis> processed) { assert(isApplicable(graph, input, node, output, taintedValues, queue, processed)); if(node instanceof InvokeStmt) taintedValues.addAll(getTaintedValues((InvokeStmt)node)); }
private Value checkThreadStartStmt(Stmt sootStmt) { // Check for function calls if(sootStmt instanceof InvokeStmt) { InvokeStmt invokeStmt = (InvokeStmt)sootStmt; // Check if the current statement is a constructor if(invokeStmt.getInvokeExpr() instanceof VirtualInvokeExpr) { // It's a constructor. Check if it's a Thread allocation site VirtualInvokeExpr invokeExpr = (VirtualInvokeExpr)invokeStmt.getInvokeExpr(); String functionSignature = invokeExpr.getMethod().getSignature(); String className = SusHelper.getClassFromSignature(functionSignature); String functionName = invokeExpr.getMethod().getName(); try { if((Thread.class.isAssignableFrom( Class.forName(className, false, this.getClass().getClassLoader()))) && (functionName.equals("start")) && (invokeExpr.getMethod().getParameterCount() == 0)) { //System.out.println("Invoke method "+invokeExpr.getMethod()+" on "+invokeExpr.getBase()); //System.out.println("run() called on "+innerRunnable.get(invokeExpr.getBase())); return invokeExpr.getBase(); } } catch (ClassNotFoundException e) { System.err.println("Unable to find class "+className); } } } return null; }
static boolean is_invoke_on(Unit stmt, Value defval) { if (stmt instanceof InvokeStmt) { InvokeExpr e = ((InvokeStmt) stmt).getInvokeExpr(); if (e instanceof InstanceInvokeExpr) return ((InstanceInvokeExpr) e).getBase().equivTo(defval); else return false; } else return false; }
/** * Analyze a statement and computes an abstract value representing what it produces. (Value * assigned for an assign) and call approximation for an invoke. * @param u * @param seen * @return */ public AbsValue analyze_single (Unit u, Set<Unit> seen) { if (u instanceof InvokeStmt) { ProgramSpy.debug("************ INVOKE ********"); InvokeExpr e = ((InvokeStmt) u).getInvokeExpr(); return analyzeInvoke(e,u,seen); } else if (u instanceof DefinitionStmt) { ProgramSpy.debug("************ DEFINITION "+ u + " ********"); Value r = ((DefinitionStmt)u).getRightOp (); return analyze_expr(r, u, seen); } else { ProgramSpy.debug("************ OTHER STMT ********"); return new UnknownValue (u.toString()); } }
@Override protected void analyse(SootClass clazz, final SootMethod method, Body body) { for (Unit unit : body.getUnits()) { unit.apply(new AbstractStmtSwitch() { @Override public void caseInvokeStmt(InvokeStmt stmt) { InvokeExpr expr = stmt.getInvokeExpr(); SootMethod targetMethod = expr.getMethod(); if (!Signatures.methodSignatureMatches(targetMethod, Types.HTTPS_URL_CONNECTION, VoidType.v(), "setDefaultHostnameVerifier", Types.HOSTNAME_VERIFIER)) return; Value value = expr.getArg(0); if (!(value instanceof Local)) return; // TODO e.g. could be a field ref? does soot support points-to in this case? VulnerabilityState state = VulnerabilityState.UNKNOWN; PointsToSet set = Scene.v().getPointsToAnalysis().reachingObjects((Local) value); if (!set.isEmpty()) { if (PointsToUtils.anyTypeVulnerable(set, HostnameVerifierTag.NAME)) { state = VulnerabilityState.VULNERABLE; } else if (PointsToUtils.allTypesSafe(set, HostnameVerifierTag.NAME)) { state = VulnerabilityState.SAFE; } } vulnerabilities.add(new Vulnerability(method, VulnerabilityType.HTTPS_CONNECTION_DEFAULT_HOSTNAME_VERIFIER, state)); } }); } }
@Override protected void analyse(SootClass clazz, final SootMethod method, Body body) { for (Unit unit : body.getUnits()) { unit.apply(new AbstractStmtSwitch() { @Override public void caseInvokeStmt(InvokeStmt stmt) { InvokeExpr expr = stmt.getInvokeExpr(); SootMethod targetMethod = expr.getMethod(); // TODO what if it is casted to HTTP_URL_CONNECTION? if (!Signatures.methodSignatureMatches(targetMethod, Types.HTTPS_URL_CONNECTION, VoidType.v(), "setHostnameVerifier", Types.HOSTNAME_VERIFIER)) return; Value value = expr.getArg(0); if (!(value instanceof Local)) return; VulnerabilityState state = VulnerabilityState.UNKNOWN; PointsToSet set = Scene.v().getPointsToAnalysis().reachingObjects((Local) value); if (!set.isEmpty()) { if (PointsToUtils.anyTypeVulnerable(set, HostnameVerifierTag.NAME)) { state = VulnerabilityState.VULNERABLE; } else if (PointsToUtils.allTypesSafe(set, HostnameVerifierTag.NAME)) { state = VulnerabilityState.SAFE; } } vulnerabilities.add(new Vulnerability(method, VulnerabilityType.HTTPS_CONNECTION_USES_HOSTNAME_VERIFIER, state)); } }); } }
public static Unit getSuperOnCreateUnit(Body b) { for(Unit u : b.getUnits()){ if(u instanceof InvokeStmt){ InvokeStmt invStmt = (InvokeStmt)u; if(invStmt.getInvokeExpr().getMethod().getSubSignature().equals("void onCreate(android.os.Bundle)")) return u; } } return null; }
@Override public void caseInvokeStmt(InvokeStmt stmt) { SecurityConstraintValueReadSwitch readSwitch = getReadSwitch(stmt.getInvokeExpr()); addConstraints(readSwitch.getConstraints()); addInheritedWriteEffects(readSwitch); removeAccessArtifacts(readSwitch); }
private void initializeHooking(ProcessManifest manifest) { String applicationName = manifest.getApplicationName(); //case 1 if(applicationName != null) { if(applicationName.startsWith(".")) { String packageName = manifest.getPackageName(); if(packageName == null) throw new RuntimeException("There is a problem with the package name"); applicationName = packageName + applicationName; } SootClass applicationSootClass = Scene.v().getSootClass(applicationName); if(applicationSootClass != null) { String attachMethodName = String.format("<%s: void attachBaseContext(android.content.Context)>", applicationName); SootMethod attachMethod = Scene.v().grabMethod(attachMethodName); //case 1 if(attachMethod != null) { Body body = attachMethod.getActiveBody(); Local contextParam = body.getParameterLocal(0); List<Unit> unitsToInstrument = new ArrayList<Unit>(); String hookingHelperApplicationClassAttachMethodName = String.format("<%s: void initializeHooking(android.content.Context)>", UtilInstrumenter.HOOKER_CLASS); SootMethod hookingHelperApplicationClassAttachMethod = Scene.v().getMethod(hookingHelperApplicationClassAttachMethodName); if(hookingHelperApplicationClassAttachMethod == null) throw new RuntimeException("this should not happen"); SootMethodRef ref = hookingHelperApplicationClassAttachMethod.makeRef(); InvokeExpr invExpr = Jimple.v().newStaticInvokeExpr(ref, contextParam); unitsToInstrument.add(Jimple.v().newInvokeStmt(invExpr)); Unit instrumentAfterUnit = null; for(Unit unit : body.getUnits()) { if(unit instanceof InvokeStmt) { InvokeStmt invStmt = (InvokeStmt)unit; if(invStmt.getInvokeExpr().getMethod().getSubSignature().equals("void attachBaseContext(android.content.Context)")) { instrumentAfterUnit = unit; break; } } } if(instrumentAfterUnit == null) throw new RuntimeException("this should not happen"); body.getUnits().insertAfter(unitsToInstrument, instrumentAfterUnit); } //case 2 else { attachMethodName = String.format("<%s: void attachBaseContext(android.content.Context)>", UtilInstrumenter.HELPER_APPLICATION_FOR_HOOKING); attachMethod = Scene.v().grabMethod(attachMethodName); if(attachMethod == null) throw new RuntimeException("this should not happen"); List<Type> params = new ArrayList<Type>(); SootClass contextClass = Scene.v().getSootClass("android.content.Context"); params.add(contextClass.getType()); SootMethod newAttachMethod = new SootMethod("attachBaseContext", params, VoidType.v()); newAttachMethod.setModifiers(soot.Modifier.PROTECTED); newAttachMethod.setActiveBody(attachMethod.getActiveBody()); applicationSootClass.addMethod(newAttachMethod); } //there is no need for our Application class Scene.v().getSootClass(UtilInstrumenter.HELPER_APPLICATION_FOR_HOOKING).setLibraryClass(); } else { throw new RuntimeException("There is a problem with the Application class!"); } } //case 3 else{ //there is no need for any instrumentation since the Application class is set to application-class. } }
private void instrumentInfoAboutNonApiCaller(Body body, Unit unit) { //our instrumented code if(unit.hasTag(InstrumentedCodeTag.name)) return; InvokeExpr invokeExpr = null; if(unit instanceof DefinitionStmt) { DefinitionStmt defStmt = (DefinitionStmt)unit; if(defStmt.containsInvokeExpr()) { invokeExpr = defStmt.getInvokeExpr(); } } else if(unit instanceof InvokeStmt) { InvokeStmt invokeStmt = (InvokeStmt)unit; invokeExpr = invokeStmt.getInvokeExpr(); } if(invokeExpr != null) { if(!UtilInstrumenter.isApiCall(invokeExpr)) { String invokeExprMethodSignature = invokeExpr.getMethod().getSignature(); List<Value> parameter = invokeExpr.getArgs(); List<Unit> generated = new ArrayList<Unit>(); Pair<Value, List<Unit>> arrayRefAndInstrumentation = UtilInstrumenter.generateParameterArray(parameter, body); List<Unit> generatedArrayInstrumentation = arrayRefAndInstrumentation.getSecond(); Value arrayRef = arrayRefAndInstrumentation.getFirst(); Unit generatedInvokeStmt = UtilInstrumenter.makeJimpleStaticCallForPathExecution("logInfoAboutNonApiMethodCaller", RefType.v("java.lang.String"), StringConstant.v(body.getMethod().getSignature()), RefType.v("java.lang.String"), StringConstant.v(invokeExprMethodSignature), UtilInstrumenter.getParameterArrayType(), (parameter.isEmpty())? NullConstant.v() : arrayRef); generatedInvokeStmt.addTag(new InstrumentedCodeTag()); generated.addAll(generatedArrayInstrumentation); generated.add(generatedInvokeStmt); body.getUnits().insertBefore(generated, unit); } } }
@Override public void caseInvokeStmt(InvokeStmt stmt) { InvokeExpr invokeExpr = stmt.getInvokeExpr(); SootClass declaringClass = invokeExpr.getMethod().getDeclaringClass(); if(exprVisitor.isExpressionThatNeedsToBeConvertedToSMT(invokeExpr)) exprVisitor.convertSpecialExpressionsToSMT(invokeExpr, stmt); else if(UtilInstrumenter.isAppDeveloperCode(declaringClass)) { SootMethod method = invokeExpr.getMethod(); Body body = method.retrieveActiveBody(); SMTBinding newRhs = getBindingForTaintedValue(stmt); //if there is no taint-tracking involved (newRhs == null), we do not have to do anything here if(newRhs == null) return; int indexOfInterest = -1; for(int i = 0; i < invokeExpr.getArgCount(); i++) { if(newRhs.getVariableName().equals(invokeExpr.getArg(i).toString())) { indexOfInterest = i; break; } } if(indexOfInterest == -1) return; for(Unit unit : body.getUnits()) { if(unit instanceof IdentityStmt) { IdentityStmt identity = (IdentityStmt)unit; Value rhs = identity.getRightOp(); if(rhs instanceof ParameterRef) { ParameterRef param = (ParameterRef)rhs; if(param.getIndex() == indexOfInterest) { Value lhs = identity.getLeftOp(); SMTBinding newLhs = createNewBindingForValue(lhs); addValueBindingToVariableDeclaration(lhs, newLhs); SMTSimpleAssignment simpleAssignment = new SMTSimpleAssignment(newLhs, new SMTBindingValue(newRhs)); SMTAssertStatement assignmentAssert = new SMTAssertStatement(simpleAssignment); addAssertStmtToAllPrograms(assignmentAssert); } } } } } else { System.err.println(String.format("Double-Check if the following method contains useful information which can be extracted: \n%s", stmt)); } }
private void fixExceptions(SootMethod caller, Unit callSite, Set<SootClass> doneSet) { ThrowAnalysis ta = Options.v().src_prec() == Options.src_prec_apk ? DalvikThrowAnalysis.v() : UnitThrowAnalysis.v(); ThrowableSet throwSet = ta.mightThrow(callSite); for (final Trap t : caller.getActiveBody().getTraps()) if (doneSet.add(t.getException()) && throwSet.catchableAs(t.getException().getType())) { SootMethod thrower = exceptionThrowers.get(t.getException()); if (thrower == null) { if (exceptionClass == null) { exceptionClass = new SootClass("FLOWDROID_EXCEPTIONS", Modifier.PUBLIC); Scene.v().addClass(exceptionClass); } // Create the new method thrower = new SootMethod("throw" + exceptionThrowers.size(), Collections.<Type>emptyList(), VoidType.v()); thrower.setModifiers(Modifier.PUBLIC | Modifier.STATIC); final Body body = Jimple.v().newBody(thrower); thrower.setActiveBody(body); final SootMethod meth = thrower; IEntryPointCreator epc = new BaseEntryPointCreator() { @Override public Collection<String> getRequiredClasses() { return Collections.emptySet(); } @Override protected SootMethod createDummyMainInternal(SootMethod emptySootMethod) { LocalGenerator generator = new LocalGenerator(body); // Create the counter used for the opaque predicate int conditionCounter = 0; Value intCounter = generator.generateLocal(IntType.v()); AssignStmt assignStmt = new JAssignStmt(intCounter, IntConstant.v(conditionCounter)); body.getUnits().add(assignStmt); Stmt afterEx = Jimple.v().newNopStmt(); IfStmt ifStmt = Jimple.v().newIfStmt(Jimple.v().newEqExpr(intCounter, IntConstant.v(conditionCounter)), afterEx); body.getUnits().add(ifStmt); conditionCounter++; Local lcEx = generator.generateLocal(t.getException().getType()); AssignStmt assignNewEx = Jimple.v().newAssignStmt(lcEx, Jimple.v().newNewExpr(t.getException().getType())); body.getUnits().add(assignNewEx); InvokeStmt consNewEx = Jimple.v().newInvokeStmt(Jimple.v().newVirtualInvokeExpr(lcEx, Scene.v().makeConstructorRef(exceptionClass, Collections.<Type>emptyList()))); body.getUnits().add(consNewEx); ThrowStmt throwNewEx = Jimple.v().newThrowStmt(lcEx); body.getUnits().add(throwNewEx); body.getUnits().add(afterEx); return meth; } }; epc.createDummyMain(thrower); exceptionThrowers.put(t.getException(), thrower); exceptionClass.addMethod(thrower); } // Call the exception thrower after the old call site Stmt throwCall = Jimple.v().newInvokeStmt(Jimple.v().newStaticInvokeExpr(thrower.makeRef())); caller.getActiveBody().getUnits().insertBefore(throwCall, callSite); } }
public void caseInvokeStmt(InvokeStmt stmt) { InvokeExpr expr = stmt.getInvokeExpr(); Variable lvar = jt.makeVariable(expr); et.translateExpr(lvar, stmt.getInvokeExprBox()); }
public void caseInvokeStmt(InvokeStmt stmt) { String varName = printValueAssignment(stmt.getInvokeExpr(), "ie"); printStmt(stmt,varName); }
/** * Creates a method body that throws an "unresolved compilation error" * message * @param declaringClass The class that was supposed to contain the method * @return The created SootMethod */ private SootMethod createUnresolvedErrorMethod(SootClass declaringClass) { SootMethod m = new SootMethod(name, parameterTypes, returnType, isStatic()?Modifier.STATIC:0); int modifiers = Modifier.PUBLIC; // we don't know who will be calling us if (isStatic()) modifiers |= Modifier.STATIC; m.setModifiers(modifiers); JimpleBody body = Jimple.v().newBody(m); m.setActiveBody(body); final LocalGenerator lg = new LocalGenerator(body); // For producing valid Jimple code, we need to access all parameters. // Otherwise, methods like "getThisLocal()" will fail. if (!isStatic) { RefType thisType = RefType.v(declaringClass); Local lThis = lg.generateLocal(thisType); body.getUnits().add(Jimple.v().newIdentityStmt(lThis, Jimple.v().newThisRef(thisType))); } for (int i = 0; i < m.getParameterCount(); i++) { Type paramType = m.getParameterType(i); Local lParam = lg.generateLocal(paramType); body.getUnits().add(Jimple.v().newIdentityStmt(lParam, Jimple.v().newParameterRef(paramType, i))); } //exc = new Error RefType runtimeExceptionType = RefType.v("java.lang.Error"); NewExpr newExpr = Jimple.v().newNewExpr(runtimeExceptionType); Local exceptionLocal = lg.generateLocal(runtimeExceptionType); AssignStmt assignStmt = Jimple.v().newAssignStmt(exceptionLocal, newExpr); body.getUnits().add(assignStmt); //exc.<init>(message) SootMethodRef cref = Scene.v().makeConstructorRef(runtimeExceptionType.getSootClass(), Collections.<Type>singletonList(RefType.v("java.lang.String"))); SpecialInvokeExpr constructorInvokeExpr = Jimple.v().newSpecialInvokeExpr(exceptionLocal, cref, StringConstant.v("Unresolved compilation error: Method "+getSignature()+" does not exist!")); InvokeStmt initStmt = Jimple.v().newInvokeStmt(constructorInvokeExpr); body.getUnits().insertAfter(initStmt, assignStmt); //throw exc body.getUnits().insertAfter(Jimple.v().newThrowStmt(exceptionLocal), initStmt); declaringClass.addMethod(m); return m; }
private void split_new() { LocalDefs defs = LocalDefs.Factory.newLocalDefs(jb); PatchingChain<Unit> units = this.jb.getUnits(); Stmt[] stmts = new Stmt[units.size()]; units.toArray(stmts); for ( Stmt stmt : stmts ) { if ( stmt instanceof InvokeStmt ) { InvokeStmt invoke = (InvokeStmt)stmt; if ( invoke.getInvokeExpr() instanceof SpecialInvokeExpr ) { SpecialInvokeExpr special = (SpecialInvokeExpr)invoke.getInvokeExpr(); if ( special.getMethodRef().name().equals("<init>") ) { List<Unit> deflist = defs.getDefsOfAt( (Local)special.getBase(), invoke); while ( deflist.size() == 1 ) { Stmt stmt2 = (Stmt)deflist.get(0); if ( stmt2 instanceof AssignStmt ) { AssignStmt assign = (AssignStmt)stmt2; if ( assign.getRightOp() instanceof Local ) { deflist = defs.getDefsOfAt( (Local)assign.getRightOp(), assign); continue; } else if ( assign.getRightOp() instanceof NewExpr ) { Local newlocal = Jimple.v().newLocal( "tmp", null); newlocal.setName("tmp$" + System.identityHashCode(newlocal)); this.jb.getLocals().add(newlocal); special.setBase(newlocal); DefinitionStmt assignStmt = Jimple.v().newAssignStmt( assign.getLeftOp(), newlocal); Unit u = Util.findLastIdentityUnit(jb, assign); units.insertAfter(assignStmt, u); assign.setLeftOp(newlocal); this.addLocal(newlocal); this.initAssignment(assignStmt); } } break; } } } } } }
public void caseInvokeStmt(InvokeStmt stmt) { this.handleInvokeExpr(stmt.getInvokeExpr(), stmt); }
private void split_new() { LocalDefs defs = LocalDefs.Factory.newLocalDefs(stmtBody); PatchingChain<Unit> units = stmtBody.getUnits(); Stmt[] stmts = new Stmt[units.size()]; units.toArray(stmts); for (Stmt stmt : stmts) { if(stmt instanceof InvokeStmt) { InvokeStmt invoke = (InvokeStmt) stmt; if(invoke.getInvokeExpr() instanceof SpecialInvokeExpr) { SpecialInvokeExpr special = (SpecialInvokeExpr) invoke.getInvokeExpr(); if("<init>".equals(special.getMethodRef().name())) { List<Unit> deflist = defs.getDefsOfAt((Local) special.getBase(), invoke); while(deflist.size() == 1) { Stmt stmt2 = (Stmt) deflist.get(0); if(stmt2 instanceof AssignStmt) { AssignStmt assign = (AssignStmt) stmt2; if(assign.getRightOp() instanceof Local) { deflist = defs.getDefsOfAt((Local) assign.getRightOp(), assign); continue; } else if(assign.getRightOp() instanceof NewExpr) { // We split the local. //G.v().out.println("split: [" + assign + "] and [" + stmt + "]"); Local newlocal = Jimple.v().newLocal("tmp", null); stmtBody.getLocals().add(newlocal); special.setBase(newlocal); units.insertAfter(Jimple.v().newAssignStmt(assign.getLeftOp(), newlocal), assign); assign.setLeftOp(newlocal); } } break; } } } } } }
public void caseInvokeStmt(InvokeStmt stmt) { handleInvokeExpr(stmt.getInvokeExpr(), stmt); }
public void caseInvokeStmt(InvokeStmt stmt) { handleInvokeExpr(stmt.getInvokeExpr()); }
private void split_new() { LocalDefs defs = LocalDefs.Factory.newLocalDefs(stmtBody); PatchingChain<Unit> units = stmtBody.getUnits(); Stmt[] stmts = new Stmt[units.size()]; units.toArray(stmts); for (Stmt stmt : stmts) { if(stmt instanceof InvokeStmt) { InvokeStmt invoke = (InvokeStmt) stmt; if(invoke.getInvokeExpr() instanceof SpecialInvokeExpr) { SpecialInvokeExpr special = (SpecialInvokeExpr) invoke.getInvokeExpr(); if(special.getMethodRef().name().equals("<init>")) { List<Unit> deflist = defs.getDefsOfAt((Local) special.getBase(), invoke); while(deflist.size() == 1) { Stmt stmt2 = (Stmt) deflist.get(0); if(stmt2 instanceof AssignStmt) { AssignStmt assign = (AssignStmt) stmt2; if(assign.getRightOp() instanceof Local) { deflist = defs.getDefsOfAt((Local) assign.getRightOp(), assign); continue; } else if(assign.getRightOp() instanceof NewExpr) { // We split the local. //G.v().out.println("split: [" + assign + "] and [" + stmt + "]"); Local newlocal = Jimple.v().newLocal("tmp", null); stmtBody.getLocals().add(newlocal); special.setBase(newlocal); units.insertAfter(Jimple.v().newAssignStmt(assign.getLeftOp(), newlocal), assign); assign.setLeftOp(newlocal); } } break; } } } } } }
@Override public void caseInvokeStmt(InvokeStmt stmt) { exprV.setOrigStmt(stmt); stmt.getInvokeExpr().apply(exprV); }
public void inInvokeStmt(InvokeStmt s){ InvokeExpr invokeExpr = s.getInvokeExpr(); SootMethod maybeInline = invokeExpr.getMethod(); //check whether we want to inline ASTMethodNode toInlineASTMethod = cleaner.inline(maybeInline); if(toInlineASTMethod ==null){ //not to inline return; } else{//yes we want to inline // we know that the method to be inlined has no declarations. List<Object> subBodies = toInlineASTMethod.get_SubBodies(); if(subBodies.size() != 1){ throw new RuntimeException ("Found ASTMEthod node with more than one subBodies"); } List body = (List)subBodies.get(0); ASTParentNodeFinder finder = new ASTParentNodeFinder(); underAnalysis.apply(finder); List<ASTStatementSequenceNode> newChangedBodyPart = createChangedBodyPart(s,body,finder); boolean replaced = replaceSubBody(s,newChangedBodyPart,finder); if(replaced){ //so the invoke stmt has been replaced with the body of the method invoked /* * if the inlined method contained an assignment to a static field * we want to replace that with a throw stmt */ StaticDefinitionFinder defFinder = new StaticDefinitionFinder(maybeInline); toInlineASTMethod.apply(defFinder); if(defFinder.anyFinalFieldDefined()){ //create throw stmt to be added to inlined method //create a SootMethodRef SootClass runtime = Scene.v().loadClassAndSupport("java.lang.RuntimeException"); if(runtime.declaresMethod("void <init>(java.lang.String)")){ SootMethod sootMethod = runtime.getMethod("void <init>(java.lang.String)"); SootMethodRef methodRef = sootMethod.makeRef(); RefType myRefType = RefType.v(runtime); StringConstant tempString = StringConstant.v("This method used to have a definition of a final variable. "+ "Dava inlined the definition into the static initializer"); List list = new ArrayList(); list.add(tempString); GNewInvokeExpr newInvokeExpr = new GNewInvokeExpr(myRefType,methodRef,list); GThrowStmt throwStmt = new GThrowStmt(newInvokeExpr); AugmentedStmt augStmt = new AugmentedStmt(throwStmt); List<Object> sequence = new ArrayList<Object>(); sequence.add(augStmt); ASTStatementSequenceNode seqNode = new ASTStatementSequenceNode(sequence); List<Object> subBody = new ArrayList<Object>(); subBody.add(seqNode); toInlineASTMethod.replaceBody(subBody); } } } } }
public List<ASTStatementSequenceNode> createChangedBodyPart(InvokeStmt s, List body, ASTParentNodeFinder finder){ //get parent node of invoke stmt Object parent = finder.getParentOf(s); if(parent == null){ throw new RuntimeException ("MethodCall FInder: parent of invoke stmt not found"); } ASTNode parentNode = (ASTNode)parent; if(!(parentNode instanceof ASTStatementSequenceNode)){ throw new RuntimeException ("MethodCall FInder: parent node not a stmt seq node"); } ASTStatementSequenceNode orignal = (ASTStatementSequenceNode)parentNode; //copying the stmts till above the inoke stmt into one stmt sequence node List<Object> newInitialNode = new ArrayList<Object>(); Iterator<Object> it = orignal.getStatements().iterator(); while(it.hasNext()){ AugmentedStmt as = (AugmentedStmt)it.next(); Stmt tempStmt = as.get_Stmt(); if(tempStmt != s){ newInitialNode.add(as); } else{ //the first time we get to a stmt which points to the invoke stmt we break break; } } //copy remaining stmts into the AFTER stmt sequence node List<Object> newSecondNode = new ArrayList<Object>(); while(it.hasNext()){ newSecondNode.add(it.next()); } List<ASTStatementSequenceNode> toReturn = new ArrayList<ASTStatementSequenceNode>(); if(newInitialNode.size()!=0) toReturn.add(new ASTStatementSequenceNode(newInitialNode)); //add inline methods body toReturn.addAll(body); if(newSecondNode.size()!=0) toReturn.add(new ASTStatementSequenceNode(newSecondNode)); return toReturn; }
@Override public void caseInvokeStmt(InvokeStmt s) { result = result.add(mightThrow(s.getInvokeExpr())); }
/** 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()) G.v().out.println("[" + 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); } } }
@Override public boolean isApplicable(UnitGraph graph, Set<Unit> input, Unit node, Set<Unit> output, Set<Value> taintedValues, Queue<MethodAnalysis> queue, Set<MethodAnalysis> processed) { return node instanceof InvokeStmt && isApplicable((InvokeStmt) node); }
private boolean isApplicable(InvokeStmt node) { SootMethod method = node.getInvokeExpr().getMethod(); return methods.stream().anyMatch(m -> isSameSubSignature(method, m)); }
private Set<Value> getTaintedValues(InvokeStmt node) { return node.getInvokeExpr().getArgs().stream().filter(this::isStringLike).collect(Collectors.toSet()); }
@Override public void caseInvokeStmt(InvokeStmt arg0) { injectLabelStatements(arg0); AssignmentTranslation.translateAssignment(this, null, arg0.getInvokeExpr(), arg0); }