soot.jimple.Jimple Java Examples

The following examples show how to use soot.jimple.Jimple. 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 Project: DroidForce   Author: secure-software-engineering   File: PolicyEnforcementPoint.java    License: GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * 
 * @param parameter
 * @param body
 * @return
 */
private Pair<Value, List<Unit>> generateParameterArray(List<Value> parameter, Body body){
	List<Unit> generated = new ArrayList<Unit>();
	
	NewArrayExpr arrayExpr = Jimple.v().newNewArrayExpr(RefType.v("java.lang.Object"), IntConstant.v(parameter.size()));
	
	Value newArrayLocal = generateFreshLocal(body, getParameterArrayType());
	Unit newAssignStmt = Jimple.v().newAssignStmt(newArrayLocal, arrayExpr);
	generated.add(newAssignStmt);
	
	for(int i = 0; i < parameter.size(); i++){
		Value index = IntConstant.v(i);
		ArrayRef leftSide = Jimple.v().newArrayRef(newArrayLocal, index);
		Value rightSide = generateCorrectObject(body, parameter.get(i), generated);
		
		Unit parameterInArray = Jimple.v().newAssignStmt(leftSide, rightSide);
		generated.add(parameterInArray);
	}
	
	return new Pair<Value, List<Unit>>(newArrayLocal, generated);
}
 
Example #2
Source Project: JAADAS   Author: flankerhqd   File: LibraryClassPatcher.java    License: GNU General Public License v3.0 6 votes vote down vote up
/**
 * Creates a synthetic "<init>(java.lang.Runnable)" method implementation
 * that stores the given runnable into a field for later use
 * @param smCons The <init>() method for which to create a synthetic
 * implementation
 * @param runnable The "java.lang.Runnable" interface
 * @param fldTarget The field receiving the Runnable
 */
private void patchThreadConstructor(SootMethod smCons, SootClass runnable,
		SootField fldTarget) {
	SootClass sc = smCons.getDeclaringClass();
	Body b = Jimple.v().newBody(smCons);
	smCons.setActiveBody(b);
	
	Local thisLocal = Jimple.v().newLocal("this", sc.getType());
	b.getLocals().add(thisLocal);
	b.getUnits().add(Jimple.v().newIdentityStmt(thisLocal,
			Jimple.v().newThisRef(sc.getType())));
	
	Local param0Local = Jimple.v().newLocal("p0", runnable.getType());
	b.getLocals().add(param0Local);
	b.getUnits().add(Jimple.v().newIdentityStmt(param0Local,
			Jimple.v().newParameterRef(runnable.getType(), 0)));
	
	b.getUnits().add(Jimple.v().newAssignStmt(Jimple.v().newInstanceFieldRef(thisLocal,
			fldTarget.makeRef()), param0Local));
	
	b.getUnits().add(Jimple.v().newReturnVoidStmt());
}
 
Example #3
Source Project: JAADAS   Author: flankerhqd   File: ImplicitFlowAliasStrategy.java    License: GNU General Public License v3.0 6 votes vote down vote up
@Override
public void computeAliasTaints(Abstraction d1, Stmt src, Value targetValue,
		Set<Abstraction> taintSet, SootMethod method, Abstraction newAbs) {
	// Use global aliasing
	Value baseValue = ((InstanceFieldRef) targetValue).getBase();
	Set<AccessPath> aliases = methodToAliases.getUnchecked(method).get
			(new AccessPath(baseValue, true));
	if (aliases != null)
		for (AccessPath ap : aliases) {
			Abstraction aliasAbs = newAbs.deriveNewAbstraction(
					ap.merge(newAbs.getAccessPath()), null);
			if (taintSet.add(aliasAbs))
				// We have found a new alias. This new base object may however yet
				// again alias with something, so we need to check again
				if (ap.isInstanceFieldRef()) {
					InstanceFieldRef aliasBaseVal = Jimple.v().newInstanceFieldRef
							(ap.getPlainValue(), ap.getFirstField().makeRef());
					computeAliasTaints(d1, src, aliasBaseVal, taintSet, method, aliasAbs);
				}
		}
}
 
