soot.jimple.IntConstant Java Examples

The following examples show how to use soot.jimple.IntConstant. 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: FuzzDroid   Author: srasthofer   File: TimingBombTransformer.java    License: Apache License 2.0 7 votes vote down vote up
private void prepareAlarmManagerSet(Body body, InvokeStmt setStmt, SootMethodRef reportRef) {
	Value oldVal = setStmt.getInvokeExpr().getArg(1);
	
	Local longLocal = UtilInstrumenter.generateFreshLocal(body, LongType.v());
	SootMethod currentTimeMillis = Scene.v().getMethod("<java.lang.System: long currentTimeMillis()>");		
	StaticInvokeExpr timeInvoke = Jimple.v().newStaticInvokeExpr(currentTimeMillis.makeRef());		
	AssignStmt timeInitalize = Jimple.v().newAssignStmt(longLocal, timeInvoke);
	
	AddExpr addTime = Jimple.v().newAddExpr(longLocal, LongConstant.v(2000L));
	AssignStmt timeAssign = Jimple.v().newAssignStmt(longLocal, addTime);
			
	
	body.getUnits().insertBefore(timeInitalize, setStmt);
	body.getUnits().insertBefore(timeAssign, setStmt);
	
	InvokeExpr expr = setStmt.getInvokeExpr();
	expr.setArg(0, IntConstant.v(0));
	expr.setArg(1, longLocal);
	
	// Report the change
	InvokeStmt reportStmt = Jimple.v().newInvokeStmt(Jimple.v().newStaticInvokeExpr(
			reportRef, oldVal, longLocal));
	reportStmt.addTag(new InstrumentedCodeTag());
	body.getUnits().insertAfter(reportStmt, setStmt);
}
 
Example #2
Source Project: FuzzDroid   Author: srasthofer   File: UtilInstrumenter.java    License: Apache License 2.0 6 votes vote down vote up
public static Pair<Value, List<Unit>> generateParameterArray(List<Value> parameterList, Body body){
	List<Unit> generated = new ArrayList<Unit>();
	
	NewArrayExpr arrayExpr = Jimple.v().newNewArrayExpr(RefType.v("java.lang.Object"), IntConstant.v(parameterList.size()));
	
	Value newArrayLocal = generateFreshLocal(body, getParameterArrayType());
	Unit newAssignStmt = Jimple.v().newAssignStmt(newArrayLocal, arrayExpr);
	generated.add(newAssignStmt);
	
	for(int i = 0; i < parameterList.size(); i++){
		Value index = IntConstant.v(i);
		ArrayRef leftSide = Jimple.v().newArrayRef(newArrayLocal, index);
		Value rightSide = generateCorrectObject(body, parameterList.get(i), generated);
		
		Unit parameterInArray = Jimple.v().newAssignStmt(leftSide, rightSide);
		generated.add(parameterInArray);
	}
	
	return new Pair<Value, List<Unit>>(newArrayLocal, generated);
}
 
Example #3
Source Project: FuzzDroid   Author: srasthofer   File: SmartConstantDataExtractorFuzzyAnalysis.java    License: Apache License 2.0 6 votes vote down vote up
private boolean hasConstantIndexAtArrayForSplitDataFlow(Stmt[] dataflow) {
	Stmt firstAssign = dataflow[0];
	if(firstAssign instanceof AssignStmt) {
		AssignStmt ass = (AssignStmt)firstAssign;
		Value value = ass.getRightOp();
		if(value instanceof ArrayRef) {
			ArrayRef aRef = (ArrayRef)value;
			Value index = aRef.getIndex();
			
			if(index instanceof IntConstant)
				return true;
		}
	}
	else
		throw new RuntimeException("this should not happen - wrong assumption");
	
	return false;
}
 
