soot.jimple.IdentityStmt Java Examples

The following examples show how to use soot.jimple.IdentityStmt. 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: SootHelper.java    From soot-infoflow-android-iccta with GNU Lesser General Public License v2.1 6 votes vote down vote up
public static Stmt getFirstNonIdentityStmt(SootMethod sootMethod)
{
	Stmt rtVal = null;
	
	Body b = sootMethod.retrieveActiveBody();
	PatchingChain<Unit> units = b.getUnits();
	
	for (Iterator<Unit> iter = units.iterator(); iter.hasNext(); )
	{
		Stmt stmt = (Stmt) iter.next();
		
		if ( ! (stmt instanceof IdentityStmt) )
		{
			rtVal = stmt;
		}
	}
	
	return rtVal;
}
 
Example #2
Source File: DummyMainGenerator.java    From DroidRA with GNU Lesser General Public License v2.1 6 votes vote down vote up
public void instrumentDummyMainMethod(SootMethod mainMethod)
{
	Body body = mainMethod.getActiveBody();
   	
   	PatchingChain<Unit> units = body.getUnits();
   	for (Iterator<Unit> iter = units.snapshotIterator(); iter.hasNext(); )
   	{
   		Stmt stmt = (Stmt) iter.next();
   		
   		if (stmt instanceof IdentityStmt)
   		{
   			continue;
   		}
   		   	
   		//For the purpose of confusion dex optimization (because of the strategy of generating dummyMain method)
		AssignStmt aStmt = (AssignStmt) stmt;
		SootMethod fuzzyMe = generateFuzzyMethod(mainMethod.getDeclaringClass());
		InvokeExpr invokeExpr = Jimple.v().newVirtualInvokeExpr(body.getThisLocal(), fuzzyMe.makeRef());
		Unit assignU = Jimple.v().newAssignStmt(aStmt.getLeftOp(), invokeExpr);
		units.insertAfter(assignU, aStmt);
		
		break;
   	}
}
 
Example #3
Source File: ForwardBoomerangResults.java    From SPDS with Eclipse Public License 2.0 6 votes vote down vote up
private void findLastUsage(Statement exitStmt, Map<Val, W> row, Table<Statement, Val, W> destructingStatement,
        ForwardBoomerangSolver<W> forwardSolver) {
    LinkedList<Statement> worklist = Lists.newLinkedList();
    worklist.add(exitStmt);
    Set<Statement> visited = Sets.newHashSet();
    while (!worklist.isEmpty()) {
        Statement curr = worklist.poll();
        if (!visited.add(curr)) {
            continue;
        }
        boolean valueUsedInStmt = false;
        for (Entry<Val, W> e : row.entrySet()) {
            if (forwardSolver.valueUsedInStatement(curr.getUnit().get(), e.getKey())) {
                destructingStatement.put(curr, e.getKey(), e.getValue());
                valueUsedInStmt = true;
            }
        }
    	Stmt stmt = curr.getUnit().get();
        if (!valueUsedInStmt && /**Do not continue over CatchStmt*/!(stmt instanceof IdentityStmt)) {
            for (Unit succ : icfg.getPredsOf(curr.getUnit().get())) {
                worklist.add(new Statement((Stmt) succ, curr.getMethod()));
            }
        }
    }
}
 
Example #4
Source File: Body.java    From JAADAS with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Get all the LHS of the identity statements assigning from parameter references.
 *
 * @return a list of size as per <code>getMethod().getParameterCount()</code> with all elements ordered as per the parameter index.
 * @throws RuntimeException if a parameterref is missing
 */
public List<Local> getParameterLocals(){
    final int numParams = getMethod().getParameterCount();
    final List<Local> retVal = new ArrayList<Local>(numParams);

    //Parameters are zero-indexed, so the keeping of the index is safe
    for (Unit u : getUnits()){
        if (u instanceof IdentityStmt){
            IdentityStmt is = ((IdentityStmt)u);
            if (is.getRightOp() instanceof ParameterRef){
                ParameterRef pr = (ParameterRef) is.getRightOp();
                retVal.add(pr.getIndex(), (Local) is.getLeftOp());
            }
        }
    }
    if (retVal.size() != numParams){
    	//FLANKER FIX BEGIN
        //throw new RuntimeException("couldn't find parameterref! in " + getMethod());
    	return retVal;
    	//FLANKER FIX END
    }
    return retVal;
}
 