Example #4
public SootMethod generateFuzzyMethod(SootClass sootClass)
{
   	String name = "fuzzyMe";
    List<Type> parameters = new ArrayList<Type>();
    Type returnType = IntType.v();
    int modifiers = Modifier.PUBLIC;
    SootMethod fuzzyMeMethod = new SootMethod(name, parameters, returnType, modifiers);
    sootClass.addMethod(fuzzyMeMethod);
    
    {
    	Body b = Jimple.v().newBody(fuzzyMeMethod);
    	fuzzyMeMethod.setActiveBody(b);
    	LocalGenerator lg = new LocalGenerator(b);
        Local thisLocal = lg.generateLocal(sootClass.getType());
        Unit thisU = Jimple.v().newIdentityStmt(thisLocal, 
                Jimple.v().newThisRef(sootClass.getType()));
        Unit returnU = Jimple.v().newReturnStmt(IntConstant.v(1));
        b.getUnits().add(thisU);
        b.getUnits().add(returnU);
    }
        
    return fuzzyMeMethod;
}
 
Example #5
Source Project: JAADAS   Author: flankerhqd   File: BaseEntryPointCreator.java    License: GNU General Public License v3.0 6 votes vote down vote up
/**
 * Constructs an array of the given type with a single element of this type
 * in the given method
 * @param body The body of the method in which to create the array
 * @param gen The local generator
 * @param tp The type of which to create the array
 * @param constructionStack Set of classes currently being built to avoid
 * constructor loops
 * @param parentClasses If a requested type is compatible with one of the
 * types in this list, the already-created object is used instead of
 * creating a new one.
 * @return The local referencing the newly created array, or null if the
 * array generation failed
 */
private Value buildArrayOfType(Body body, LocalGenerator gen, ArrayType tp,
		Set<SootClass> constructionStack, Set<SootClass> parentClasses) {
	Local local = gen.generateLocal(tp);

	// Generate a new single-element array
	NewArrayExpr newArrayExpr = Jimple.v().newNewArrayExpr(tp.getElementType(),
			IntConstant.v(1));
	AssignStmt assignArray = Jimple.v().newAssignStmt(local, newArrayExpr);
	body.getUnits().add(assignArray);
	
	// Generate a single element in the array
	AssignStmt assign = Jimple.v().newAssignStmt
			(Jimple.v().newArrayRef(local, IntConstant.v(0)),
			getValueForType(body, gen, tp.getElementType(), constructionStack, parentClasses));
	body.getUnits().add(assign);
	return local;
}
 
Example #6
Source Project: JAADAS   Author: flankerhqd   File: BDynamicInvokeInst.java    License: GNU General Public License v3.0 6 votes vote down vote up
public String toString()
{
    StringBuffer buffer = new StringBuffer();

    buffer.append(Jimple.DYNAMICINVOKE);
    buffer.append(" \"");
    buffer.append(methodRef.name()); //quoted method name (can be any UTF8 string)
    buffer.append("\" <");
    buffer.append(SootMethod.getSubSignature(""/* no method name here*/, methodRef.parameterTypes(), methodRef.returnType()));
    buffer.append(">");
    buffer.append(bsmRef.getSignature());
    buffer.append("(");
    for(int i = 0; i < bsmArgs.size(); i++)
    {
        if(i != 0)
            buffer.append(", ");

        buffer.append(bsmArgs.get(i).toString());
    }
    buffer.append(")");

    return buffer.toString();
}
 
Example #7
Source Project: JAADAS   Author: flankerhqd   File: BDynamicInvokeInst.java    License: GNU General Public License v3.0 6 votes vote down vote up
public void toString(UnitPrinter up)
{
    up.literal(Jimple.DYNAMICINVOKE);        
    up.literal(" \"" + methodRef.name() + "\" <" + SootMethod.getSubSignature(""/* no method name here*/, methodRef.parameterTypes(), methodRef.returnType()) +"> ");        
    up.methodRef(bsmRef);
    up.literal("(");
    
    for(int i = 0; i < bsmArgs.size(); i++)
    {
        if(i != 0)
            up.literal(", ");
            
        bsmArgs.get(i).toString(up);
    }

    up.literal(")");
}
 
