Java Code Examples for soot.util.Chain#iterator()

The following examples show how to use soot.util.Chain#iterator() . 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: BodyBuilder.java    From JAADAS with GNU General Public License v3.0 5 votes vote down vote up
public static boolean isExceptionCaughtAt(Chain<Unit> units, Unit u, Iterator<Trap> trapsIt)
{
  while (trapsIt.hasNext())
  {
    Trap t = trapsIt.next();
    Iterator<Unit> it = units.iterator(t.getBeginUnit(),units.getPredOf(t.getEndUnit()));
    while (it.hasNext())
      if (u.equals(it.next()))
        return true;
  }
  
  return false;
}
 
Example 2
Source File: IndirectIfJumpsToCaughtGotos.java    From JAADAS with GNU General Public License v3.0 5 votes vote down vote up
private Unit findNonTrappedUnit(PatchingChain<Unit> units, Chain<Trap> traps) {
  int intrap = 0;
  ArrayList<Unit> untrapped = new ArrayList<Unit>();
  Iterator<Unit> it = units.snapshotIterator();
  while (it.hasNext()) {
    Unit u = it.next();
    Iterator<Trap> tit = traps.iterator();
    while (tit.hasNext()) {
      Trap t = tit.next();
      if (u == t.getBeginUnit()) intrap++;
      if (u == t.getEndUnit()) intrap--;
    }
    
    if (intrap == 0) untrapped.add(u);
  }
  
  Unit result = null;
  if (untrapped.size() > 0) {
    int count = 0;
    while (result == null && count <10) {
      count++;
      result = untrapped.get(Rand.getInt(999999) % untrapped.size());
      if (!result.fallsThrough() || units.getSuccOf(result) == null || units.getSuccOf(result) instanceof ThrowInst) 
        result = null;
    }
  }
  
  return result;
}
 
Example 3
Source File: StackTypeHeightCalculator.java    From JAADAS with GNU General Public License v3.0 5 votes vote down vote up
private static RefType isHandlerUnit(Chain<Trap> traps, Unit h) {
  Iterator<Trap> it = traps.iterator();
  while (it.hasNext()) {
    Trap t = (Trap)it.next();
    if (t.getHandlerUnit() == h)
      return t.getException().getType();
  }
  return null;
}
 
Example 4
Source File: SootUtil.java    From JAADAS with GNU General Public License v3.0 5 votes vote down vote up
public static boolean hasRecursiveField(SootClass sootClass) {
  Chain fields = sootClass.getFields();
  for (Iterator iter = fields.iterator(); iter.hasNext();) {
    SootField sootField = (SootField) iter.next();
    Type type = sootField.getType();
    if (type instanceof RefType) {
      RefType refType = (RefType) type;
      SootClass sootClass2 = refType.getSootClass();
      if (sootClass == sootClass2) {
        return true;
      }
    }
  }
  return false;
}
 
Example 5
Source File: GraphComparer.java    From JAADAS with GNU General Public License v3.0 5 votes vote down vote up
/**
 * A utility method for determining if a {@link Unit} is among
 * those protected by a particular {@link Trap}..
 *
 * @param unit the {@link Unit} being asked about.
 *
 * @param trap the {@link Trap} being asked about.
 *
 * @return <tt>true</tt> if <tt>unit</tt> is protected by
 * <tt>trap</tt>, false otherwise.
 */
protected boolean amongTrappedUnits(Unit unit, Trap trap) {
    Chain units = exceptional.getBody().getUnits();
    for (Iterator it = units.iterator(trap.getBeginUnit(),
				      units.getPredOf(trap.getEndUnit()));
	 it.hasNext(); ) {
	Unit u = (Unit) it.next();
	if (u == unit) {
	    return true;
	}
    }
    return false;
}
 