Example #5
Source File: Body.java    From JAADAS with GNU General Public License v3.0 6 votes vote down vote up
/** Return LHS of the first identity stmt assigning from \@parameter i. **/
public Local getParameterLocal(int i)
{
    for (Unit s : getUnits())
    {
        if (s instanceof IdentityStmt &&
            ((IdentityStmt)s).getRightOp() instanceof ParameterRef)
        {
            IdentityStmt is = (IdentityStmt)s;
            ParameterRef pr = (ParameterRef)is.getRightOp();
            if (pr.getIndex() == i)
                return (Local)is.getLeftOp();
        }
    }

    throw new RuntimeException("couldn't find parameterref" + i +"! in "+getMethod());
}
 
Example #6
Source File: SynchronizedMethodTransformer.java    From JAADAS with GNU General Public License v3.0 6 votes vote down vote up
protected void internalTransform(Body b, String phaseName, Map<String, String> options) {
	if (!b.getMethod().isSynchronized() || b.getMethod().isStatic())
		return;
	
	Iterator<Unit> it = b.getUnits().snapshotIterator();
	while (it.hasNext()) {
		Unit u = it.next();
		if (u instanceof IdentityStmt)
			continue;
		
		// This the first real statement. If it is not a MonitorEnter
		// instruction, we generate one
		if (!(u instanceof EnterMonitorStmt)) {
			b.getUnits().insertBeforeNoRedirect(Jimple.v().newEnterMonitorStmt(b.getThisLocal()), u);
			
			// We also need to leave the monitor when the method terminates
			UnitGraph graph = new ExceptionalUnitGraph(b);
			for (Unit tail : graph.getTails())
    			b.getUnits().insertBefore(Jimple.v().newExitMonitorStmt(b.getThisLocal()), tail);
		}
		break;
	}
}
 
Example #7
Source File: ConstraintChecker.java    From JAADAS with GNU General Public License v3.0 6 votes vote down vote up
public void caseIdentityStmt(IdentityStmt stmt) {
	Value l = stmt.getLeftOp();
	Value r = stmt.getRightOp();

	if (l instanceof Local) {
		if (((Local) l).getType() instanceof IntegerType) {
			TypeNode left = ClassHierarchy.v().typeNode(
					(((Local) l).getType()));
			TypeNode right = ClassHierarchy.v().typeNode(r.getType());

			if (!right.hasAncestor_1(left)) {
				if (fix) {
					((soot.jimple.internal.JIdentityStmt) stmt)
							.setLeftOp(insertCastAfter((Local) l,
									getTypeForCast(left),
									getTypeForCast(right), stmt));
				} else {
					error("Type Error(16)");
				}
			}
		}
	}
}
 
Example #8
Source File: StmtVisitor.java    From JAADAS with GNU General Public License v3.0 6 votes vote down vote up
@Override
public void caseIdentityStmt(IdentityStmt stmt) {
	Value lhs = stmt.getLeftOp();
	Value rhs = stmt.getRightOp();
	if (rhs instanceof CaughtExceptionRef) {
		// save the caught exception with move-exception
		Register localReg = regAlloc.asLocal(lhs);
		
           addInsn(new Insn11x(Opcode.MOVE_EXCEPTION, localReg), stmt);

           this.insnRegisterMap.put(insns.get(insns.size() - 1), LocalRegisterAssignmentInformation.v(localReg, (Local)lhs));
	} else if (rhs instanceof ThisRef || rhs instanceof ParameterRef) {
		/* 
		 * do not save the ThisRef or ParameterRef in a local, because it always has a parameter register already.
		 * at least use the local for further reference in the statements
		 */
		Local localForThis = (Local) lhs;
		regAlloc.asParameter(belongingMethod, localForThis);
		
		parameterInstructionsList.add(LocalRegisterAssignmentInformation.v(regAlloc.asLocal(localForThis).clone(), localForThis));
	} else {
		throw new Error("unknown Value as right-hand side of IdentityStmt: " + rhs);
	}
}
 