Example #8
Source Project: JAADAS   Author: flankerhqd   File: CastInstruction.java    License: GNU General Public License v3.0 6 votes vote down vote up
public void jimplify (DexBody body) {
     TwoRegisterInstruction i = (TwoRegisterInstruction)instruction;
     int dest = i.getRegisterA();
     int source = i.getRegisterB();
     Type targetType = getTargetType();
     CastExpr cast = Jimple.v().newCastExpr(body.getRegisterLocal(source), targetType);
     assign = Jimple.v().newAssignStmt(body.getRegisterLocal(dest), cast);
     assign.addTag (getTag());
     setUnit(assign);
     addTags(assign);
     body.add(assign);
     
     if (IDalvikTyper.ENABLE_DVKTYPER) {
Debug.printDbg(IDalvikTyper.DEBUG, "constraint cast: "+ assign +" castexpr type: "+ cast.getType()+" cast type: "+ cast.getCastType());
       int op = (int)instruction.getOpcode().value;
       DalvikTyper.v().setType(assign.getLeftOpBox(), cast.getType(), false);
       //DalvikTyper.v().captureAssign((JAssignStmt)assign, op);
     }
 }
 
Example #9
Source Project: JAADAS   Author: flankerhqd   File: UnopInstruction.java    License: GNU General Public License v3.0 6 votes vote down vote up
/**
 * Return the appropriate Jimple Expression according to the OpCode
 */
private Value getExpression(Local source) {
    Opcode opcode = instruction.getOpcode();
    switch(opcode) {
    case NEG_INT:
    case NEG_LONG:
    case NEG_FLOAT:
    case NEG_DOUBLE:
        return Jimple.v().newNegExpr(source);
    case NOT_LONG:
        return getNotLongExpr(source);
    case NOT_INT:
        return getNotIntExpr(source);
    default:
        throw new RuntimeException("Invalid Opcode: " + opcode);
    }

}
 
Example #10
Source Project: DroidRA   Author: serval-snt-uni-lu   File: DummyMainGenerator.java    License: 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 #11
Source Project: JAADAS   Author: flankerhqd   File: Walker.java    License: GNU General Public License v3.0 6 votes vote down vote up
public void outACaseStmt(ACaseStmt node)
   {        
String labelName = (String) mProductions.removeLast();
       UnitBox box = Jimple.v().newStmtBox(null);

       addBoxToPatch(labelName, box);
       
       Value labelValue = null;
       if(node.getCaseLabel() instanceof AConstantCaseLabel)
    labelValue = (Value) mProductions.removeLast();

       // if labelValue == null, this is the default label.
       if(labelValue == null)
    mProductions.addLast(box);
       else {            
           Object[] valueTargetPair = new Object[2];
           valueTargetPair[0] = labelValue;
           valueTargetPair[1] = box;
    mProductions.addLast(valueTargetPair);
       }        
   }
 
Example #12
Source Project: JAADAS   Author: flankerhqd   File: IfTestInstruction.java    License: GNU General Public License v3.0 6 votes vote down vote up
protected IfStmt ifStatement(DexBody body) {
      Instruction22t i = (Instruction22t) instruction;
      Local one = body.getRegisterLocal(i.getRegisterA());
      Local other = body.getRegisterLocal(i.getRegisterB());
      BinopExpr condition = getComparisonExpr(one, other);
      jif = (JIfStmt)Jimple.v().newIfStmt(condition, targetInstruction.getUnit());
      // setUnit() is called in ConditionalJumpInstruction

if (IDalvikTyper.ENABLE_DVKTYPER) {
    Debug.printDbg(IDalvikTyper.DEBUG, "constraint if: "+ jif +" condition: "+ condition);
    DalvikTyper.v().addConstraint(condition.getOp1Box(), condition.getOp2Box());
      }
      
      
      return jif;
      
  }
 
