Java Code Examples for soot.jimple.Stmt#containsInvokeExpr()

The following examples show how to use soot.jimple.Stmt#containsInvokeExpr() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: BackwardBoomerangSolver.java    From SPDS with Eclipse Public License 2.0 6 votes vote down vote up
@Override
public void computeSuccessor(Node<Statement, Val> node) {
    Statement stmt = node.stmt();
    Optional<Stmt> unit = stmt.getUnit();
    logger.trace("Computing successor for {} with solver {}", node, this);
    if (unit.isPresent()) {
        Stmt curr = unit.get();
        Val value = node.fact();
        SootMethod method = icfg.getMethodOf(curr);
        if (method == null)
            return;
        if (killFlow(method, curr, value)) {
            return;
        }
        if (options.isIgnoredMethod(method)) {
            return;
        }
        if (curr.containsInvokeExpr() && valueUsedInStatement(curr, value) && INTERPROCEDURAL) {
            callFlow(method, node);
        } else if (icfg.isExitStmt(curr)) {
            returnFlow(method, node);
        } else {
            normalFlow(method, node);
        }
    }
}
 
Example 2
Source File: SmartConstantDataExtractorFuzzyAnalysis.java    From FuzzDroid with Apache License 2.0 6 votes vote down vote up
private String fixSMTSolverIntegerOutput(String loggingPoint, Stmt stmt) {
	if(stmt.containsInvokeExpr()) {
		InvokeExpr inv = stmt.getInvokeExpr();
		String metSig = inv.getMethod().getSignature();
		if(metSig.equals("<android.telephony.TelephonyManager: java.lang.String getSimOperator()>") 
				|| metSig.equals("<android.telephony.TelephonyManager: java.lang.String getNetworkOperator()>")
			) {
			String newLoggingPoint = "";
			for(char c : loggingPoint.toCharArray()) {
				if(c < '0' || c > '9') {
					Random rand = new Random();
					int num = rand.nextInt(10);
					newLoggingPoint += num;
				}
				else
					newLoggingPoint += c;
			}
			return newLoggingPoint;				
		}
	}
	return loggingPoint;
}
 
Example 3
Source File: Model.java    From DroidRA with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * Returns the arguments for a potential COAL query.
 * 
 * @param stmt A program statement.
 * @return An array of arguments if the statement is for a COAL query, null otherwise.
 */
public Argument[] getArgumentsForQuery(Stmt stmt) {
  if (stmt.containsInvokeExpr()) {
    InvokeExpr invokeExpr = stmt.getInvokeExpr();
    SootMethod method = invokeExpr.getMethod();
    if (AnalysisParameters.v().isAnalysisClass(method.getDeclaringClass().getName())
        && method.isConcrete() && method.hasActiveBody()) {
      MethodDescription description = queryToMethodDescriptionMap.get(method.getSignature());
      if (description == null) {
        return null;
      } else {
        return description.getArguments();
      }
    }
    return getArgumentsFromMethodDescription(queryToMethodDescriptionMap, invokeExpr);
  }
  return null;
}
 
Example 4
Source File: AuthorityValueAnalysis.java    From ic3 with Apache License 2.0 6 votes vote down vote up
@Override
public Set<Object> computeArgumentValues(Argument argument, Unit callSite) {
  ArgumentValueAnalysis stringAnalysis =
      ArgumentValueManager.v().getArgumentValueAnalysis(
          Constants.DefaultArgumentTypes.Scalar.STRING);

  Stmt stmt = (Stmt) callSite;
  if (!stmt.containsInvokeExpr()) {
    throw new RuntimeException("Statement " + stmt + " does not contain an invoke expression");
  }
  InvokeExpr invokeExpr = stmt.getInvokeExpr();

  Set<Object> hosts =
      stringAnalysis.computeVariableValues(invokeExpr.getArg(argument.getArgnum()[0]), stmt);
  Set<Object> ports =
      stringAnalysis.computeVariableValues(invokeExpr.getArg(argument.getArgnum()[1]), stmt);

  Set<Object> result = new HashSet<>();
  for (Object host : hosts) {
    for (Object port : ports) {
      result.add(new DataAuthority((String) host, (String) port));
    }
  }

  return result;
}
 