Example #9
Source File: ConstraintCollector.java    From JAADAS with GNU General Public License v3.0 6 votes vote down vote up
public void caseIdentityStmt(IdentityStmt stmt) {
	Value l = stmt.getLeftOp();
	Value r = stmt.getRightOp();

	if (l instanceof Local) {
		TypeVariable left = resolver.typeVariable((Local) l);

		if (!(r instanceof CaughtExceptionRef)) {
			TypeVariable right = resolver.typeVariable(r.getType());
			right.addParent(left);
		} else {
			List<RefType> exceptionTypes = TrapManager.getExceptionTypesOf(stmt, stmtBody);
			Iterator<RefType> typeIt = exceptionTypes.iterator();

			while (typeIt.hasNext()) {
				Type t = typeIt.next();

				resolver.typeVariable(t).addParent(left);
			}

			if (uses) {
				left.addParent(resolver.typeVariable(RefType.v("java.lang.Throwable")));
			}
		}
	}
}
 
Example #10
Source File: CodePositionTracking.java    From FuzzDroid with Apache License 2.0 5 votes vote down vote up
@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);
	}
}
 
Example #11
Source File: Body.java    From JAADAS with GNU General Public License v3.0 5 votes vote down vote up
/**
  * Returns the list of parameter references used in this body. The list is as long as
  * the number of parameters declared in the associated method's signature.
  * The list may have <code>null</code> entries for parameters not referenced in the body.
  * The returned list is of fixed size.
  */
 public List<Value> getParameterRefs()
 {
 	Value[] res = new Value[getMethod().getParameterCount()];
     for (Unit s : getUnits()) {
         if (s instanceof IdentityStmt) {
	Value rightOp = ((IdentityStmt)s).getRightOp();
	if (rightOp instanceof ParameterRef) {
		ParameterRef parameterRef = (ParameterRef) rightOp;
		res[parameterRef.getIndex()] = parameterRef;
	}
}
     }
     return Arrays.asList(res);
 }
 
Example #12
Source File: Body.java    From JAADAS with GNU General Public License v3.0 5 votes vote down vote up
/** Return LHS of the first identity stmt assigning from \@this. **/
public Local getThisLocal()
{
    for (Unit s : getUnits())
    {
        if (s instanceof IdentityStmt &&
            ((IdentityStmt)s).getRightOp() instanceof ThisRef)
            return (Local)(((IdentityStmt)s).getLeftOp());
    }

    throw new RuntimeException("couldn't find identityref!"+" in "+getMethod());
}
 
Example #13
Source File: FastDexTrapTightener.java    From JAADAS with GNU General Public License v3.0 5 votes vote down vote up
private boolean isDexInstruction(Unit unit) {
	if (unit instanceof IdentityStmt) {
		IdentityStmt is = (IdentityStmt) unit;
		return !(is.getRightOp() instanceof ThisRef
				|| is.getRightOp() instanceof ParameterRef);
	}
	return true;
}
 
Example #14
Source File: Util.java    From JAADAS with GNU General Public License v3.0 5 votes vote down vote up
/**
 * A new "normal" statement cannot be inserted in the middle of special
 * "identity statements" (a = @parameter or b = @this in Jimple).
 * 
 * This method returns the last "identity statement" of the method.
 * @param b
 * @param s
 * @return
 */
public static Unit findLastIdentityUnit(Body b, Stmt s) {
    Unit u2 = s;
    Unit u1 = s;
    while (u1 instanceof IdentityStmt) {
        u2 = u1;
        u1 = b.getUnits().getSuccOf(u1);
    }
    return u2;
}
 
Example #15
Source File: CrashReporterInjection.java    From FuzzDroid with Apache License 2.0 5 votes vote down vote up
@Override
protected void internalTransform(String phaseName,
		Map<String, String> options) {
	// Make a reference to the registration method
	SootMethodRef ref = Scene.v().makeMethodRef(
			Scene.v().getSootClass(UtilInstrumenter.JAVA_CLASS_FOR_CRASH_REPORTING),
			"registerExceptionHandler",
			Collections.<Type>emptyList(),
			VoidType.v(),
			true);
	
	for (String sig : methodsToInstrument) {
		try{
			SootMethod sm = Scene.v().grabMethod(sig);
			if(sm == null)
				continue;
			
			for (Iterator<Unit> unitIt = sm.getActiveBody().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)
					continue;
				
				// Put the registration in
				Stmt stmt = Jimple.v().newInvokeStmt(Jimple.v().newStaticInvokeExpr(ref));
				stmt.addTag(new InstrumentedCodeTag());					
				sm.getActiveBody().getUnits().insertAfter(stmt, curUnit);
				break;
			}
		}catch(Exception ex) {
			ex.printStackTrace();
		}
	}
}
 
Example #16
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 #17
Source File: InterproceduralConstantValuePropagator.java    From JAADAS with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Gets the first statement in the body of the given method that does not
 * assign the "this" local or a parameter local
 * @param sm The method in whose body to look
 * @return The first non-identity statement in the body of the given method.
 */