Example #13
Source Project: JAADAS   Author: flankerhqd   File: AsmMethodSource.java    License: GNU General Public License v3.0 6 votes vote down vote up
private void convertArrayStoreInsn(InsnNode insn) {
	int op = insn.getOpcode();
	boolean dword = op == LASTORE || op == DASTORE;
	StackFrame frame = getFrame(insn);
	if (!units.containsKey(insn)) {
		Operand valu = dword ? popImmediateDual() : popImmediate();
		Operand indx = popImmediate();
		Operand base = popLocal();
		ArrayRef ar = Jimple.v().newArrayRef(
				base.stackOrValue(), indx.stackOrValue());
		indx.addBox(ar.getIndexBox());
		base.addBox(ar.getBaseBox());
		AssignStmt as = Jimple.v().newAssignStmt(ar, valu.stackOrValue());
		valu.addBox(as.getRightOpBox());
		frame.in(valu, indx, base);
		frame.boxes(as.getRightOpBox(),
				ar.getIndexBox(), ar.getBaseBox());
		setUnit(insn, as);
	} else {
		frame.mergeIn(dword ? popDual() : pop(), pop(), pop());
	}
}
 
Example #14
Source Project: JAADAS   Author: flankerhqd   File: InstanceOfInstruction.java    License: GNU General Public License v3.0 6 votes vote down vote up
public void jimplify (DexBody body) {
      Instruction22c i = (Instruction22c)instruction;
      int dest = i.getRegisterA();
      int source = i.getRegisterB();

      Type t = DexType.toSoot((TypeReference)(i.getReference()));

      InstanceOfExpr e = Jimple.v().newInstanceOfExpr(body.getRegisterLocal(source), t);
      assign = Jimple.v().newAssignStmt(body.getRegisterLocal(dest), e);
      setUnit(assign);
      addTags(assign);
      body.add(assign);

if (IDalvikTyper.ENABLE_DVKTYPER) {
	Debug.printDbg(IDalvikTyper.DEBUG, "constraint: "+ assign);
        int op = (int)instruction.getOpcode().value;
        //DalvikTyper.v().?
      }
  }
 
Example #15
Source Project: JAADAS   Author: flankerhqd   File: UnitThrowAnalysisTest.java    License: GNU General Public License v3.0 6 votes vote down vote up
@Test
public void testJEnterMonitorStmt() {
    Stmt s = Jimple.v().newEnterMonitorStmt(StringConstant.v("test"));

    Set expectedRep = new ExceptionHashSet(utility.VM_ERRORS);
    Set expectedCatch = new ExceptionHashSet(utility.VM_ERRORS_PLUS_SUPERTYPES);
    expectedRep.add(utility.NULL_POINTER_EXCEPTION);
    assertTrue(ExceptionTestUtility.sameMembers(expectedRep, Collections.EMPTY_SET,
                unitAnalysis.mightThrow(s)));

    expectedCatch.add(utility.NULL_POINTER_EXCEPTION);
    expectedCatch.add(utility.RUNTIME_EXCEPTION);
    expectedCatch.add(utility.EXCEPTION);
    assertEquals(expectedCatch,
            utility.catchableSubset(unitAnalysis.mightThrow(s)));
}
 
Example #16
Source Project: JAADAS   Author: flankerhqd   File: UnitThrowAnalysisTest.java    License: GNU General Public License v3.0 6 votes vote down vote up
@Ignore("Fails")
@Test
public void testJReturnVoidStmt() {
    Stmt s = Jimple.v().newReturnVoidStmt();

    Set expectedRep = new ExceptionHashSet(utility.VM_ERRORS);
    expectedRep.add(utility.ILLEGAL_MONITOR_STATE_EXCEPTION);
    assertTrue(ExceptionTestUtility.sameMembers(expectedRep, Collections.EMPTY_SET,
                unitAnalysis.mightThrow(s)));

    Set expectedCatch = new ExceptionHashSet(utility.VM_ERRORS_PLUS_SUPERTYPES);
    expectedCatch.add(utility.ILLEGAL_MONITOR_STATE_EXCEPTION);
    expectedCatch.add(utility.RUNTIME_EXCEPTION);
    expectedCatch.add(utility.EXCEPTION);
    assertEquals(expectedCatch, 
            utility.catchableSubset(unitAnalysis.mightThrow(s)));
}
 