Example 6
Source File: InterProceduralAnalyses.java    From JAADAS with GNU General Public License v3.0 4 votes vote down vote up
public static void applyInterProceduralAnalyses(){
	Chain classes = Scene.v().getApplicationClasses();
	
	if(DEBUG)
		System.out.println("\n\nInvoking redundantFielduseEliminator");
	ConstantFieldValueFinder finder = new ConstantFieldValueFinder(classes);
	
	HashMap<String, Object> constantValueFields = finder.getFieldsWithConstantValues();
	if(DEBUG)		
		finder.printConstantValueFields();
	
	/*
	 * The code above this gathers interprocedural information
	 * the code below this USES the interprocedural results
	 */		
	Iterator it = classes.iterator();
	while(it.hasNext()){
		//go though all the methods
		SootClass s = (SootClass)it.next();
		Iterator methodIt = s.methodIterator();
		while (methodIt.hasNext()) {
			SootMethod m = (SootMethod) methodIt.next();
			/*
			 * Adding try block to handle RuntimeException no active body found
			 */
			DavaBody body = null;
			if(m.hasActiveBody()){
				body = (DavaBody)m.getActiveBody();
			}
			else{
				continue;
			}
			ASTNode AST = (ASTNode) body.getUnits().getFirst();

			if(! (AST instanceof ASTMethodNode))
				continue;
			
			Map options = PhaseOptions.v().getPhaseOptions("db.deobfuscate");
	        boolean deobfuscate = PhaseOptions.getBoolean(options, "enabled");
	        //System.out.println("force is "+force);
	        if(deobfuscate){
	        	if(DEBUG)
	        		System.out.println("\nSTART CP Class:"+s.getName()+ " Method: "+m.getName());
	        	CPApplication CPApp = new CPApplication((ASTMethodNode)AST , constantValueFields, finder.getClassNameFieldNameToSootFieldMapping());
	        	AST.apply(CPApp);
			
	        	if(DEBUG)
	        		System.out.println("DONE CP for "+m.getName());
	        }
	        
	        //expression simplification
	        //SimplifyExpressions.DEBUG=true;
	        AST.apply(new SimplifyExpressions());
	        
	        
	        //SimplifyConditions.DEBUG=true;
	        AST.apply(new SimplifyConditions());
	        
	        // condition elimination      
	        //EliminateConditions.DEBUG=true;
	        
	        AST.apply(new EliminateConditions((ASTMethodNode)AST));
	        //the above should ALWAYS be followed by an unreachable code eliminator
	        AST.apply(new UnreachableCodeEliminator(AST));
	        
	        //local variable cleanup
	        AST.apply(new LocalVariableCleaner(AST));

	         //VERY EXPENSIVE STAGE of redoing all analyses!!!!
	        if(deobfuscate){
	        	if(DEBUG)System.out.println("reinvoking analyzeAST");
	        	UselessLabelFinder.DEBUG=false;
	        	body.analyzeAST();
	        }
	
	        //renaming should be applied as the last stage
			options = PhaseOptions.v().getPhaseOptions("db.renamer");
	        boolean renamer = PhaseOptions.getBoolean(options, "enabled");
	        //System.out.println("renaming is"+renamer);
	        if(renamer){
	        	applyRenamerAnalyses(AST,body);
	        }

	        //remove returns from void methods
			VoidReturnRemover.cleanClass(s);

		}

	}	
}
 