private Unit getFirstNonIdentityStmt(SootMethod sm) {
	for (Unit u : sm.getActiveBody().getUnits()) {
		if (!(u instanceof IdentityStmt))
			return u;
		
		IdentityStmt id = (IdentityStmt) u;
		if (!(id.getRightOp() instanceof ThisRef)
				&& !(id.getRightOp() instanceof ParameterRef))
			return u;
	}
	return null;
}
 
Example #18
Source File: ThisInliner.java    From JAADAS with GNU General Public License v3.0 5 votes vote down vote up
private IdentityStmt findIdentityStmt(Body b){
    for (Unit u : b.getUnits()) {
        Stmt s = (Stmt)u;
        if ((s instanceof IdentityStmt) && (((IdentityStmt)s).getRightOp() instanceof ThisRef)){
            return (IdentityStmt)s;
        }
    }
    return null;
}
 
Example #19
Source File: ConstraintCollector.java    From JAADAS with GNU General Public License v3.0 5 votes vote down vote up
public void caseIdentityStmt(IdentityStmt stmt) {
	Value l = stmt.getLeftOp();
	Value r = stmt.getRightOp();

	if (l instanceof Local) {
		if (((Local) l).getType() instanceof IntegerType) {
			TypeVariable left = resolver.typeVariable((Local) l);

			TypeVariable right = resolver.typeVariable(r.getType());
			right.addParent(left);
		}
	}
}
 
Example #20
Source File: Util.java    From JAADAS with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Returns the first statement after all the "identity statements".
 * @param b
 * @param s
 * @return
 */
public static Unit findFirstNonIdentityUnit(Body b, Stmt s) {
    Unit u1 = s;
    while (u1 instanceof IdentityStmt)
        u1 = b.getUnits().getSuccOf(u1);
    return u1;
}
 
Example #21
Source File: StmtTranslator.java    From JAADAS with GNU General Public License v3.0 4 votes vote down vote up
public void caseIdentityStmt(IdentityStmt stmt) {
	handleAssign(stmt);			
}
 
Example #22
Source File: BusyCodeMotion.java    From JAADAS with GNU General Public License v3.0 4 votes vote down vote up
private Unit getFirstNonIdentityStmt(Body b) {
	for (Unit u : b.getUnits())
		if (!(u instanceof IdentityStmt))
			return u;
	return null;
}
 
Example #23
Source File: UnitThrowAnalysis.java    From JAADAS with GNU General Public License v3.0 4 votes vote down vote up
@Override
public void caseIdentityStmt(IdentityStmt s) {}
 
Example #24
Source File: JimpleStmtVisitorImpl.java    From FuzzDroid with Apache License 2.0 4 votes vote down vote up
@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));
	}
	
}
 
Example #25
Source File: BackwardValueAnalysis.java    From DroidRA with GNU Lesser General Public License v2.1 4 votes vote down vote up
/**
 * Returns all assignments for a local variable. This walks the interprocedural control flow graph
 * back from a statement looking for all assignments to a given local variable.
 * 
 * @param start The statement where the analysis should start.
 * @param local The local variable whose assignments should be found.
 * @param init A boolean that indicates whether the analysis should be initialized. This should
 *          always be true for non-recursive calls.
 * @param visitedUnits The set of statements visited by the analysis.
 * @return The set of assignment statements for the local variable.
 */
protected List<DefinitionStmt> findAssignmentsForLocal(Unit start, Local local, boolean init,
    Set<Pair<Unit, Local>> visitedUnits) {
  if (logger.isDebugEnabled()) {
    logger.debug("Finding assignments for local " + local);
  }
  SootMethod method = AnalysisParameters.v().getIcfg().getMethodOf(start);
  ExceptionalUnitGraph graph = new ExceptionalUnitGraph(method.getActiveBody());
  List<DefinitionStmt> result = new ArrayList<DefinitionStmt>();

  Stack<Unit> stack = new Stack<Unit>();
  stack.push(start);
  if (init) {
    visitedUnits.clear();
  }

  while (!stack.empty()) {
    Unit current = stack.pop();
    if (logger.isDebugEnabled()) {
      logger.debug(current + " " + current.getClass());
    }
    Pair<Unit, Local> pair = new Pair<Unit, Local>(current, local);
    if (visitedUnits.contains(pair)) {
      continue;
    }
    visitedUnits.add(pair);
    if (current instanceof IdentityStmt) {
      IdentityStmt identityStmt = (IdentityStmt) current;
      // method.
      if (identityStmt.getLeftOp().equivTo(local)) {
        result.add(identityStmt);
      }
    } else if (current instanceof AssignStmt) {
      AssignStmt assignStmt = (AssignStmt) current;
      if (assignStmt.getLeftOp().equivTo(local)) {
        if (assignStmt.getRightOp() instanceof Local) {
          result.addAll(findAssignmentsForLocal(current, (Local) assignStmt.getRightOp(), false,
              visitedUnits));
        } else {
          result.add(assignStmt);
        }
        // The assignment generates the local on that path.
        // Anything before is irrelevant.
        continue;
      }
    }
    for (Unit pred : graph.getPredsOf(current)) {
      stack.push(pred);
    }
  }

  return result;
}
 