Example #17
Source Project: JAADAS   Author: flankerhqd   File: MoveResultInstruction.java    License: GNU General Public License v3.0 6 votes vote down vote up
public void jimplify (DexBody body) {
//        if (local != null && expr != null)
//            throw new RuntimeException("Both local and expr are set to move.");

        int dest = ((OneRegisterInstruction)instruction).getRegisterA();

//        if (local != null)
//            assign = Jimple.v().newAssignStmt(body.getRegisterLocal(dest), local);
//        else if (expr != null)
//            assign = Jimple.v().newAssignStmt(body.getRegisterLocal(dest), expr);
//        else
//            throw new RuntimeException("Neither local and expr are set to move.");
        assign = Jimple.v().newAssignStmt(body.getRegisterLocal(dest), body.getStoreResultLocal());
        setUnit(assign);
        addTags(assign);
        if (tag != null)
            assign.addTag(tag);
        body.add(assign);
        
		if (IDalvikTyper.ENABLE_DVKTYPER) {
			Debug.printDbg(IDalvikTyper.DEBUG, "constraint: "+ assign);
          int op = (int)instruction.getOpcode().value;
          JAssignStmt jassign = (JAssignStmt)assign;
          DalvikTyper.v().addConstraint(assign.getLeftOpBox(), assign.getRightOpBox());
        }
    }
 
Example #18
Source Project: JAADAS   Author: flankerhqd   File: UnopInstruction.java    License: GNU General Public License v3.0 6 votes vote down vote up
public void jimplify (DexBody body) {
      if(!(instruction instanceof Instruction12x))
          throw new IllegalArgumentException("Expected Instruction12x but got: "+instruction.getClass());

      Instruction12x cmpInstr = (Instruction12x)instruction;
      int dest = cmpInstr.getRegisterA();

      Local source = body.getRegisterLocal(cmpInstr.getRegisterB());
      Value expr = getExpression(source);

      assign = Jimple.v().newAssignStmt(body.getRegisterLocal(dest), expr);

      setUnit(assign);
      addTags(assign);
      body.add(assign);
      
if (IDalvikTyper.ENABLE_DVKTYPER) {
	Debug.printDbg(IDalvikTyper.DEBUG, "constraint: "+ assign);
        int op = (int)instruction.getOpcode().value;
        //DalvikTyper.v().captureAssign((JAssignStmt)assign, op);
        JAssignStmt jass = (JAssignStmt)assign;
        DalvikTyper.v().setType((expr instanceof JCastExpr) ? ((JCastExpr) expr).getOpBox() : ((UnopExpr) expr).getOpBox(), opUnType[op - 0x7b], true);
        DalvikTyper.v().setType(jass.leftBox, resUnType[op - 0x7b], false);
      }
  }
 
Example #19
Source Project: JAADAS   Author: flankerhqd   File: AsmMethodSource.java    License: GNU General Public License v3.0 6 votes vote down vote up
private void convertTableSwitchInsn(TableSwitchInsnNode insn) {
	StackFrame frame = getFrame(insn);
	if (units.containsKey(insn)) {
		frame.mergeIn(pop());
		return;
	}
	Operand key = popImmediate();
	UnitBox dflt = Jimple.v().newStmtBox(null);
	List<UnitBox> targets = new ArrayList<UnitBox>(insn.labels.size());
	labels.put(insn.dflt, dflt);
	for (LabelNode ln : insn.labels) {
		UnitBox box = Jimple.v().newStmtBox(null);
		targets.add(box);
		labels.put(ln, box);
	}
	TableSwitchStmt tss = Jimple.v().newTableSwitchStmt(key.stackOrValue(),
			insn.min, insn.max, targets, dflt);
	key.addBox(tss.getKeyBox());
	frame.in(key);
	frame.boxes(tss.getKeyBox());
	setUnit(insn, tss);
}
 