Example 7
Source File: TrapTightener.java    From JAADAS with GNU General Public License v3.0 4 votes vote down vote up
protected void internalTransform(Body body, String phaseName, Map<String, String> options) {
	if (this.throwAnalysis == null)
		this.throwAnalysis = Scene.v().getDefaultThrowAnalysis();

	if (Options.v().verbose())
		G.v().out.println("[" + body.getMethod().getName() + "] Tightening trap boundaries...");

	Chain<Trap> trapChain = body.getTraps();
	Chain<Unit> unitChain = body.getUnits();
	if (trapChain.size() > 0) {
		ExceptionalUnitGraph graph = new ExceptionalUnitGraph(body, throwAnalysis);
		Set<Unit> unitsWithMonitor = getUnitsWithMonitor(graph);

		for (Iterator<Trap> trapIt = trapChain.iterator(); trapIt.hasNext();) {
			Trap trap = trapIt.next();
			boolean isCatchAll = trap.getException().getName().equals("java.lang.Throwable");
			Unit firstTrappedUnit = trap.getBeginUnit();
			Unit firstTrappedThrower = null;
			Unit firstUntrappedUnit = trap.getEndUnit();
			Unit lastTrappedUnit = unitChain.getPredOf(firstUntrappedUnit);
			Unit lastTrappedThrower = null;
			for (Unit u = firstTrappedUnit; u != null && u != firstUntrappedUnit; u = unitChain.getSuccOf(u)) {
				if (mightThrowTo(graph, u, trap)) {
					firstTrappedThrower = u;
					break;
				}
				
				// If this is the catch-all block and the current unit has an,
				// active monitor, we need to keep the block
				if (isCatchAll && unitsWithMonitor.contains(u))
					break;
			}
			if (firstTrappedThrower != null) {
				for (Unit u = lastTrappedUnit; u != null; u = unitChain.getPredOf(u)) {						
					if (mightThrowTo(graph, u, trap)) {
						lastTrappedThrower = u;
						break;
					}
					
					// If this is the catch-all block and the current unit has an,
					// active monitor, we need to keep the block
					if (isCatchAll && unitsWithMonitor.contains(u))
						break;
				}
			}
			// If no statement inside the trap can throw an exception, we
			// remove the
			// complete trap.
			if (firstTrappedThrower == null)
				trapIt.remove();
			else {
				if (firstTrappedThrower != null && firstTrappedUnit != firstTrappedThrower) {
					trap.setBeginUnit(firstTrappedThrower);
				}
				if (lastTrappedThrower == null) {
					lastTrappedThrower = firstTrappedUnit;
				}
				if (lastTrappedUnit != lastTrappedThrower) {
					trap.setEndUnit(unitChain.getSuccOf(lastTrappedThrower));
				}
			}
		}
	}
}
 
Example 8
Source File: DummyMainGenerator.java    From DroidRA with GNU Lesser General Public License v2.1 4 votes vote down vote up
public SootMethod appendNonComponents(SootMethod mainMethod)
{
	Set<String> coveredMethods = new HashSet<String>();
	
	CallGraph cg = Scene.v().getCallGraph();
	
	for (Iterator<Edge> iter = cg.iterator(); iter.hasNext(); )
	{
		Edge edge = iter.next();
		
		coveredMethods.add(edge.src().getSignature());
		coveredMethods.add(edge.tgt().getSignature());
	}
	
	Chain<SootClass> sootClasses = Scene.v().getApplicationClasses();
	
	for (Iterator<SootClass> iter = sootClasses.iterator(); iter.hasNext();)
	{
		SootClass sc = iter.next();
		
		List<SootMethod> methodList = sc.getMethods();
		for (SootMethod sm : methodList)
		{
			if (sm.getDeclaringClass().getName().startsWith("android.support"))
			{
				continue;
			}
			
			if (sc.isPhantom() || ! sm.isConcrete())
			{
				continue;
			}
			
			if (sm.getName().equals("<init>") || sm.getName().equals("<clinit>"))
			{
				continue;
			}

			
			
			if (coveredMethods.contains(sm.getSignature()))
			{
				//Already covered.
				continue;
			}
			
			mainMethod = addMethod(mainMethod, sm.getSignature());
		}
	}
	
	return mainMethod;
}
 
Example 9
Source File: JimpleIndexNumberTransformer.java    From soot-infoflow-android-iccta with GNU Lesser General Public License v2.1 4 votes vote down vote up
@Override
public void updateJimple() 
{
	Chain<SootClass> sootClasses = Scene.v().getClasses();
	
	for (Iterator<SootClass> iter = sootClasses.iterator(); iter.hasNext(); )
	{
		SootClass sc = iter.next();
		
		//Putting all the code in a try-catch.
		//Just trying the best to put the index number to "JimpleIndexNumberTag" of Stmt.
		try
		{
			List<SootMethod> sms = sc.getMethods();
			
			for (SootMethod sm : sms)
			{
				Body b = sm.retrieveActiveBody();
				
				PatchingChain<Unit> units = b.getUnits();
				
				int indexNumber = 0;
				
				for (Iterator<Unit> iterU = units.snapshotIterator(); iterU.hasNext(); )
				{
					Stmt stmt = (Stmt) iterU.next();
					
					//System.out.println(indexNumber + "->" + stmt);
					
					Tag t = new JimpleIndexNumberTag(indexNumber++);
					stmt.addTag(t);
				}
			}
		}
		catch (Exception ex)
		{
			//System.out.println("Exception in " + sc.getName());
			//ex.printStackTrace();
		}
	}
}
 