Example #26
Source File: SharedPreferencesUpdater.java    From soot-infoflow-android-iccta with GNU Lesser General Public License v2.1 4 votes vote down vote up
public void forward(Map<Stmt, SootMethod> stmtMapping, SootMethod sootMethod, int argsIndex)
{	
	Body body = sootMethod.retrieveActiveBody();
	PatchingChain<Unit> units = body.getUnits();
	
	int index = -1;
	if (sootMethod.isStatic())
	{
		//No this statement
		index++;
	}
	
	Value value = null;
	
	for (Iterator<Unit> unitIter = units.snapshotIterator(); unitIter.hasNext(); )
	{
		Stmt stmt = (Stmt) unitIter.next();
		
		if (index < argsIndex)
		{
			index++;
		}
		else if (index == argsIndex)
		{
			if (stmt instanceof IdentityStmt)
			{
				value = stmt.getDefBoxes().get(0).getValue();
			}
			else
			{
				throw new RuntimeException("Wrong argsIndex (" + argsIndex + ") number for IdentityStmt");
			}
			
			index++;
		}
		else
		{
			List<ValueBox> valueBoxes = stmt.getUseBoxes();
			for (ValueBox vb : valueBoxes)
			{
				if (value.equals(vb.getValue()))
				{
					stmtMapping.put(stmt, sootMethod);
					
					int newArgsIndex = getArgsIndex(stmt, value);
					if (-1 != newArgsIndex)
					{
						forward(stmtMapping, stmt.getInvokeExpr().getMethod(), newArgsIndex);
					}
				}
			}
		}
		
	}
}
 
Example #27
Source File: DynamicValueTransformer.java    From FuzzDroid with Apache License 2.0 4 votes vote down vote up
@Override
protected void internalTransform(Body b, String phaseName,
		Map<String, String> options) {
	// Do not instrument methods in framework classes
	if (!canInstrumentMethod(b.getMethod()))
		return;
	
	// Iterate over all statements. For each definition statement that
	// defines a string, report the string to the server.
	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;			
		
		if (instrumentOnlyComparisons) {
			// Is this a comparison?
			Stmt curStmt = (Stmt) curUnit;
			if (!curStmt.containsInvokeExpr())
				continue;
			InvokeExpr invExpr = curStmt.getInvokeExpr();
			if (comparisonSignatures.contains(invExpr.getMethod().getSignature())) {					
				if (invExpr instanceof InstanceInvokeExpr)
					checkAndReport(b, curStmt, ((InstanceInvokeExpr) invExpr).getBase(), -1);
				for (int i = 0; i < invExpr.getArgCount(); i++)
					checkAndReport(b, curStmt, invExpr.getArg(i), i);
			}
			
			// Do not look for anything else
			continue;
		}
		
		// We only care about statements that define strings
		if (!(curUnit instanceof AssignStmt))
			continue;
		AssignStmt assignStmt = (AssignStmt) curUnit;
		checkAndReport(b, assignStmt, assignStmt.getLeftOp(), -1);
	}

}
 