Example #20
Source Project: JAADAS   Author: flankerhqd   File: JDynamicInvokeExpr.java    License: GNU General Public License v3.0 6 votes vote down vote up
public JDynamicInvokeExpr(SootMethodRef bootstrapMethodRef, List<? extends Value> bootstrapArgs, SootMethodRef methodRef, int tag, List<? extends Value> methodArgs)
  {
  	super(methodRef, new ValueBox[methodArgs.size()]);
  	
if(!methodRef.getSignature().startsWith("<"+SootClass.INVOKEDYNAMIC_DUMMY_CLASS_NAME+": "))
  		throw new IllegalArgumentException("Receiver type of JDynamicInvokeExpr must be "+SootClass.INVOKEDYNAMIC_DUMMY_CLASS_NAME+"!");
if(!bootstrapMethodRef.returnType().equals(RefType.v("java.lang.invoke.CallSite"))) {
  		throw new IllegalArgumentException("Return type of bootstrap method must be java.lang.invoke.CallSite!");
}


  	this.bsmRef = bootstrapMethodRef;
      this.bsmArgBoxes = new ValueBox[bootstrapArgs.size()];
      this.tag = tag;

      for(int i = 0; i < bootstrapArgs.size(); i++)
      {
      	this.bsmArgBoxes[i] = Jimple.v().newImmediateBox(bootstrapArgs.get(i));	
      }
      for(int i = 0; i < methodArgs.size(); i++)
      {
      	this.argBoxes[i] = Jimple.v().newImmediateBox( methodArgs.get(i));	
      }
  }
 
Example #21
Source Project: DroidRA   Author: serval-snt-uni-lu   File: DummyMainGenerator.java    License: GNU Lesser General Public License v2.1 6 votes vote down vote up
public SootMethod generateFuzzyMethod(SootClass sootClass)
{
   	String name = "fuzzyMe";
    List<Type> parameters = new ArrayList<Type>();
    Type returnType = IntType.v();
    int modifiers = Modifier.PUBLIC;
    SootMethod fuzzyMeMethod = new SootMethod(name, parameters, returnType, modifiers);
    sootClass.addMethod(fuzzyMeMethod);
    
    {
    	Body b = Jimple.v().newBody(fuzzyMeMethod);
    	fuzzyMeMethod.setActiveBody(b);
    	LocalGenerator lg = new LocalGenerator(b);
        Local thisLocal = lg.generateLocal(sootClass.getType());
        Unit thisU = Jimple.v().newIdentityStmt(thisLocal, 
                Jimple.v().newThisRef(sootClass.getType()));
        Unit returnU = Jimple.v().newReturnStmt(IntConstant.v(1));
        b.getUnits().add(thisU);
        b.getUnits().add(returnU);
    }
        
    return fuzzyMeMethod;
}
 
Example #22
Source Project: JAADAS   Author: flankerhqd   File: UnitThrowAnalysisTest.java    License: GNU General Public License v3.0 5 votes vote down vote up
@Test
public void testJLookupSwitchStmt() {
    Stmt target = Jimple.v().newAssignStmt(Jimple.v().newLocal("local0",
                IntType.v()),
            IntConstant.v(0));
    Stmt s = Jimple.v().newLookupSwitchStmt(IntConstant.v(1),
            Collections.singletonList(IntConstant.v(1)),
            Collections.singletonList(target),
            target);
    assertTrue(ExceptionTestUtility.sameMembers(utility.VM_ERRORS, Collections.EMPTY_SET,
                unitAnalysis.mightThrow(s)));
    assertEquals(utility.VM_ERRORS_PLUS_SUPERTYPES, 
            utility.catchableSubset(unitAnalysis.mightThrow(s)));
}
 