Example 10
Source File: BlockGraph.java    From JAADAS with GNU General Public License v3.0 3 votes vote down vote up
/**
 * <p>
 * Utility method for computing the basic block leaders for a {@link Body},
 * given its {@link UnitGraph} (i.e., the instructions which begin new basic
 * blocks).
 * </p>
 *
 * <p>
 * This implementation designates as basic block leaders :
 *
 * <ul>
 *
 * <li>Any <code>Unit</code> which has zero predecessors (e.g. the
 * <code>Unit</code> following a return or unconditional branch) or more
 * than one predecessor (e.g. a merge point).</li>
 *
 * <li><code>Unit</code>s which are the target of any branch (even if they
 * have no other predecessors and the branch has no other successors, which
 * is possible for the targets of unconditional branches or degenerate
 * conditional branches which both branch and fall through to the same
 * <code>Unit</code>).</li>
 *
 * <li>All successors of any <code>Unit</code> which has more than one
 * successor (this includes the successors of <code>Unit</code>s which may
 * throw an exception that gets caught within the <code>Body</code>, as well
 * the successors of conditional branches).</li>
 *
 * <li>The first <code>Unit</code> in any <code>Trap</code> handler.
 * (Strictly speaking, if <code>unitGraph</code> were a
 * <code>ExceptionalUnitGraph</code> that included only a single
 * unexceptional predecessor for some handler&mdash;because no trapped unit
 * could possibly throw the exception that the handler catches, while the
 * code preceding the handler fell through to the handler's code&mdash;then
 * you could merge the handler into the predecessor's basic block; but such
 * situations occur only in carefully contrived bytecode.)
 *
 * </ul>
 * </p>
 *
 * @param unitGraph
 *            is the <code>Unit</code>-level CFG which is to be split into
 *            basic blocks.
 *
 * @return the {@link Set} of {@link Unit}s in <code>unitGraph</code> which
 *         are block leaders.
 */
protected Set<Unit> computeLeaders(UnitGraph unitGraph) {
	Body body = unitGraph.getBody();
	if (body != mBody) {
		throw new RuntimeException(
				"BlockGraph.computeLeaders() called with a UnitGraph that doesn't match its mBody.");
	}
	Set<Unit> leaders = new HashSet<Unit>();

	// Trap handlers start new basic blocks, no matter how many
	// predecessors they have.
	Chain<Trap> traps = body.getTraps();
	for (Iterator<Trap> trapIt = traps.iterator(); trapIt.hasNext();) {
		Trap trap = trapIt.next();
		leaders.add(trap.getHandlerUnit());
	}

	for (Iterator<Unit> unitIt = body.getUnits().iterator(); unitIt.hasNext();) {
		Unit u = unitIt.next();
		List<Unit> predecessors = unitGraph.getPredsOf(u);
		int predCount = predecessors.size();
		List<Unit> successors = unitGraph.getSuccsOf(u);
		int succCount = successors.size();

		if (predCount != 1) { // If predCount == 1 but the predecessor
			leaders.add(u); // is a branch, u will get added by that
		} // branch's successor test.
		if ((succCount > 1) || (u.branches())) {
			for (Iterator<Unit> it = successors.iterator(); it.hasNext();) {
				leaders.add((Unit) it.next()); // The cast is an
			} // assertion check.
		}
	}
	return leaders;
}
 
Example 11
Source File: PatchingChain.java    From JAADAS with GNU General Public License v3.0 votes vote down vote up
protected PatchingIterator (Chain<E> innerChain) { innerIterator = innerChain.iterator(); } 
Example 12
Source File: PatchingChain.java    From JAADAS with GNU General Public License v3.0 votes vote down vote up
protected PatchingIterator (Chain<E> innerChain, E u) { innerIterator = innerChain.iterator(u); } 
Example 13
Source File: PatchingChain.java    From JAADAS with GNU General Public License v3.0 votes vote down vote up
protected PatchingIterator (Chain<E> innerChain, E head, E tail) { innerIterator = innerChain.iterator(head, tail); }