Example #28
Source File: ICCInstrumentDestination.java    From soot-infoflow-android-iccta with GNU Lesser General Public License v2.1 4 votes vote down vote up
public void instrumentDummyMainMethod(SootClass compSootClass, SootField intentSootField)
{
	SootMethod mainMethod = compSootClass.getMethodByName(ICCDummyMainCreator.DUMMY_MAIN_METHOD);
	if (null == mainMethod)
	{
		mainMethod = generateDummyMainMethod(compSootClass.getName());
	}
	
	Body body = mainMethod.getActiveBody();
	
	//For the purpose of confusion dex optimization (because of the strategy of generating dummyMain method)
	boolean firstStmt = true;
	
	PatchingChain<Unit> units = body.getUnits();
	for (Iterator<Unit> iter = units.snapshotIterator(); iter.hasNext(); )
	{
		Stmt stmt = (Stmt) iter.next();
		
		if (stmt instanceof IdentityStmt)
		{
			continue;
		}
		   		
		if (firstStmt)
		{
			firstStmt = false;
			AssignStmt aStmt = (AssignStmt) stmt;
			SootMethod fuzzyMe = generateFuzzyMethod(compSootClass);
			InvokeExpr invokeExpr = Jimple.v().newVirtualInvokeExpr(body.getThisLocal(), fuzzyMe.makeRef());
			Unit assignU = Jimple.v().newAssignStmt(aStmt.getLeftOp(), invokeExpr);
			units.insertAfter(assignU, aStmt);
		}
		
		if (! stmt.containsInvokeExpr())
		{
			continue;
		}
		
		if (stmt.toString().contains("<init>"))
		{
			continue;
		}
			
		List<Value> argValues = stmt.getInvokeExpr().getArgs();	
		/*
		for (Value value : argValues)
		{
			Type type = value.getType();
			if (type.equals(INTENT_TYPE))
			{
				Unit setIntentU = Jimple.v().newAssignStmt(     
						value,
	                    Jimple.v().newStaticFieldRef(intentSootField.makeRef()));
				
	    		units.insertBefore(setIntentU, stmt);
			}
		}*/
		
		//Using another way to transfer Intent
		for (int i = 0; i < argValues.size(); i++)
		{
			Value value = argValues.get(i);
			Type type = value.getType();
			if (type.equals(INTENT_TYPE))
			{
				assignIntent(compSootClass, stmt.getInvokeExpr().getMethod(), i+1);
			}
		}
	}
}
 
Example #29
Source File: ICCInstrumentDestination.java    From soot-infoflow-android-iccta with GNU Lesser General Public License v2.1 4 votes vote down vote up
public void assignIntent(SootClass hostComponent, SootMethod method, int indexOfArgs)
  {
  	Body body = method.getActiveBody();

  	PatchingChain<Unit> units = body.getUnits();
  	Chain<Local> locals = body.getLocals();
  	Value intentV = null;
int identityStmtIndex = 0;

  	for (Iterator<Unit> iter = units.snapshotIterator(); iter.hasNext(); )
  	{
  		Stmt stmt = (Stmt) iter.next();
	if (! method.isStatic())
	{
   		if (stmt instanceof IdentityStmt)
   		{			
   			if (identityStmtIndex == indexOfArgs)
   			{
   				intentV = ((IdentityStmt) stmt).getLeftOp();
   			}
   			
   			identityStmtIndex++;
   		}
   		else
   		{
   	 		Local thisLocal = locals.getFirst();
   			
   	 		/*
   			Unit setIntentU = Jimple.v().newAssignStmt(     
   					intentV,
   					Jimple.v().newVirtualInvokeExpr(thisLocal, method.getDeclaringClass().getMethodByName("getIntent").makeRef()));
			*/
   	 		
   	 		/* Using the component that the dummyMain() belongs to, as in some cases the invoked method is only available in its superclass.
   	 		 * and its superclass does not contain getIntent() and consequently cause an runtime exception of couldn't find getIntent(). 
   	 		 * 
   	 		 * RuntimeException: couldn't find method getIntent(*) in com.google.android.gcm.GCMBroadcastReceiver
   	 		*/
   	 		Unit setIntentU = Jimple.v().newAssignStmt(     
   					intentV,
   					Jimple.v().newVirtualInvokeExpr(thisLocal, hostComponent.getMethodByName("getIntent").makeRef()));
   	 		
    		units.insertBefore(setIntentU, stmt);
    		
    		System.out.println(body);
    		
    		return;
   		}
	}
	
  		
  	}
  }
 
Example #30
Source File: PolicyEnforcementPoint.java    From DroidForce with GNU Lesser General Public License v2.1 4 votes vote down vote up
private boolean isSourceInfoParameter(ResultSourceInfo sInfo) {
	return sInfo.getSource() instanceof IdentityStmt
			&& ((IdentityStmt) sInfo.getSource()).getRightOp() instanceof ParameterRef;
}