Example #4
Source Project: FuzzDroid   Author: srasthofer   File: SmartConstantDataExtractorFuzzyAnalysis.java    License: Apache License 2.0 6 votes vote down vote up
private int getConstantArrayIndexForSplitDataFlow(Stmt[] dataflow) {
	Stmt firstAssign = dataflow[0];
	if(firstAssign instanceof AssignStmt) {
		AssignStmt ass = (AssignStmt)firstAssign;
		Value value = ass.getRightOp();
		if(value instanceof ArrayRef) {
			ArrayRef aRef = (ArrayRef)value;
			Value index = aRef.getIndex();
			
			if(index instanceof IntConstant)
				return ((IntConstant) index).value;
		}
	}
	else
		throw new RuntimeException("this should not happen - wrong assumption");
	
	return -1;
}
 
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: BaseEntryPointCreator.java    License: GNU General Public License v3.0 6 votes vote down vote up
protected Value getSimpleDefaultValue(String t) {
	if (t.equals("java.lang.String"))
		return StringConstant.v("");
	if (t.equals("char"))
		return DIntConstant.v(0, CharType.v());
	if (t.equals("byte"))
		return DIntConstant.v(0, ByteType.v());
	if (t.equals("short"))
		return DIntConstant.v(0, ShortType.v());
	if (t.equals("int"))
		return IntConstant.v(0);
	if (t.equals("float"))
		return FloatConstant.v(0);
	if (t.equals("long"))
		return LongConstant.v(0);
	if (t.equals("double"))
		return DoubleConstant.v(0);
	if (t.equals("boolean"))
		return DIntConstant.v(0, BooleanType.v());

	//also for arrays etc.
	return G.v().soot_jimple_NullConstant();
}
 
Example #7
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 #8
Source Project: JAADAS   Author: flankerhqd   File: Walker.java    License: GNU General Public License v3.0 6 votes vote down vote up
public void outAIntegerConstant(AIntegerConstant node)
   {
String s = (String) mProductions.removeLast();
       
       StringBuffer buf = new StringBuffer();
       if(node.getMinus() != null)
           buf.append('-');
       buf.append(s);
       
       s = buf.toString();
       if(s.endsWith("L")) {                        
    mProductions.addLast(LongConstant.v(Long.parseLong(s.substring(0, s.length()-1))));
       } 
       else if (s.equals("2147483648"))
    mProductions.addLast(IntConstant.v(Integer.MIN_VALUE));
       else
    mProductions.addLast(IntConstant.v(Integer.parseInt(s)));
   }
 
Example #9
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 #10
Source Project: JAADAS   Author: flankerhqd   File: StmtVisitor.java    License: GNU General Public License v3.0 6 votes vote down vote up
@Override
public void caseLookupSwitchStmt(LookupSwitchStmt stmt) {
       exprV.setOrigStmt(stmt);
       constantV.setOrigStmt(stmt);
	// create payload that references the switch's targets
	List<IntConstant> keyValues = stmt.getLookupValues();
	int[] keys = new int[keyValues.size()];
	for (int i = 0; i < keys.length; i++) {
		keys[i] = keyValues.get(i).value;
	}
	List<Unit> targets = stmt.getTargets();
	SparseSwitchPayload payload = new SparseSwitchPayload(keys, targets);
	switchPayloads.add(payload);
	// create sparse-switch instruction that references the payload
	Value key = stmt.getKey();
	Stmt defaultTarget = (Stmt) stmt.getDefaultTarget();
	if (defaultTarget == stmt)
		throw new RuntimeException("Looping switch block detected");
       addInsn(buildSwitchInsn(Opcode.SPARSE_SWITCH, key, defaultTarget,
       		payload, stmt), stmt);
}
 
Example #11
Source Project: JAADAS   Author: flankerhqd   File: DexNumTransformer.java    License: GNU General Public License v3.0 6 votes vote down vote up
/**
 * Collect all the locals which are assigned a IntConstant(0) or are used
 * within a zero comparison.
 *
 * @param body
 *            the body to analyze
 */
private Set<Local> getNumCandidates(Body body) {
	Set<Local> candidates = new HashSet<Local>();
	for (Unit u : body.getUnits()) {
		if (u instanceof AssignStmt) {
			AssignStmt a = (AssignStmt) u;
			if (!(a.getLeftOp() instanceof Local))
				continue;
			Local l = (Local) a.getLeftOp();
			Value r = a.getRightOp();
			if ((r instanceof IntConstant || r instanceof LongConstant)) {
				candidates.add(l);
				Debug.printDbg("[add null candidate: ", u);
			}
		}
	}

	return candidates;
}
 