Example 5
Source File: QueryForCallSiteDetector.java    From SPDS with Eclipse Public License 2.0 6 votes vote down vote up
@Override
public Optional<? extends Query> test(Stmt unit) {
    Stmt stmt = unit;
    if (!(stmt.containsInvokeExpr()))
        return Optional.empty();
    InvokeExpr invokeExpr = stmt.getInvokeExpr();
    if (!invokeExpr.getMethod().getName().matches(methodNameMatcher))
        return Optional.empty();
    Value param = invokeExpr.getArg(0);
    if (!(param instanceof Local))
        return Optional.empty();
    SootMethod newMethod = icfg.getMethodOf(unit);
    Statement newStatement = new Statement(unit, newMethod);
    Val newVal = new Val(param, newMethod);
    BackwardQuery newBackwardQuery = new BackwardQuery(newStatement, newVal);
    return Optional.<Query> of(newBackwardQuery);
}
 
Example 6
Source File: ArgumentValueAnalysis.java    From DroidRA with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Computes the possible argument values for a given statement and a given argument.
 * 
 * By default this simply calls {@link #computeArgumentValues(Argument, Unit)}.
 * 
 * @param argument An {@link Argument}.
 * @param callSite A call statement.
 * @return The set of possible values for the argument.
 */
public Set<Object> computeArgumentValues(Argument argument, Unit callSite) {
  if (argument.getArgnum() == null) {
    return null;
  }
  if (AnalysisParameters.v().useShimple()) {
    // Shimple is not supported.
    return Collections.singleton((Object) getTopValue());
  } else {
    Stmt stmt = (Stmt) callSite;
    if (!stmt.containsInvokeExpr()) {
      throw new RuntimeException("Statement " + stmt + " does not contain an invoke expression");
    }
    InvokeExpr invokeExpr = stmt.getInvokeExpr();
    int argnum = argument.getArgnum()[0];
    Value value = null;
    if (argnum == Constants.INSTANCE_INVOKE_BASE_INDEX) {
      if (invokeExpr instanceof InstanceInvokeExpr) {
        value = ((InstanceInvokeExpr) invokeExpr).getBase();
      } else {
        throw new RuntimeException("Invoke expression has no base: " + invokeExpr);
      }
    } else {
      value = stmt.getInvokeExpr().getArg(argnum);
    }

    return computeVariableValues(value, stmt);
  }
}
 
Example 7
Source File: SourceSinkTests.java    From JAADAS with GNU General Public License v3.0 5 votes vote down vote up
@Override
public SourceInfo getSourceInfo(Stmt sCallSite, InterproceduralCFG<Unit, SootMethod> cfg) {
	if (sCallSite.containsInvokeExpr()
			&& sCallSite instanceof DefinitionStmt
			&& (sCallSite.getInvokeExpr().getMethod().getName().equals("getSecret")
					|| (sCallSite.getInvokeExpr().getMethod().getName().equals("getSecret2")))) {
		AccessPath ap = new AccessPath(((DefinitionStmt) sCallSite).getLeftOp(), true);
		return new SourceInfo(ap);
	}
	return null;
}
 
Example 8
Source File: SourceSinkTests.java    From JAADAS with GNU General Public License v3.0 5 votes vote down vote up
@Override
public boolean isSink(Stmt sCallSite, InterproceduralCFG<Unit, SootMethod> cfg,
		AccessPath ap) {
	if (!sCallSite.containsInvokeExpr())
		return false;
	SootMethod target = sCallSite.getInvokeExpr().getMethod();
	if (target.getSignature().equals(sink))
		return true;
	
	if (target.getSignature().equals(sinkAP)
			&& sCallSite.getInvokeExpr().getArgCount() > 0
			&& ap.getPlainValue() == sCallSite.getInvokeExpr().getArg(0))
		return true;
	return false;
}
 
Example 9
Source File: IDEALTestingFramework.java    From SPDS with Eclipse Public License 2.0 5 votes vote down vote up
private void parseExpectedQueryResults(SootMethod m, Set<Assertion> queries, Set<SootMethod> visited) {
    if (!m.hasActiveBody() || visited.contains(m))
        return;
    visited.add(m);
    Body activeBody = m.getActiveBody();
    for (Unit callSite : staticIcfg.getCallsFromWithin(m)) {
        staticIcfg.addCalleeListener(new ParseExpectedQueryResultCalleeListener(queries, visited, callSite));
    }
    for (Unit u : activeBody.getUnits()) {
        if (!(u instanceof Stmt))
            continue;

        Stmt stmt = (Stmt) u;
        if (!(stmt.containsInvokeExpr()))
            continue;
        InvokeExpr invokeExpr = stmt.getInvokeExpr();
        String invocationName = invokeExpr.getMethod().getName();
        if (invocationName.equals("shouldNotBeAnalyzed")) {
            queries.add(new ShouldNotBeAnalyzed(stmt));
        }
        if (!invocationName.startsWith("mayBeIn") && !invocationName.startsWith("mustBeIn"))
            continue;
        Value param = invokeExpr.getArg(0);
        Val val = new Val(param, m);
        if (invocationName.startsWith("mayBeIn")) {
            if (invocationName.contains("Error"))
                queries.add(new MayBe(stmt, val, InternalState.ERROR));
            else
                queries.add(new MayBe(stmt, val, InternalState.ACCEPTING));
        } else if (invocationName.startsWith("mustBeIn")) {
            if (invocationName.contains("Error"))
                queries.add(new MustBe(stmt, val, InternalState.ERROR));
            else
                queries.add(new MustBe(stmt, val, InternalState.ACCEPTING));
        }
    }
}
 
Example 10
Source File: SourceMethodReturnValueAnalysis.java    From DroidRA with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Override
public Set<Object> computeMethodReturnValues(Call call) {
  Stmt stmt = call.stmt;
  if (!stmt.containsInvokeExpr() || !(stmt.getInvokeExpr() instanceof InstanceInvokeExpr)) {
    return Collections.singleton((Object) "(.*)");
  } else {
    return Collections.singleton((Object) new SourceDescriptor(((InstanceInvokeExpr) stmt
        .getInvokeExpr()).getBase(), stmt));
  }

}
 
Example 11
Source File: DefaultSourceSinkManager.java    From JAADAS with GNU General Public License v3.0 5 votes vote down vote up
@Override
public SourceInfo getSourceInfo(Stmt sCallSite, InterproceduralCFG<Unit, SootMethod> cfg) {
	SootMethod callee = sCallSite.containsInvokeExpr() ?
			sCallSite.getInvokeExpr().getMethod() : null;
	
	AccessPath targetAP = null;
	if (callee != null && sources.contains(callee.toString())) {
		if (callee.getReturnType() != null 
				&& sCallSite instanceof DefinitionStmt) {
			// Taint the return value
			Value leftOp = ((DefinitionStmt) sCallSite).getLeftOp();
			targetAP = new AccessPath(leftOp, true);
		}
		else if (sCallSite.getInvokeExpr() instanceof InstanceInvokeExpr) {
			// Taint the base object
			Value base = ((InstanceInvokeExpr) sCallSite.getInvokeExpr()).getBase();
			targetAP = new AccessPath(base, true);
		}
	}
	// Check whether we need to taint parameters
	else if (sCallSite instanceof IdentityStmt) {
		IdentityStmt istmt = (IdentityStmt) sCallSite;
		if (istmt.getRightOp() instanceof ParameterRef) {
			ParameterRef pref = (ParameterRef) istmt.getRightOp();
			SootMethod currentMethod = cfg.getMethodOf(istmt);
			if (parameterTaintMethods.contains(currentMethod.toString()))
				targetAP = new AccessPath(currentMethod.getActiveBody()
						.getParameterLocal(pref.getIndex()), true);
		}
	}
	
	if (targetAP == null)
		return null;
	
	// Create the source information data structure
	return new SourceInfo(targetAP);
}
 
Example 12
Source File: AbstractBoomerangSolver.java    From SPDS with Eclipse Public License 2.0 5 votes vote down vote up
protected boolean isIdentityFlow(Val value, Stmt succ, SootMethod method, Collection<State> out) {
    if (out.size() != 1 || succ.containsInvokeExpr() || icfg.isExitStmt(succ))
        return false;
    if (value.isStatic()) {
        if (containsStaticFieldAccess(succ)) {
            return false;
        }
    } else if (succ.containsFieldRef()) {
        return false;
    }
    List<State> l = Lists.newArrayList(out);
    State state = l.get(0);
    return state.equals(new Node<Statement, Val>(new Statement((Stmt) succ, method), value));
}
 
Example 13
Source File: AndroidSourceSinkManager.java    From JAADAS with GNU General Public License v3.0 4 votes vote down vote up
/**
 * Checks whether the given call site indicates a UI source, e.g. a password
 * input
 * 
 * @param sCallSite
 *            The call site that may potentially read data from a sensitive
 *            UI control
 * @param cfg
 *            The bidirectional control flow graph
 * @return True if the given call site reads data from a UI source, false
 *         otherwise
 */
private boolean isUISource(Stmt sCallSite, InterproceduralCFG<Unit, SootMethod> cfg) {
	// If we match input controls, we need to check whether this is a call
	// to one of the well-known resource handling functions in Android
	if (this.layoutMatching != LayoutMatchingMode.NoMatch && sCallSite.containsInvokeExpr()) {
		InvokeExpr ie = sCallSite.getInvokeExpr();
		final String signature = methodToSignature.getUnchecked(ie.getMethod());
		if (signature.equals(Activity_FindViewById)
				|| signature.equals(View_FindViewById)) {
			// Perform a constant propagation inside this method exactly
			// once
			SootMethod uiMethod = cfg.getMethodOf(sCallSite);
			if (analyzedLayoutMethods.add(uiMethod))
				ConstantPropagatorAndFolder.v().transform(uiMethod.getActiveBody());

			// If we match all controls, we don't care about the specific
			// control we're dealing with
			if (this.layoutMatching == LayoutMatchingMode.MatchAll)
				return true;
			// If we don't have a layout control list, we cannot perform any
			// more specific checks
			if (this.layoutControls == null)
				return false;

			// If we match specific controls, we need to get the ID of
			// control and look up the respective data object
			if (ie.getArgCount() != 1) {
				System.err.println("Framework method call with unexpected " + "number of arguments");
				return false;
			}
			int id = 0;
			if (ie.getArg(0) instanceof IntConstant)
				id = ((IntConstant) ie.getArg(0)).value;
			else if (ie.getArg(0) instanceof Local) {
				Integer idVal = findLastResIDAssignment(sCallSite, (Local) ie.getArg(0), (BiDiInterproceduralCFG<Unit, SootMethod>) cfg, new HashSet<Stmt>(cfg.getMethodOf(sCallSite).getActiveBody().getUnits().size()));
				if (idVal == null) {
					System.err.println("Could not find assignment to local "
								+ ((Local) ie.getArg(0)).getName()
								+ " in method "
								+ cfg.getMethodOf(sCallSite).getSignature());
					return false;
				} else
					id = idVal.intValue();
			} else {
				System.err.println("Framework method call with unexpected " + "parameter type: " + ie.toString() + ", " + "first parameter is of type " + ie.getArg(0).getClass());
				return false;
			}

			LayoutControl control = this.layoutControls.get(id);
			if (control == null) {
				System.err.println("Layout control with ID " + id + " not found");
				return false;
			}
			if (this.layoutMatching == LayoutMatchingMode.MatchSensitiveOnly && control.isSensitive())
				return true;
		}
	}
	return false;
}
 
Example 14
Source File: UtilDecisionMaker.java    From FuzzDroid with Apache License 2.0 4 votes vote down vote up
public static Set<Unit> extractAllTargetLocations() {
	//extract all logging points from file
	Set<String> targetLocationsTmp = new HashSet<String>();
	
	Set<String> targetMethods = new HashSet<String>();		
	Set<Unit> allTargetLocations = new HashSet<Unit>();
	
	try{
		BufferedReader br = new BufferedReader(new FileReader(TARGET_METHODS_FILENAME));
	    try {
	        String line;
	        while ((line = br.readLine()) != null) {
	        	targetLocationsTmp.add(line);
	        }
	    } finally {
	        br.close();
	    }
	}catch(Exception ex) {
		LoggerHelper.logEvent(MyLevel.EXCEPTION_ANALYSIS, ex.getMessage());
		ex.printStackTrace();
		System.exit(-1);
	}
	
	targetMethods.addAll(targetLocationsTmp);
	
	if(!targetLocationsTmp.isEmpty()) {
		
		Chain<SootClass> applicationClasses = Scene.v().getApplicationClasses();
		for(SootClass clazz : applicationClasses) {				
			//no need to look into our code
			if (!UtilInstrumenter.isAppDeveloperCode(clazz)) 
				continue;
			
			for(SootMethod method : clazz.getMethods()) {
				if(method.hasActiveBody()) {
					Body body = method.retrieveActiveBody();
					for (Iterator<Unit> unitIt = body.getUnits().iterator(); unitIt.hasNext(); ) {
						Unit curUnit = unitIt.next();
						if(curUnit instanceof Stmt) {
							Stmt statement = (Stmt)curUnit;
							
							if(statement.containsInvokeExpr()){
								InvokeExpr invExpr = statement.getInvokeExpr();
								String invokeExprMethodSignature = invExpr.getMethod().getSignature();
								
								for(String targetLocation : targetLocationsTmp) {
									//we accept all classes
									if(targetLocation.startsWith("<*:")) {
										String pattern = "<.:\\s(.*)\\s(.*)\\((.*)\\)>";
									      Pattern r = Pattern.compile(pattern);

									      Matcher m = r.matcher(targetLocation);
									      if (m.find()) {
									    	  if(m.group(1).equals(invExpr.getMethod().getReturnType().toString()) &&
									    		  m.group(2).equals(invExpr.getMethod().getName()))
									    		  allTargetLocations.add(curUnit);
									      }
									}
									else if(targetLocation.equals(invokeExprMethodSignature))
										allTargetLocations.add(curUnit);
								}
							}
						}
					}
				}
			}
		}
	}
	
	return allTargetLocations;		
}
 
Example 15
Source File: DynamicValueAnalysis.java    From FuzzDroid with Apache License 2.0 4 votes vote down vote up
@Override
public List<AnalysisDecision> resolveRequest(DecisionRequest clientRequest,
		ThreadTraceManager completeHistory) {
	Stmt s = (Stmt) codePositionManager.getUnitForCodePosition(clientRequest.getCodePosition() + 1);
	if (!s.containsInvokeExpr())
		return Collections.emptyList();
	
	RefType stringType = RefType.v("java.lang.String");
	
	// Return the dynamically-obtained values
	Set<DynamicValue> runtimeValues = completeHistory.getNewestClientHistory().getDynamicValues().getValues();
	List<AnalysisDecision> decisions = new ArrayList<>(runtimeValues.size());
	for (DynamicValue value : runtimeValues) {
		ServerResponse serverResponse = new ServerResponse();
		serverResponse.setAnalysisName(getAnalysisName());
		serverResponse.setResponseExist(true);
		
		Type returnType = s.getInvokeExpr().getMethod().getReturnType();
		if (clientRequest.isHookAfter() && isSupported(returnType)) {
			serverResponse.setReturnValue(checkAndGet(returnType, value));
		}
		else {
			Set<Pair<Integer, Object>> paramValues = new HashSet<>();
			for (int i = 0; i < s.getInvokeExpr().getArgCount(); i++) {
				Type paramType = s.getInvokeExpr().getMethod().getParameterType(i);
				if (paramType == stringType) {
					Object newParamVal = checkAndGet(paramType, value);
					if (newParamVal != null)
						paramValues.add(new Pair<Integer, Object>(i, newParamVal));
				}
			}
			serverResponse.setParamValues(paramValues);
		}
		
		AnalysisDecision decision = new AnalysisDecision();
		decision.setAnalysisName(getAnalysisName());
		decision.setServerResponse(serverResponse);
		decision.setDecisionWeight(5);
		decisions.add(decision);
	}
	return decisions;
}
 
Example 16
Source File: ICCLink.java    From soot-infoflow-android-iccta with GNU Lesser General Public License v2.1 4 votes vote down vote up
public void linkWithTarget() 
{
    if (fromSM == null) 
    {
    	try
    	{
    		fromSM = Scene.v().getMethod(fromSMString);
    		
    		Body body = fromSM.retrieveActiveBody();
            units = body.getUnits();
            
            // index in (0, 1, 2, 3, ...)
            int index = instructions.indexOf(instruction);
            
            System.out.println("body: "+ body);
            // get correct unit for the link source method
            int i = 0;
            for (Unit u: units) {
                Stmt stmt = (Stmt)u;
                System.out.println("bs: "+ stmt);
                if (!stmt.containsInvokeExpr())
                    continue;
                System.out.println("s: "+ stmt);
                if (isICCMethod(stmt.getInvokeExpr().getMethod())) {
                    System.out.println("u: "+ u);
                    if (index == i++) {
                        fromU = u;
                        break;
                    }
                }
                
            }
            System.out.println("fromU: "+ fromU);
    	}
    	catch (Exception ex)
    	{
    		System.out.println("Linking the target: " + fromSMString + " is ignored.");
    		//ex.printStackTrace();
    	}
    }
}
 
Example 17
Source File: ExtraExtractor.java    From soot-infoflow-android-iccta with GNU Lesser General Public License v2.1 4 votes vote down vote up
@Override
public void updateBodyJimple(Body body) 
{
	if (AndroidHelper.isAndroidClass(body.getMethod().getDeclaringClass().getName()))
	{
		return;
	}
	
	PatchingChain<Unit> units = body.getUnits();
	
	String methodSignature = body.getMethod().getSignature();
	int count = 0;
	List<String> getKeys = new ArrayList<String>();
	List<String> putKeys = new ArrayList<String>();
	
	for (Iterator<Unit> iter = units.snapshotIterator(); iter.hasNext(); )
	{
		Stmt stmt = (Stmt) iter.next();
		
		if (! stmt.containsInvokeExpr())
		{
			continue;
		}
		
		SootMethod sm = stmt.getInvokeExpr().getMethod();
		String methodName = sm.getName();
		int type = 0; //0:other | 1:get | 2:put
		String extraKey = null;
		
		if (methodName.startsWith("get"))
		{
			type = 1;
		}
		else if (methodName.startsWith("put"))
		{
			type = 2;
		}
		
		if (0 == type)
		{
			continue;
		}
		
		if ( (sm.getDeclaringClass().toString().equals(intentCls) && methodName.contains("Extra")) ||
			 (sm.getDeclaringClass().toString().equals(bundleCls)))
		{
			if (stmt.getInvokeExpr().getArgs().size() > 0)
			{
				Value v = stmt.getInvokeExpr().getArgs().get(0);
				if (v.toString().contains("\""))
				{
					extraKey = v.toString();
				}
				else
				{
					extraKey = "<anything>" + (count++);
				}
			}
		}
		
		if (type == 1 && extraKey != null)
		{
			getKeys.add(extraKey);
		}
		else if (type == 2 && extraKey != null)
		{
			putKeys.add(extraKey);
		}
	}
	
	if (getKeys.size() != 0)
	{
		getExtras.put(methodSignature, getKeys);
	}
	if (putKeys.size() != 0)
	{
		putExtras.put(methodSignature, putKeys);
	}
	
	//System.out.println(getExtras);
	//System.out.println(putExtras);
}
 
Example 18
Source File: InterproceduralConstantValuePropagator.java    From JAADAS with GNU General Public License v3.0 4 votes vote down vote up
/**
 * Checks whether the given method or one of its transitive callees has
 * side-effects or calls a sink method
 * @param method The method to check
 * @param runList A set to receive all methods that have already been
 * processed
 * @param cache The cache in which to store the results
 * @return True if the given method or one of its transitive callees has
 * side-effects or calls a sink method, otherwise false.
 */
private boolean hasSideEffectsOrReadsThis(SootMethod method,
		Set<SootMethod> runList) {		
	// Without a body, we cannot say much
	if (!method.hasActiveBody())
		return false;
	
	// Do we already have an entry?
	Boolean hasSideEffects = methodSideEffects.get(method);
	if (hasSideEffects != null)
		return hasSideEffects;
	
	// Do not process the same method twice
	if (!runList.add(method))
		return false;
	
	// If this is an Android stub method that just throws a stub exception,
	// this will never happen in practice and can be removed
	if (methodIsAndroidStub(method)) {
		methodSideEffects.put(method, false);
		return false;
	}
	
	// Scan for references to this variable
	Local thisLocal = method.isStatic() ? null : method.getActiveBody().getThisLocal();
	for (Unit u : method.getActiveBody().getUnits()) {
		if (u instanceof AssignStmt) {
			AssignStmt assign = (AssignStmt) u;
			if (assign.getLeftOp() instanceof FieldRef
					|| assign.getLeftOp() instanceof ArrayRef) {
				methodSideEffects.put(method, true);
				return true;
			}
		}
		
		Stmt s = (Stmt) u;
		
		// If this statement uses the "this" local, we have to
		// conservatively assume that is can read data
		if (thisLocal != null)
			for (ValueBox vb : s.getUseBoxes())
				if (vb.getValue() == thisLocal)
					return true;
		
		if (s.containsInvokeExpr()) {
			// Check the callees
			for (Iterator<Edge> edgeIt = Scene.v().getCallGraph().edgesOutOf(u); edgeIt.hasNext(); ) {
				Edge e = edgeIt.next();
				if (hasSideEffectsOrReadsThis(e.getTgt().method(), runList))
					return true;
			}
		}
	}
	
	// Variable is not read
	methodSideEffects.put(method, false);
	return false;
}
 
Example 19
Source File: CallFlowFunctionFactory.java    From DroidRA with GNU Lesser General Public License v2.1 4 votes vote down vote up
/**
 * Returns a call flow function.
 * 
 * @param src A statement that is the source of a call edge in the call graph. This is generally a
 *          call statement, but field accesses can also lead to edges leading to class
 *          initializers.
 * @param dest The destination method.
 * @param zeroValue The zero value for the analysis, which represents the absence of a data flow
 *          fact.
 * @return The call flow function for the input statement.
 */
public FlowFunction<Value> getCallFlowFunction(Unit src, final SootMethod dest,
    final Value zeroValue) {
  if (logger.isDebugEnabled()) {
    logger.debug("Call: " + src);
  }

  String declaringClass = dest.getDeclaringClass().getName();

  if (!AnalysisParameters.v().isAnalysisClass(declaringClass)) {
    // Only propagate through analysis classes.
    return KillAll.v();
  }

  Stmt stmt = (Stmt) src;
  // Some statements other than call statements (e.g., field accesses) can lead to call edges to
  // class initializers.
  boolean containsInvokeExpr = stmt.containsInvokeExpr();

  final InvokeExpr ie = containsInvokeExpr ? stmt.getInvokeExpr() : null;

  if (containsInvokeExpr
      && (Model.v().getArgumentsForGenMethod(ie) != null || Model.v()
          .getArgumentsForCopyConstructor(ie.getMethodRef()) != null)) {
    return KillAll.v();
  }

  return new FlowFunction<Value>() {
    @Override
    public Set<Value> computeTargets(Value source) {
      if (logger.isDebugEnabled()) {
        logger.debug("Source: " + source);
      }

      if (dest.getName().equals(SootMethod.staticInitializerName)) {
        if (source instanceof FieldRef) {
          return Collections.singleton(source);
        } else {
          return Collections.emptySet();
        }
      }

      final List<Value> paramLocals = new ArrayList<Value>();

      for (int i = 0; i < dest.getParameterCount(); ++i) {
        // TODO (Damien): maybe activate again?
        // if (ie.getArg(i) instanceof NullConstant && source.equals(zeroValue)) {
        // return Collections.singleton((Value) dest.getActiveBody().getParameterLocal(i));
        // }
        paramLocals.add(dest.getActiveBody().getParameterLocal(i));
      }

      int argIndex = FunctionFactoryUtils.shouldPropagateSource(source, ie.getArgs());
      if (argIndex != -1) {
        if (logger.isDebugEnabled()) {
          logger.debug("Returning " + paramLocals.get(argIndex));
        }
        return Collections.singleton(paramLocals.get(argIndex));
      }

      if (source instanceof StaticFieldRef) {
        // Always propagate static fields.
        return Collections.singleton(source);
      } else if (source instanceof InstanceFieldRef) {
        if (FunctionFactoryUtils.shouldPropagateInstanceField((InstanceFieldRef) source, ie)) {
          return Collections.singleton(source);
        }
      }

      if (logger.isDebugEnabled()) {
        logger.debug("Returning empty set");
      }
      return Collections.emptySet();
    }
  };
}
 
Example 20
Source File: GlobalInstanceTransformer.java    From FuzzDroid with Apache License 2.0 4 votes vote down vote up
@Override
protected void internalTransform(String phaseName, Map<String, String> options) {
	// Get some system components
	SootClass scActivity = Scene.v().getSootClassUnsafe("android.app.Activity");
	SootClass scService = Scene.v().getSootClassUnsafe("android.app.Service");
	SootClass scBroadcastReceiver = Scene.v().getSootClassUnsafe("android.app.BroadcastReceiver");
	SootClass scContentProvider = Scene.v().getSootClassUnsafe("android.app.ContentProvider");
	
	// Get the registration class
	SootClass scRegistrar = Scene.v().getSootClassUnsafe("de.tu_darmstadt.sse.additionalappclasses.ComponentCallerService");
	SootMethodRef smRegistrarRef = scRegistrar.getMethodByName("registerGlobalInstance").makeRef();
	
	// Get the getClass() method
	Type classType = Scene.v().getType("java.lang.Class");
	SootMethodRef smGetClass = Scene.v().getObjectType().getSootClass().getMethod("java.lang.Class getClass()").makeRef();
	
	// Is this an Android component?
	for (SootClass sc : Scene.v().getApplicationClasses()) {
		// We only instrument user code
		if (!UtilInstrumenter.isAppDeveloperCode(sc))
			continue;
		
		// Is this class a component?
		if (Scene.v().getOrMakeFastHierarchy().canStoreType(sc.getType(), scActivity.getType())
				|| Scene.v().getOrMakeFastHierarchy().canStoreType(sc.getType(), scService.getType())
				|| Scene.v().getOrMakeFastHierarchy().canStoreType(sc.getType(), scBroadcastReceiver.getType())
				|| Scene.v().getOrMakeFastHierarchy().canStoreType(sc.getType(), scContentProvider.getType())) {
			Body b = null;
			Local locThis = null;
			Unit lastUnit = null;
			
			// Do we already have a constructor?
			SootMethod cons = sc.getMethodUnsafe("void <init>()");
			if (cons == null) {
				SootMethod smSuperClassCons = sc.getSuperclass().getMethodUnsafe("void <init>()");
				if (smSuperClassCons == null)
					continue;
				
				// Create the new constructor
				cons = new SootMethod("<init>", Collections.<Type>emptyList(), VoidType.v());
				sc.addMethod(cons);
				cons.setActiveBody(b = Jimple.v().newBody(cons));
				
				// Add a reference to the "this" object
				locThis = Jimple.v().newLocal("this", sc.getType());
				b.getLocals().add(locThis);
				b.getUnits().add(Jimple.v().newIdentityStmt(locThis, Jimple.v().newThisRef(sc.getType())));
				
				// Add a call to the superclass constructor
				b.getUnits().add(Jimple.v().newInvokeStmt(Jimple.v().newSpecialInvokeExpr(locThis,
						smSuperClassCons.makeRef())));
				
				// Add a return statement
				b.getUnits().add(lastUnit = Jimple.v().newReturnVoidStmt());
			}
			else {
				b = cons.getActiveBody();
				locThis = b.getThisLocal();
				
				// Find where we can inject out code. We must have called
				// the super constructor first, or the Dalvik verifier will
				// complain that the "this" local is not yet initialized.
				for (Unit u : b.getUnits()) {
					Stmt s = (Stmt) u;
					if (s.containsInvokeExpr()) {
						InvokeExpr iexpr = s.getInvokeExpr();
						if (iexpr instanceof SpecialInvokeExpr) {
							if (iexpr.getMethod().getName().equals("<init>")
									&& ((SpecialInvokeExpr) iexpr).getBase() == locThis) {
								lastUnit = b.getUnits().getSuccOf(u);
								break;
							}
						}
					}
				}
			}
			
			// Get the class
			LocalGenerator localGen = new LocalGenerator(b);
			Local locClass = localGen.generateLocal(classType);
			Stmt stmtAssignClass = Jimple.v().newAssignStmt(locClass, Jimple.v().newVirtualInvokeExpr(
					locThis, smGetClass));
			stmtAssignClass.addTag(new InstrumentedCodeTag());
			b.getUnits().insertBefore(stmtAssignClass, lastUnit);
			
			// Register the instance
			List<Value> argList = new ArrayList<>();
			argList.add(locClass);
			argList.add(locThis);
			Stmt stmtRegister = Jimple.v().newInvokeStmt(Jimple.v().newStaticInvokeExpr(
					smRegistrarRef, argList));
			stmtRegister.addTag(new InstrumentedCodeTag());
			b.getUnits().insertBefore(stmtRegister, lastUnit);
		}
	}
}