Example #23
Source Project: JAADAS   Author: flankerhqd   File: UnitThrowAnalysisTest.java    License: GNU General Public License v3.0 5 votes vote down vote up
@Test
public void testJIdentityStmt() {

    Stmt s = Jimple.v().newIdentityStmt(Grimp.v().newLocal("local0", 
                IntType.v()),
            Jimple.v().newCaughtExceptionRef());
    assertTrue(ExceptionTestUtility.sameMembers(utility.VM_ERRORS, Collections.EMPTY_SET,
                unitAnalysis.mightThrow(s)));
    assertEquals(utility.VM_ERRORS_PLUS_SUPERTYPES, 
            utility.catchableSubset(unitAnalysis.mightThrow(s)));

    s = Jimple.v().newIdentityStmt(Grimp.v().newLocal("local0",
                RefType.v("java.lang.NullPointerException")),
            Jimple.v().newThisRef(RefType.v("java.lang.NullPointerException")));
    assertTrue(ExceptionTestUtility.sameMembers(utility.VM_ERRORS, Collections.EMPTY_SET,
                unitAnalysis.mightThrow(s)));
    assertEquals(utility.VM_ERRORS_PLUS_SUPERTYPES, 
            utility.catchableSubset(unitAnalysis.mightThrow(s)));

    s = Jimple.v().newIdentityStmt(Grimp.v().newLocal("local0",
                RefType.v("java.lang.NullPointerException")),
            Jimple.v().newParameterRef(RefType.v("java.lang.NullPointerException"), 
                0));
    assertTrue(ExceptionTestUtility.sameMembers(utility.VM_ERRORS, Collections.EMPTY_SET,
                unitAnalysis.mightThrow(s)));
    assertEquals(utility.VM_ERRORS_PLUS_SUPERTYPES, 
            utility.catchableSubset(unitAnalysis.mightThrow(s)));
}
 
Example #24
Source Project: JAADAS   Author: flankerhqd   File: UnitThrowAnalysisTest.java    License: GNU General Public License v3.0 5 votes vote down vote up
@Test
public void testJGotoStmt() {
    Stmt nop = Jimple.v().newNopStmt();
    Stmt s = Jimple.v().newGotoStmt(nop);
    assertTrue(ExceptionTestUtility.sameMembers(utility.VM_ERRORS, Collections.EMPTY_SET,
                unitAnalysis.mightThrow(s)));
    assertEquals(utility.VM_ERRORS_PLUS_SUPERTYPES, 
            utility.catchableSubset(unitAnalysis.mightThrow(s)));
}
 
Example #25
Source Project: FuzzDroid   Author: srasthofer   File: ClassLoaderTransformer.java    License: 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;
	
	// Check for calls to DexFile.loadClass
	for (Iterator<Unit> unitIt = b.getUnits().snapshotIterator(); unitIt.hasNext(); ) {
		Stmt stmt = (Stmt) unitIt.next();
		if (stmt.hasTag(InstrumentedCodeTag.name))
			continue;
		if (!(stmt instanceof AssignStmt))
			continue;
		AssignStmt assignStmt = (AssignStmt) stmt;
		
		if (stmt.containsInvokeExpr()) {
			InvokeExpr iexpr = stmt.getInvokeExpr();
			if (iexpr.getMethod()  == methodDexFileLoadClass) {
				List<Value> args = new ArrayList<>();
				args.add(((InstanceInvokeExpr) iexpr).getBase());
				args.addAll(iexpr.getArgs());
				InvokeExpr newLoadExpr = Jimple.v().newStaticInvokeExpr(methodOwnLoader.makeRef(), args);
				b.getUnits().swapWith(stmt, Jimple.v().newAssignStmt(assignStmt.getLeftOp(), newLoadExpr));
			}
		}
	}
}
 