Example #12
Source Project: JAADAS   Author: flankerhqd   File: PackedSwitchInstruction.java    License: GNU General Public License v3.0 6 votes vote down vote up
protected Stmt switchStatement(DexBody body, Instruction targetData, Local key) {
     PackedSwitchPayload i = (PackedSwitchPayload) targetData;
     List<? extends SwitchElement> seList = i.getSwitchElements();

     // the default target always follows the switch statement
     int defaultTargetAddress = codeAddress + instruction.getCodeUnits();
     Unit defaultTarget = body.instructionAtAddress(defaultTargetAddress).getUnit();

     List<IntConstant> lookupValues = new ArrayList<IntConstant>();
     List<Unit> targets = new ArrayList<Unit>();
     for(SwitchElement se: seList) {
       lookupValues.add(IntConstant.v(se.getKey()));
       int offset = se.getOffset();
       targets.add(body.instructionAtAddress(codeAddress + offset).getUnit());
     }
     switchStmt = Jimple.v().newLookupSwitchStmt(key, lookupValues, targets, defaultTarget);
     setUnit(switchStmt);
     
     if (IDalvikTyper.ENABLE_DVKTYPER) {
Debug.printDbg(IDalvikTyper.DEBUG, "constraint: "+ switchStmt);
         DalvikTyper.v().setType(switchStmt.getKeyBox(), IntType.v(), true);
     }
     
     return switchStmt;
 }
 
Example #13
Source Project: JAADAS   Author: flankerhqd   File: SparseSwitchInstruction.java    License: GNU General Public License v3.0 6 votes vote down vote up
protected Stmt switchStatement(DexBody body, Instruction targetData, Local key) {
     SparseSwitchPayload i = (SparseSwitchPayload) targetData;
     List<? extends SwitchElement> seList = i.getSwitchElements();

     // the default target always follows the switch statement
     int defaultTargetAddress = codeAddress + instruction.getCodeUnits();
     Unit defaultTarget = body.instructionAtAddress(defaultTargetAddress).getUnit();

     List<IntConstant> lookupValues = new ArrayList<IntConstant>();
     List<Unit> targets = new ArrayList<Unit>();
     for(SwitchElement se: seList) {
       lookupValues.add(IntConstant.v(se.getKey()));
       int offset = se.getOffset();
       targets.add(body.instructionAtAddress(codeAddress + offset).getUnit());
     }
     switchStmt = Jimple.v().newLookupSwitchStmt(key, lookupValues, targets, defaultTarget);
     setUnit(switchStmt);
     
     if (IDalvikTyper.ENABLE_DVKTYPER) {
Debug.printDbg(IDalvikTyper.DEBUG, "constraint: "+ switchStmt);
         DalvikTyper.v().setType(switchStmt.getKeyBox(), IntType.v(), true);
     }
     
     return switchStmt;
 }
 
Example #14
Source Project: JAADAS   Author: flankerhqd   File: DexNullThrowTransformer.java    License: GNU General Public License v3.0 6 votes vote down vote up
@Override
protected void internalTransform(Body b, String phaseName, Map<String, String> options) {
	LocalCreation lc = new LocalCreation(b.getLocals(), "ex");
	
	for (Iterator<Unit> unitIt = b.getUnits().snapshotIterator(); unitIt.hasNext(); ) {
		Unit u = unitIt.next();
		
		// Check for a null exception
		if (u instanceof ThrowStmt) {
			ThrowStmt throwStmt = (ThrowStmt) u;
			if (throwStmt.getOp() == NullConstant.v()
					|| throwStmt.getOp().equals(IntConstant.v(0))
					|| throwStmt.getOp().equals(LongConstant.v(0))) {
				createThrowStmt(b, throwStmt, lc);
			}
		}
	}
}
 
Example #15
Source Project: JAADAS   Author: flankerhqd   File: CPHelper.java    License: GNU General Public License v3.0 6 votes vote down vote up
public static Object isAConstantValue(Value toCheck){
	Object value=null;
	
	if(toCheck instanceof LongConstant){
		value = new Long(((LongConstant)toCheck).value);
	}
	else if(toCheck instanceof DoubleConstant){
		value = new Double(((DoubleConstant)toCheck).value);
	}
	else if(toCheck instanceof FloatConstant){
		value = new Float(((FloatConstant)toCheck).value);
	}
	else if(toCheck instanceof IntConstant){
		int val = ((IntConstant)toCheck).value;
		value = new Integer(val);			
	}
	return value;
}
 
Example #16
Source Project: JAADAS   Author: flankerhqd   File: CPHelper.java    License: GNU General Public License v3.0 6 votes vote down vote up
public static Value createConstant(Object toConvert){
	if(toConvert instanceof Long){
		return LongConstant.v( ((Long)toConvert).longValue() );
	}
	else if(toConvert instanceof Double){
		return DoubleConstant.v( ((Double)toConvert).doubleValue());
	}
	else if(toConvert instanceof Boolean){
		boolean val = ((Boolean)toConvert).booleanValue();
		if(val)
			return DIntConstant.v(1,BooleanType.v());
		else
			return DIntConstant.v(0,BooleanType.v());
	}	
	else if(toConvert instanceof Float){
		return FloatConstant.v( ((Float)toConvert).floatValue());
	}
	else if(toConvert instanceof Integer){
		return IntConstant.v( ((Integer)toConvert).intValue());
	}
	else
		return null;
}
 
Example #17
Source Project: JAADAS   Author: flankerhqd   File: AsmMethodSource.java    License: GNU General Public License v3.0 6 votes vote down vote up
private Value toSootValue(Object val) throws AssertionError {
	Value v;
	if (val instanceof Integer)
		v = IntConstant.v((Integer) val);
	else if (val instanceof Float)
		v = FloatConstant.v((Float) val);
	else if (val instanceof Long)
		v = LongConstant.v((Long) val);
	else if (val instanceof Double)
		v = DoubleConstant.v((Double) val);
	else if (val instanceof String)
		v = StringConstant.v(val.toString());
	else if (val instanceof org.objectweb.asm.Type)
		v = ClassConstant.v(((org.objectweb.asm.Type) val).getInternalName());
	else if (val instanceof Handle)
		v = MethodHandle.v(toSootMethodRef((Handle) val), ((Handle)val).getTag());
	else
		throw new AssertionError("Unknown constant type: " + val.getClass());
	return v;
}
 
Example #18
Source Project: JAADAS   Author: flankerhqd   File: UnitThrowAnalysis.java    License: GNU General Public License v3.0 6 votes vote down vote up
private void caseBinopDivExpr(BinopExpr expr) {
    // Factors out code common to caseDivExpr and caseRemExpr.
    // The checks against constant divisors would perhaps be
    // better performed in a later pass, post-constant-propagation.
    Value divisor = expr.getOp2();
    Type divisorType = divisor.getType();
    if (divisorType instanceof UnknownType) {
	result = result.add(mgr.ARITHMETIC_EXCEPTION);
    } else if ((divisorType instanceof IntegerType) &&
	((! (divisor instanceof IntConstant)) ||
	 (((IntConstant) divisor).equals(INT_CONSTANT_ZERO)))) {
	result = result.add(mgr.ARITHMETIC_EXCEPTION);
    } else if ((divisorType == LongType.v()) &&
	       ((! (divisor instanceof LongConstant)) ||
		(((LongConstant) divisor).equals(LONG_CONSTANT_ZERO)))) {
	result = result.add(mgr.ARITHMETIC_EXCEPTION);
    }
    caseBinopExpr(expr);
}
 