Example #26
Source Project: FuzzDroid   Author: srasthofer   File: CodePositionTracking.java    License: 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 #27
Source Project: FuzzDroid   Author: srasthofer   File: GoalReachedTracking.java    License: 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;
	
	// Create method references
	final SootMethodRef targetReachedRef = Scene.v().makeMethodRef(
			Scene.v().getSootClass(UtilInstrumenter.JAVA_CLASS_FOR_CODE_POSITIONS),
			"reportTargetReachedSynchronous",
			Collections.<Type>emptyList(),
			VoidType.v(),
			true);
	
	// Iterate over the method and find calls to the target methods
	for (Iterator<Unit> unitIt = b.getUnits().snapshotIterator(); unitIt.hasNext(); ) {
		Stmt stmt = (Stmt) unitIt.next();
		
		if(targetSignatures.contains(stmt)){
			// Notify the server that the target was reached
			Stmt reachedStmt = Jimple.v().newInvokeStmt(
					Jimple.v().newStaticInvokeExpr(targetReachedRef));
			reachedStmt.addTag(new InstrumentedCodeTag());
			b.getUnits().insertBefore(reachedStmt, stmt);
		}
	}
}
 
Example #28
Source Project: JAADAS   Author: flankerhqd   File: LibraryClassPatcher.java    License: GNU General Public License v3.0 5 votes vote down vote up
/**
 * Creates a synthetic "java.lang.Thread.run()" method implementation that
 * calls the target previously passed in when the constructor was called
 * @param smRun The run() method for which to create a synthetic
 * implementation
 * @param runnable The "java.lang.Runnable" interface
 * @param fldTarget The field containing the target object
 */
private void patchThreadRunMethod(SootMethod smRun, SootClass runnable,
		SootField fldTarget) {
	SootClass sc = smRun.getDeclaringClass();
	Body b = Jimple.v().newBody(smRun);
	smRun.setActiveBody(b);
	
	Local thisLocal = Jimple.v().newLocal("this", sc.getType());
	b.getLocals().add(thisLocal);
	b.getUnits().add(Jimple.v().newIdentityStmt(thisLocal,
			Jimple.v().newThisRef(sc.getType())));
	
	Local targetLocal = Jimple.v().newLocal("target", runnable.getType());
	b.getLocals().add(targetLocal);
	b.getUnits().add(Jimple.v().newAssignStmt(targetLocal,
			Jimple.v().newInstanceFieldRef(thisLocal, fldTarget.makeRef())));
	
	Unit retStmt = Jimple.v().newReturnVoidStmt();
	
	// If (this.target == null) return;
	b.getUnits().add(Jimple.v().newIfStmt(Jimple.v().newEqExpr(targetLocal,
			NullConstant.v()), retStmt));
	
	// Invoke target.run()
	b.getUnits().add(Jimple.v().newInvokeStmt(Jimple.v().newInterfaceInvokeExpr(targetLocal,
			runnable.getMethod("void run()").makeRef())));
	
	b.getUnits().add(retStmt);
}
 
Example #29
Source Project: JAADAS   Author: flankerhqd   File: AsmMethodSource.java    License: GNU General Public License v3.0 5 votes vote down vote up
private Operand popStackConst(Operand o) {
	Value v = o.value;
	Local l = o.stack;
	if (l == null && !(v instanceof Constant)) {
		l = o.stack = newStackLocal();
		setUnit(o.insn, Jimple.v().newAssignStmt(l, v));
		o.updateBoxes();
	}
	return o;
}
 
Example #30
Source Project: DroidRA   Author: serval-snt-uni-lu   File: DefaultInstrumentation.java    License: GNU Lesser General Public License v2.1 5 votes vote down vote up
public void injectedStmtWrapper(Body body, LocalGenerator localGenerator, Stmt stmt, Stmt nextStmt)
{
	Local opaqueLocal = localGenerator.generateLocal(IntType.v());
	Unit assignU = Jimple.v().newAssignStmt(opaqueLocal, Jimple.v().newStaticInvokeExpr(Alteration.v().getTryMethod().makeRef(), IntConstant.v(0)));
	Unit ifU = Jimple.v().newIfStmt(Jimple.v().newEqExpr(IntConstant.v(1), opaqueLocal), nextStmt);

	body.getUnits().insertAfter(ifU, stmt);
	body.getUnits().insertAfter(assignU, stmt);
}