Example #19
Source Project: JAADAS   Author: flankerhqd   File: UnitThrowAnalysisTest.java    License: GNU General Public License v3.0 6 votes vote down vote up
@Test
public void testGLookupSwitchStmt() {
    Stmt target = Grimp.v().newAssignStmt(Grimp.v().newLocal("local0",
                IntType.v()),
            IntConstant.v(0));
    Stmt s = Grimp.v().newLookupSwitchStmt(IntConstant.v(1),
            Arrays.asList(new Value[] {
                IntConstant.v(1)
            }),
            Arrays.asList(new Unit[] {
                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 #20
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 testJReturnStmt() {
    Stmt s = Jimple.v().newReturnStmt(IntConstant.v(1));

    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 #21
Source Project: vasco   Author: rohanpadhye   File: PointsToAnalysis.java    License: GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * Returns a points-to graph with the locals of main initialised to
 * <tt>null</tt>, except the command-line arguments which are
 * initialised to an array of strings.
 */
@Override
public PointsToGraph boundaryValue(SootMethod entryPoint) {
	// For now we only support entry to the main method
	assert(entryPoint == Scene.v().getMainMethod());
	
	// Ok, start setting up entry value
	PointsToGraph entryValue = new PointsToGraph();		

	// Locals of main... (only reference types)
	SootMethod mainMethod = Scene.v().getMainMethod();
	for (Local local : mainMethod.getActiveBody().getLocals()) {
		if (local.getType() instanceof RefLikeType) {
			entryValue.assign(local, null);
		}
	}		
	
	// Command-line arguments to main...
	Local argsLocal = mainMethod.getActiveBody().getParameterLocal(0);
	NewArrayExpr argsExpr = new JNewArrayExpr(Scene.v().getRefType("java.lang.String"), IntConstant.v(0));
	entryValue.assignNew(argsLocal, argsExpr);
	entryValue.setFieldConstant(argsLocal, PointsToGraph.ARRAY_FIELD, PointsToGraph.STRING_CONST);
	

	return entryValue;
}
 
Example #22
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 #23
Source Project: JAADAS   Author: flankerhqd   File: UnitThrowAnalysisTest.java    License: GNU General Public License v3.0 6 votes vote down vote up
@Test
public void testJArrayRef() {
    ArrayRef arrayRef = Jimple.v().newArrayRef(
            Jimple.v().newLocal("local1",
                ArrayType.v(RefType.v("java.lang.Object"), 1)), 
            IntConstant.v(0));

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

    Set expectedCatch = new ExceptionHashSet(utility.VM_ERRORS_PLUS_SUPERTYPES);
    expectedCatch.add(utility.NULL_POINTER_EXCEPTION);
    expectedCatch.add(utility.ARRAY_INDEX_OUT_OF_BOUNDS_EXCEPTION);
    expectedCatch.add(utility.INDEX_OUT_OF_BOUNDS_EXCEPTION);
    expectedCatch.add(utility.RUNTIME_EXCEPTION);
    expectedCatch.add(utility.EXCEPTION);
    assertEquals(expectedCatch, 
            utility.catchableSubset(unitAnalysis.mightThrow(arrayRef)));
}
 
Example #24
Source Project: JAADAS   Author: flankerhqd   File: UnitThrowAnalysisTest.java    License: GNU General Public License v3.0 6 votes vote down vote up
@Test
public void testGArrayRef() {
    ArrayRef arrayRef = Grimp.v().newArrayRef(
            Grimp.v().newLocal("local1",
                ArrayType.v(RefType.v("java.lang.Object"), 1)), 
            IntConstant.v(0));

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

    Set expectedCatch = new ExceptionHashSet(utility.VM_ERRORS_PLUS_SUPERTYPES);
    expectedCatch.add(utility.NULL_POINTER_EXCEPTION);
    expectedCatch.add(utility.ARRAY_INDEX_OUT_OF_BOUNDS_EXCEPTION);
    expectedCatch.add(utility.INDEX_OUT_OF_BOUNDS_EXCEPTION);
    expectedCatch.add(utility.RUNTIME_EXCEPTION);
    expectedCatch.add(utility.EXCEPTION);
    assertEquals(expectedCatch, 
            utility.catchableSubset(unitAnalysis.mightThrow(arrayRef)));
}
 
Example #25
Source Project: SPDS   Author: CROSSINGTUD   File: AbstractBoomerangTest.java    License: Eclipse Public License 2.0 6 votes vote down vote up
public Optional<? extends Query> test(Stmt stmt) {
    if (stmt instanceof AssignStmt) {
        AssignStmt as = (AssignStmt) stmt;
        if (as.getLeftOp().toString().equals("allocation")) {
            Statement statement = new Statement(stmt, staticIcfg.getMethodOf(stmt));
            if (as.getLeftOp() instanceof Local && as.getRightOp() instanceof IntConstant) {
                Local local = (Local) as.getLeftOp();
                ForwardQuery forwardQuery = new ForwardQuery(statement,
                        new AllocVal(local, staticIcfg.getMethodOf(stmt), as.getRightOp(),
                                new Statement(as, staticIcfg.getMethodOf(stmt))));
                return Optional.<Query> of(forwardQuery);
            }

            if (as.containsInvokeExpr()) {
                AtomicReference<Query> returnValue = new AtomicReference<>();
                staticIcfg.addCalleeListener(
                        new IntegerAllocationSiteCalleeListener(returnValue, as, statement, stmt));
                if (returnValue.get() != null) {
                    return Optional.of(returnValue.get());
                }
            }
        }
    }

    return Optional.empty();
}
 
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: JimpleExprVisitorImpl.java    License: Apache License 2.0 5 votes vote down vote up
private int findMaxIndexOfArray(InvokeExpr invokeExpr) {
	Value array = null;
	int maxIndex = -1;
	for(Stmt stmt : stmtVisitor.getJimpleDataFlowStatements()) {
		if(stmt instanceof AssignStmt) {
			AssignStmt assign = (AssignStmt)stmt;
			if(array == null) {
				if(assign.getRightOp().equals(invokeExpr)) {
					array = assign.getLeftOp();
				}
			}
			else{
				Value rhs = assign.getRightOp();
				if(rhs instanceof ArrayRef) {
					ArrayRef arrayRef = (ArrayRef)rhs;
					if(arrayRef.getBase().equals(array)) {
						Value index = arrayRef.getIndex();
						if(index instanceof IntConstant) {
							IntConstant constant = (IntConstant)index;
							maxIndex = constant.value;
						}
					}
				}
			}
		}
	}
	return maxIndex;
}
 
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 new body for one of the postXXX methods in android.os.Handler
 * @param method The method for which to create the implementation
 * @param runnable The java.lang.Runnable class
 * @return The newly created body
 */
private Body patchHandlerPostBody(SootMethod method, SootClass runnable) {
	SootClass sc = method.getDeclaringClass();
	Body b = Jimple.v().newBody(method);
	method.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())));
	
	// Assign the parameters
	Local firstParam = null;
	for (int i = 0; i < method.getParameterCount(); i++)  {
		Local paramLocal = Jimple.v().newLocal("param" + i, method.getParameterType(i));
		b.getLocals().add(paramLocal);
		b.getUnits().add(Jimple.v().newIdentityStmt(paramLocal,
				Jimple.v().newParameterRef(method.getParameterType(i), i)));
		if (i == 0)
			firstParam = paramLocal;
	}
		
	// Invoke p0.run()
	b.getUnits().add(Jimple.v().newInvokeStmt(Jimple.v().newInterfaceInvokeExpr(firstParam,
			Scene.v().makeMethodRef(runnable, "run", Collections.<Type>emptyList(), VoidType.v(), false))));
	
	Unit retStmt = Jimple.v().newReturnStmt(IntConstant.v(1));
	b.getUnits().add(retStmt);
	return b;
}
 
Example #29
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);
}
 
Example #30
Source Project: JAADAS   Author: flankerhqd   File: StmtTemplatePrinter.java    License: GNU General Public License v3.0 5 votes vote down vote up
public void caseLookupSwitchStmt(LookupSwitchStmt stmt) {
	p.openBlock();

	String keyVarName = printValueAssignment(stmt.getKey(), "key");
	
	p.println("List<IntConstant> lookupValues = new LinkedList<IntConstant>();");
	int i=0;
	for(IntConstant c: (List<IntConstant>)stmt.getLookupValues()) {
		vtp.suggestVariableName("lookupValue"+i);
		c.apply(vtp);
		i++;
		
		p.println("lookupValues.add(lookupValue"+i+");");
	}
	
	p.println("List<Unit> targets = new LinkedList<Unit>();");
	for(Unit u : stmt.getTargets()) {
		String nameOfJumpTarget = nameOfJumpTarget(u);
		p.println("targets.add("+nameOfJumpTarget+")");
	}
	
	Unit defaultTarget = stmt.getDefaultTarget();
	p.println("Unit defaultTarget=" + defaultTarget.toString() + ";");
			
	printStmt(stmt, keyVarName, "lookupValues", "targets", "defaultTarget");
	
	p.closeBlock();
}