soot.jimple.StringConstant Java Examples

The following examples show how to use soot.jimple.StringConstant. 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: UpdateManifestAndCodeForWaitPDP.java    From DroidForce with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * 
 * @param mainActivityClass
 * @param mainActivityClass 
 */
public static void updateWaitPDPActivity(String packageName, String mainActivityClass) {
	
	if (mainActivityClass.startsWith(".")) {
		mainActivityClass = packageName + mainActivityClass;
	}
	
	SootClass sc = Scene.v().getSootClass("de.ecspride.javaclasses.WaitPDPActivity");
	SootMethod sm = sc.getMethodByName("<init>");
	Body b = sm.retrieveActiveBody();
	for (Unit u: b.getUnits()) {
		if (u instanceof AssignStmt) {
			AssignStmt asg = (AssignStmt)u;
			if (asg.getRightOp() instanceof StringConstant) {
				StringConstant cst = (StringConstant)asg.getRightOp();
				System.out.println("cst: "+ cst);
				if (cst.value.equals("")) {
					asg.setRightOp(StringConstant.v(mainActivityClass));
					System.out.println("asg: "+ asg);
				}
			}
		}
	}
}
 
Example #2
Source File: Util.java    From DroidForce with GNU Lesser General Public License v2.1 6 votes vote down vote up
public static void changeConstantStringInField(SootField sf,
		String newConstantString) {
	SootClass sc = sf.getDeclaringClass();
	SootMethod sm = sc.getMethodByName("<clinit>");
	
	boolean hasBeenUpdated = false;
	for (Unit u: sm.retrieveActiveBody().getUnits()) {
		if (u instanceof AssignStmt) {
			AssignStmt ass = (AssignStmt)u;
			Value lop = ass.getLeftOp();
			if (lop.toString().equals(sf.toString())) {
				System.out.println("previous string: "+ ass);
				ass.setRightOp(StringConstant.v(newConstantString));
				hasBeenUpdated = true;
				System.out.println("updated string : "+ ass);
			}
		}
	}
	
	if (!hasBeenUpdated)
		throw new RuntimeException("error: no StringConstant found for field "+ sf);
	
}
 
Example #3
Source File: DexNullArrayRefTransformer.java    From JAADAS with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Creates a new statement that throws a NullPointerException
 * @param body The body in which to create the statement
 * @param oldStmt The old faulty statement that shall be replaced with the
 * exception
 * @param lc The object for creating new locals
 */
private void createThrowStmt(Body body, Unit oldStmt, LocalCreation lc) {
	RefType tp = RefType.v("java.lang.NullPointerException");
	Local lcEx = lc.newLocal(tp);
	
	SootMethodRef constructorRef = Scene.v().makeConstructorRef(tp.getSootClass(),
			Collections.singletonList((Type) RefType.v("java.lang.String")));
	
	// Create the exception instance
	Stmt newExStmt = Jimple.v().newAssignStmt(lcEx, Jimple.v().newNewExpr(tp));
	body.getUnits().insertBefore(newExStmt, oldStmt);
	Stmt invConsStmt = Jimple.v().newInvokeStmt(Jimple.v().newVirtualInvokeExpr(lcEx,
			constructorRef, Collections.singletonList(StringConstant.v(
					"Invalid array reference replaced by Soot"))));
	body.getUnits().insertBefore(invConsStmt, oldStmt);
	
	// Throw the exception
	body.getUnits().swapWith(oldStmt, Jimple.v().newThrowStmt(lcEx));
}
 
Example #4
Source File: Util.java    From JAADAS with GNU General Public License v3.0 6 votes vote down vote up
/**
    * Insert a runtime exception before unit u of body b. Useful to analyze broken code (which make reference to inexisting class for instance)
    * exceptionType: e.g., "java.lang.RuntimeException"
    */
public static void addExceptionAfterUnit(Body b, String exceptionType, Unit u, String m) {
	LocalCreation lc = new LocalCreation(b.getLocals());
	Local l = lc.newLocal(RefType.v(exceptionType));
	
	List<Unit> newUnits = new ArrayList<Unit>();
	Unit u1 = Jimple.v().newAssignStmt(l, Jimple.v().newNewExpr(RefType.v(exceptionType)));
	Unit u2 = Jimple.v().newInvokeStmt(
			Jimple.v().newSpecialInvokeExpr(
					l,
					Scene.v().makeMethodRef(Scene.v().getSootClass(exceptionType),
							"<init>",
							Collections.singletonList((Type) RefType.v("java.lang.String")),
							VoidType.v(),
							false),
					StringConstant.v(m)));
	Unit u3 = Jimple.v().newThrowStmt(l);
	newUnits.add(u1);
	newUnits.add(u2);
	newUnits.add(u3);

	b.getUnits().insertBefore(newUnits, u);
}
 
Example #5
Source File: UnitThrowAnalysisTest.java    From JAADAS with GNU General Public License v3.0 6 votes vote down vote up
@Test
public void testGExitMonitorStmt() {
    Stmt s = Grimp.v().newExitMonitorStmt(StringConstant.v("test"));


    Set expectedRep = new ExceptionHashSet(utility.VM_ERRORS);
    expectedRep.add(utility.ILLEGAL_MONITOR_STATE_EXCEPTION);
    expectedRep.add(utility.NULL_POINTER_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.NULL_POINTER_EXCEPTION);
    expectedCatch.add(utility.RUNTIME_EXCEPTION);
    expectedCatch.add(utility.EXCEPTION);

    assertEquals(expectedCatch,
            utility.catchableSubset(unitAnalysis.mightThrow(s)));
}
 
Example #6
Source File: JimpleExprVisitorImpl.java    From FuzzDroid with Apache License 2.0 6 votes vote down vote up
@Override
public void caseSpecialInvokeExpr(SpecialInvokeExpr v) {
	//is the invokeExpr a source method?
	if(isSourceMethod(v)) {
		StringConstant newSourceValue = StringConstant.v("loggingPoint");
		SMTBinding binding = stmtVisitor.createNewBindingForValue(newSourceValue);
		stmtVisitor.addValueBindingToVariableDeclaration(newSourceValue, binding);				
		//no smt-statement required, just return the binding
		this.result = binding;
		
		// Additionally check whether the source method need special treatment
		if(isExpressionThatNeedsToBeConvertedToSMT(v)) {
			convertSpecialExpressionsToSMT(v, currentStatement);
		}
		
	} else {
		if(isStringOperationSupportedBySMT(v))
			convertStringOperationToSMT(v, v.getBase());
		else if(isExpressionThatNeedsToBeConvertedToSMT(v))
			convertSpecialExpressionsToSMT(v, currentStatement);
		else
			convertAPIMethodToSMT(v);
	}
}
 
Example #7
Source File: JimpleExprVisitorImpl.java    From FuzzDroid with Apache License 2.0 6 votes vote down vote up
@Override
public void caseVirtualInvokeExpr(VirtualInvokeExpr virtualInvokeExpr) {
	//is the invokeExpr a source method?
	if(isSourceMethod(virtualInvokeExpr)) {
		StringConstant newSourceValue = StringConstant.v("loggingPoint");
		SMTBinding binding = stmtVisitor.createNewBindingForValue(newSourceValue);
		stmtVisitor.addValueBindingToVariableDeclaration(newSourceValue, binding);				
		//no smt-statement required, just return the binding
		this.result = binding;
		
		// Additionally check whether the source method need special treatment
		if(isExpressionThatNeedsToBeConvertedToSMT(virtualInvokeExpr)) {
			convertSpecialExpressionsToSMT(virtualInvokeExpr, currentStatement);
		}
		
	} else {
		if(isStringOperationSupportedBySMT(virtualInvokeExpr))
			convertStringOperationToSMT(virtualInvokeExpr, virtualInvokeExpr.getBase());
		else if(isExpressionThatNeedsToBeConvertedToSMT(virtualInvokeExpr))
			convertSpecialExpressionsToSMT(virtualInvokeExpr, currentStatement);
		else
			convertAPIMethodToSMT(virtualInvokeExpr);
	}
}
 
Example #8
Source File: UnitThrowAnalysisTest.java    From JAADAS with GNU General Public License v3.0 6 votes vote down vote up
@Test
public void testJExitMonitorStmt() {
    Stmt s = Jimple.v().newExitMonitorStmt(StringConstant.v("test"));

    Set expectedRep = new ExceptionHashSet(utility.VM_ERRORS);
    expectedRep.add(utility.ILLEGAL_MONITOR_STATE_EXCEPTION);
    expectedRep.add(utility.NULL_POINTER_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.NULL_POINTER_EXCEPTION);
    expectedCatch.add(utility.RUNTIME_EXCEPTION);
    expectedCatch.add(utility.EXCEPTION);
    assertEquals(expectedCatch,
            utility.catchableSubset(unitAnalysis.mightThrow(s)));
}
 
Example #9
Source File: UnitThrowAnalysisTest.java    From JAADAS with GNU General Public License v3.0 6 votes vote down vote up
@Test
public void testGEnterMonitorStmt() {
    Stmt s = Grimp.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 #10
Source File: UnitThrowAnalysisTest.java    From JAADAS with 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 #11
Source File: DexNullThrowTransformer.java    From JAADAS with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Creates a new statement that throws a NullPointerException
 * @param body The body in which to create the statement
 * @param oldStmt The old faulty statement that shall be replaced with the
 * exception
 * @param lc The object for creating new locals
 */
private void createThrowStmt(Body body, Unit oldStmt, LocalCreation lc) {
	RefType tp = RefType.v("java.lang.NullPointerException");
	Local lcEx = lc.newLocal(tp);
	
	SootMethodRef constructorRef = Scene.v().makeConstructorRef(tp.getSootClass(),
			Collections.singletonList((Type) RefType.v("java.lang.String")));
	
	// Create the exception instance
	Stmt newExStmt = Jimple.v().newAssignStmt(lcEx, Jimple.v().newNewExpr(tp));
	body.getUnits().insertBefore(newExStmt, oldStmt);
	Stmt invConsStmt = Jimple.v().newInvokeStmt(Jimple.v().newVirtualInvokeExpr(lcEx,
			constructorRef, Collections.singletonList(StringConstant.v(
					"Null throw statement replaced by Soot"))));
	body.getUnits().insertBefore(invConsStmt, oldStmt);
	
	// Throw the exception
	body.getUnits().swapWith(oldStmt, Jimple.v().newThrowStmt(lcEx));
}
 
Example #12
Source File: BaseEntryPointCreator.java    From JAADAS with 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 #13
Source File: AsmMethodSource.java    From JAADAS with 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 #14
Source File: AndroidSourceSinkManager.java    From JAADAS with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Finds the last assignment to the given String local by searching upwards
 * from the given statement
 * 
 * @param stmt
 *            The statement from which to look backwards
 * @param local
 *            The variable for which to look for assignments
 * @return The last value assigned to the given variable
 */
private String findLastStringAssignment(Stmt stmt, Local local, BiDiInterproceduralCFG<Unit, SootMethod> cfg) {
	if (stmt instanceof AssignStmt) {
		AssignStmt assign = (AssignStmt) stmt;
		if (assign.getLeftOp() == local) {
			// ok, now find the new value from the right side
			if (assign.getRightOp() instanceof StringConstant)
				return ((StringConstant) assign.getRightOp()).value;
		}
	}

	// Continue the search upwards
	for (Unit pred : cfg.getPredsOf(stmt)) {
		if (!(pred instanceof Stmt))
			continue;
		String lastAssignment = findLastStringAssignment((Stmt) pred, local, cfg);
		if (lastAssignment != null)
			return lastAssignment;
	}
	return null;
}
 
Example #15
Source File: NullnessAnalysis.java    From JAADAS with GNU General Public License v3.0 5 votes vote down vote up
private void handleRefTypeAssignment(DefinitionStmt assignStmt, AnalysisInfo out) {
	Value left = assignStmt.getLeftOp();
	Value right = assignStmt.getRightOp();
	
	//unbox casted value
	if(right instanceof JCastExpr) {
		JCastExpr castExpr = (JCastExpr) right;
		right = castExpr.getOp();
	}
	
	//if we have a definition (assignment) statement to a ref-like type, handle it,
	if ( isAlwaysNonNull(right)
	|| right instanceof NewExpr || right instanceof NewArrayExpr
	|| right instanceof NewMultiArrayExpr || right instanceof ThisRef
	|| right instanceof StringConstant || right instanceof ClassConstant
	|| right instanceof CaughtExceptionRef) {
		//if we assign new... or @this, the result is non-null
		out.put(left,NON_NULL);
	} else if(right==NullConstant.v()) {
		//if we assign null, well, it's null
		out.put(left, NULL);
	} else if(left instanceof Local && right instanceof Local) {
		out.put(left, out.get(right));
	} else {
		out.put(left, TOP);
	}
}
 
Example #16
Source File: PathExecutionTransformer.java    From FuzzDroid with Apache License 2.0 5 votes vote down vote up
private void instrumentInfoAboutNonAPICall(Body body){					
	String methodSignature =  body.getMethod().getSignature();
	Unit generatedJimpleCode = UtilInstrumenter.makeJimpleStaticCallForPathExecution("logInfoAboutNonApiMethodAccess", RefType.v("java.lang.String"), StringConstant.v(methodSignature));
	generatedJimpleCode.addTag(new InstrumentedCodeTag());
	//super-method call has to be the first statement
	if(methodSignature.contains("<init>(") || methodSignature.contains("<clinit>"))
		body.getUnits().insertAfter(generatedJimpleCode, getUnitAfterIdentities(body));
	else
		body.getUnits().insertBefore(generatedJimpleCode, getUnitAfterIdentities(body));
}
 
Example #17
Source File: ConstantInitializerToTagTransformer.java    From JAADAS with GNU General Public License v3.0 5 votes vote down vote up
private ConstantValueTag createConstantTagFromValue(Constant rightOp) {
	if (rightOp instanceof DoubleConstant)
		return new DoubleConstantValueTag(((DoubleConstant) rightOp).value);
	else if (rightOp instanceof FloatConstant)
		return new FloatConstantValueTag(((FloatConstant) rightOp).value);
	else if (rightOp instanceof IntConstant)
		return new IntegerConstantValueTag(((IntConstant) rightOp).value);
	else if (rightOp instanceof LongConstant)
		return new LongConstantValueTag(((LongConstant) rightOp).value);
	else if (rightOp instanceof StringConstant)
		return new StringConstantValueTag(((StringConstant) rightOp).value);
	else
		return null;
}
 
Example #18
Source File: ConstantInitializerToTagTransformer.java    From JAADAS with GNU General Public License v3.0 5 votes vote down vote up
private boolean checkConstantValue(ConstantValueTag t, Constant rightOp) {
	if (t == null || rightOp == null)
		return true;
	
	if (t instanceof DoubleConstantValueTag) {
		if (!(rightOp instanceof DoubleConstant))
			return false;
		return ((DoubleConstantValueTag) t).getDoubleValue() == ((DoubleConstant) rightOp).value;
	}
	else if (t instanceof FloatConstantValueTag) {
		if (!(rightOp instanceof FloatConstant))
			return false;
		return ((FloatConstantValueTag) t).getFloatValue() == ((FloatConstant) rightOp).value;
	}
	else if (t instanceof IntegerConstantValueTag) {
		if (!(rightOp instanceof IntConstant))
			return false;
		return ((IntegerConstantValueTag) t).getIntValue() == ((IntConstant) rightOp).value;
	}
	else if (t instanceof LongConstantValueTag) {
		if (!(rightOp instanceof LongConstant))
			return false;
		return ((LongConstantValueTag) t).getLongValue() == ((LongConstant) rightOp).value;
	}
	else if (t instanceof StringConstantValueTag) {
		if (!(rightOp instanceof StringConstant))
			return false;
		return ((StringConstantValueTag) t).getStringValue().equals(((StringConstant) rightOp).value);
	}
	else
		// We don't know the type, so we assume it's alright
		return true;
}
 
Example #19
Source File: UnitThrowAnalysisTest.java    From JAADAS with GNU General Public License v3.0 5 votes vote down vote up
@Test
public void testStringConstant() {
    Value v = StringConstant.v("test");
    assertTrue(ExceptionTestUtility.sameMembers(utility.VM_ERRORS, Collections.EMPTY_SET,
                unitAnalysis.mightThrow(v)));
    assertEquals(utility.VM_ERRORS_PLUS_SUPERTYPES,
            utility.catchableSubset(unitAnalysis.mightThrow(v)));
}
 
Example #20
Source File: QueryForCallSiteDetector.java    From SPDS with Eclipse Public License 2.0 5 votes vote down vote up
private void getAllExpectedAccessPath(Stmt u, SootMethod m) {
    Value arg = u.getInvokeExpr().getArg(1);
    if (arg instanceof StringConstant) {
        StringConstant stringConstant = (StringConstant) arg;
        String value = stringConstant.value;
        expectedAccessPaths.addAll(AccessPathParser.parseAllFromString(value, m));
    }
}
 
Example #21
Source File: PointsToGraph.java    From vasco with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Creates a new node for a constant.
 */
private NewExpr constantNewExpr(Constant constant) {
	if (constant instanceof StringConstant) {
		return STRING_SITE;
	} else if (constant instanceof ClassConstant) {
		return CLASS_SITE;
	} else if (constant instanceof NullConstant) {
		return null;
	} else {
		throw new RuntimeException(constant.toString());
	}
}
 
Example #22
Source File: PathExecutionTransformer.java    From FuzzDroid with Apache License 2.0 5 votes vote down vote up
private void instrumentEachBranchAccess(Body body, IfStmt ifStmt){		
	String methodSignature =  body.getMethod().getSignature();
	String condition = ifStmt.getCondition().toString();		
	Unit generatedJimpleCodeForBranch = UtilInstrumenter.makeJimpleStaticCallForPathExecution("logInfoAboutBranchAccess", 
			RefType.v("java.lang.String"), StringConstant.v(methodSignature),
			RefType.v("java.lang.String"), StringConstant.v(condition),
			RefType.v("java.lang.String"), NullConstant.v()
			);
	generatedJimpleCodeForBranch.addTag(new InstrumentedCodeTag());
	
	Unit generatedJimpleCodeThenBranch = UtilInstrumenter.makeJimpleStaticCallForPathExecution("logInfoAboutBranchAccess", 
			RefType.v("java.lang.String"), StringConstant.v(methodSignature),
			RefType.v("java.lang.String"), NullConstant.v(),
			RefType.v("java.lang.String"), StringConstant.v("then branch")
			);
	generatedJimpleCodeThenBranch.addTag(new InstrumentedCodeTag());
	
	Unit generatedJimpleCodeElseBranch = UtilInstrumenter.makeJimpleStaticCallForPathExecution("logInfoAboutBranchAccess", 
			RefType.v("java.lang.String"), StringConstant.v(methodSignature),
			RefType.v("java.lang.String"), NullConstant.v(),
			RefType.v("java.lang.String"), StringConstant.v("else branch")
			);
	generatedJimpleCodeElseBranch.addTag(new InstrumentedCodeTag());
	
	body.getUnits().insertBefore(generatedJimpleCodeForBranch, ifStmt);
	
	//treatment of target statement ("true"-branch)
	Stmt targetStmt = ifStmt.getTarget();
	if(!branchTargetStmt.contains(targetStmt.toString())) {
		branchTargetStmt.add(generatedJimpleCodeThenBranch.toString());
		body.getUnits().insertBefore(generatedJimpleCodeThenBranch, targetStmt);
	}
	
	//treatment of "else"-branch
	body.getUnits().insertAfter(generatedJimpleCodeElseBranch, ifStmt);
}
 
Example #23
Source File: JimpleStmtVisitorImpl.java    From FuzzDroid with Apache License 2.0 5 votes vote down vote up
public SMTBinding createNewBindingForValue(Value value) {
	SMTBinding binding = null;
	if(hasBindingForValue(value)) {
		SMTBinding oldBinding = getLatestBindingForValue(value);
		int ssaVersionOldBinding = oldBinding.getVersion();
		//increment version
		ssaVersionOldBinding += 1;
		binding = new SMTBinding(oldBinding.getVariableName(), oldBinding.getType(), ssaVersionOldBinding);	
		return binding;
	}
	else{
		if(value instanceof Local) {
			Local local = (Local) value;
			SMTBinding.TYPE bindingType = createBindingType(local.getType());
			String localName = local.getName();
			//check if such a local name is already taken
			int countOccurance = 0;
			for(Map.Entry<Value, SMTBinding> entry : globalScopeSSAFormHelper.entrySet()) {
				if(entry.getKey().toString().equals(localName))
					countOccurance += 1;
			}
			if(countOccurance > 0) {
				String tmp = new String(localName);
				for(int i = 0; i < countOccurance; i++)
					localName += tmp;
			}
			binding = new SMTBinding(localName, bindingType, 0);
		}
		else if(value instanceof StringConstant) {
			StringConstant constantString = (StringConstant) value;
			String constantStringValue = constantString.value;
			binding = new SMTBinding(constantStringValue, SMTBinding.TYPE.String, 0);
		}
		
		return binding;
	}
}
 
Example #24
Source File: JimpleStmtVisitorImpl.java    From FuzzDroid with Apache License 2.0 5 votes vote down vote up
public SMTBinding createTemporalBinding(SMTBinding.TYPE type) {
	String tmpName = null;
	switch(type) {
	case String : tmpName = "StringTMP"; break;
	case Int : tmpName = "IntTMP"; break;
	case Bool : tmpName = "BoolTMP"; break;
	case Real:
		break;
	default:
		break;
	}
	StringConstant tmpValue = StringConstant.v(tmpName);
	
	SMTBinding binding = null;
	if(hasBindingForValue(tmpValue)) {
		SMTBinding oldBinding = getLatestBindingForValue(tmpValue);
		int ssaVersionOldBinding = oldBinding.getVersion();
		//increment version
		ssaVersionOldBinding += 1;
		binding = new SMTBinding(oldBinding.getVariableName(), oldBinding.getType(), ssaVersionOldBinding);	
	}
	else {
		binding = new SMTBinding(tmpName, type, 0);
	}
	addValueBindingToVariableDeclaration(tmpValue, binding);
	return binding;
}
 
Example #25
Source File: JimpleExprVisitorImpl.java    From FuzzDroid with Apache License 2.0 5 votes vote down vote up
@Override
public void caseInterfaceInvokeExpr(InterfaceInvokeExpr v) {
	if(isSourceMethod(v)) {
		StringConstant newSourceValue = StringConstant.v("loggingPoint");
		SMTBinding binding = stmtVisitor.createNewBindingForValue(newSourceValue);
		stmtVisitor.addValueBindingToVariableDeclaration(newSourceValue, binding);				
		//no smt-statement required, just return the binding
		this.result = binding;
		
		// Additionally check whether the source method need special treatment
		if(isExpressionThatNeedsToBeConvertedToSMT(v)) {
			convertSpecialExpressionsToSMT(v, currentStatement);
		}
	}
	else if(isExpressionThatNeedsToBeConvertedToSMT(v)){
		convertSpecialExpressionsToSMT(v, currentStatement);
	}else{
		//just propagate the taint value of previous statement
		Stmt prevStmt = stmtVisitor.getPreviousDataFlowPathElement(currentStatement);
		if(prevStmt == null) 
			throw new RuntimeException("there is no previous statement");
		else{			
			this.result = stmtVisitor.getBindingForTaintedValue(prevStmt);
			if(this.result == null)
				throw new RuntimeException("double check this here");
		}
	}
}
 
Example #26
Source File: Walker.java    From JAADAS with GNU General Public License v3.0 5 votes vote down vote up
public void outAStringConstant(AStringConstant node)
   {
String s = (String) mProductions.removeLast();
mProductions.addLast(StringConstant.v(s));
       /*
         try {
         String t = StringTools.getUnEscapedStringOf(s);
       
         mProductions.push(StringConstant.v(t));
         } catch(RuntimeException e) {
         G.v().out.println(s);
         throw e;
         }
       */
   }
 
Example #27
Source File: JimpleExprVisitorImpl.java    From FuzzDroid with Apache License 2.0 4 votes vote down vote up
private void generateSMTStartsWithStmt(InvokeExpr invokeExpr, Value base) {
	//############## a.startsWith(b) treatment ##############
	//(= t (StartsWith a b)
			
	//lhs treatment
	SMTBinding lhs = stmtVisitor.createTemporalBinding(SMTBinding.TYPE.Bool);
	
	//rhs treatment
	Value argumentValue = invokeExpr.getArg(0);
	SMTValue argumentSMTForm = null;
	if(argumentValue instanceof StringConstant) {
		argumentSMTForm = new SMTConstantValue<String>(((StringConstant) argumentValue).value); 
	}
	else {			
		SMTBinding tmpBinding = null;
		if(stmtVisitor.hasBindingForValue(argumentValue))
			tmpBinding = stmtVisitor.getLatestBindingForValue(argumentValue);
		else {
			tmpBinding = stmtVisitor.createNewBindingForValue(argumentValue);
			stmtVisitor.addValueBindingToVariableDeclaration(argumentValue, tmpBinding);
			stmtVisitor.addNewDynamicValueForArgumentToMap(currentStatement, tmpBinding, 0);
		}
					
		argumentSMTForm = new SMTBindingValue(tmpBinding);
	}
	
	//base treatment
	SMTBinding baseBinding = null;
	if(stmtVisitor.hasBindingForValue(base))
		baseBinding = stmtVisitor.getLatestBindingForValue(base);
	else {
		baseBinding = stmtVisitor.createNewBindingForValue(base);
		stmtVisitor.addValueBindingToVariableDeclaration(base, baseBinding);
		stmtVisitor.addNewDynamicValueForBaseObjectToMap(currentStatement, baseBinding);			
	}
	
	SMTStartsWithMethodCall startsWithMethod = new SMTStartsWithMethodCall(new SMTBindingValue(baseBinding), argumentSMTForm);
	SMTMethodAssignment methodAss = new SMTMethodAssignment(lhs, startsWithMethod);
	SMTAssertStatement assertStmt = new SMTAssertStatement(methodAss);
	
	stmtVisitor.addAssertStmtToAllPrograms(assertStmt);
	this.result = lhs;				
}
 
Example #28
Source File: DynamicValueTransformer.java    From FuzzDroid with Apache License 2.0 4 votes vote down vote up
private void checkAndReport(Body b, Stmt curStmt, Value value, int paramIdx) {
	LocalGenerator localGenerator = new LocalGenerator(b);
	RefType stringType = RefType.v("java.lang.String");
	Value lhs = value;
	
	if(lhs instanceof StringConstant)
		return;
	else if(lhs instanceof IntConstant)
		return;
	
	// If this is a CharSequence, we need to convert it into a string
	if (lhs.getType() == RefType.v("java.lang.CharSequence") ||
			lhs.getType() == RefType.v("java.lang.StringBuilder") && lhs instanceof Local) {
		SootMethodRef toStringRef = Scene.v().getMethod("<java.lang.Object: "
				+ "java.lang.String toString()>").makeRef();
		Local stringLocal = localGenerator.generateLocal(stringType);
		Stmt stringAssignStmt = Jimple.v().newAssignStmt(stringLocal,
				Jimple.v().newVirtualInvokeExpr((Local) lhs, toStringRef));
		stringAssignStmt.addTag(new InstrumentedCodeTag());
		
		b.getUnits().insertBefore(stringAssignStmt, curStmt);
		lhs = stringLocal;
	}
	else if (lhs.getType() != IntType.v() && lhs.getType() != stringType)
		return;
	
	//new String() case
	if (value instanceof NewExpr)
		return;
	
	// Depending on the type of the value, we might need an intermediate local
	if (!(lhs instanceof Local)) {
		Local newLhs = localGenerator.generateLocal(lhs.getType());
		AssignStmt assignLocalStmt = Jimple.v().newAssignStmt(newLhs, lhs);
		assignLocalStmt.addTag(new InstrumentedCodeTag());
		b.getUnits().insertBefore(assignLocalStmt, curStmt);
		lhs = newLhs;
	}
	
	// Report the value
	Stmt reportValueStmt;
	if (lhs.getType() == stringType) {
		reportValueStmt = Jimple.v().newInvokeStmt(
				Jimple.v().newStaticInvokeExpr(refString, lhs, IntConstant.v(paramIdx)));
	}
	else if (lhs.getType() == IntType.v()) {
		reportValueStmt = Jimple.v().newInvokeStmt(
				Jimple.v().newStaticInvokeExpr(refInt, lhs, IntConstant.v(paramIdx)));
	}
	else
		return;
	reportValueStmt.addTag(new InstrumentedCodeTag());
	
	b.getUnits().insertBefore(reportValueStmt, curStmt);
}
 
Example #29
Source File: PathExecutionTransformer.java    From FuzzDroid with Apache License 2.0 4 votes vote down vote up
private void instrumentInfoAboutNonApiCaller(Body body, Unit unit)
{	
	//our instrumented code
	if(unit.hasTag(InstrumentedCodeTag.name))
		return;
	
	InvokeExpr invokeExpr = null;
	if(unit instanceof DefinitionStmt)
	{
		DefinitionStmt defStmt = (DefinitionStmt)unit;
		if(defStmt.containsInvokeExpr())
		{
			invokeExpr = defStmt.getInvokeExpr();
		}
	}					
	else if(unit instanceof InvokeStmt)
	{
		InvokeStmt invokeStmt = (InvokeStmt)unit;
		invokeExpr = invokeStmt.getInvokeExpr();
	}				
	
	if(invokeExpr != null)
	{			
		if(!UtilInstrumenter.isApiCall(invokeExpr))
		{
			String invokeExprMethodSignature = invokeExpr.getMethod().getSignature();
			
			List<Value> parameter = invokeExpr.getArgs();
			List<Unit> generated = new ArrayList<Unit>();
			Pair<Value, List<Unit>> arrayRefAndInstrumentation = UtilInstrumenter.generateParameterArray(parameter, body);
			
			List<Unit> generatedArrayInstrumentation = arrayRefAndInstrumentation.getSecond();
			Value arrayRef = arrayRefAndInstrumentation.getFirst();
			
			Unit generatedInvokeStmt = UtilInstrumenter.makeJimpleStaticCallForPathExecution("logInfoAboutNonApiMethodCaller", 	
					RefType.v("java.lang.String"), StringConstant.v(body.getMethod().getSignature()),
					RefType.v("java.lang.String"), StringConstant.v(invokeExprMethodSignature),
					UtilInstrumenter.getParameterArrayType(), (parameter.isEmpty())? NullConstant.v() : arrayRef);
			generatedInvokeStmt.addTag(new InstrumentedCodeTag());
			generated.addAll(generatedArrayInstrumentation);
			generated.add(generatedInvokeStmt);

			body.getUnits().insertBefore(generated, unit);
		}
	}		
}
 
Example #30
Source File: PolicyEnforcementPoint.java    From DroidForce with GNU Lesser General Public License v2.1 4 votes vote down vote up
private List<Unit> instrumentIntentAddings(BiDiInterproceduralCFG<Unit, SootMethod> cfg,
		Unit unit, InvokeExpr sinkExpr, Set<ResultSourceInfo> sourceInfo){
	if(isMethodInterComponentSink(sinkExpr.getMethod())){
		SootMethod method = cfg.getMethodOf(unit);
		Body body = null;
		if(method.hasActiveBody())
			body = method.retrieveActiveBody();
		else
			throw new RuntimeException("No body found!");
		
		Set<String> sourceCategories = getDataIdList(sourceInfo);
		
		final String hashSetType = "java.util.HashSet";
		List<Unit> generated = new ArrayList<Unit>();
		
		//HashSet initialization
		Local hashSetLocal = generateFreshLocal(body, RefType.v(hashSetType));
		NewExpr newExpr = Jimple.v().newNewExpr(RefType.v(hashSetType));
		AssignStmt assignStmt = Jimple.v().newAssignStmt(hashSetLocal, newExpr);
		generated.add(assignStmt);
		
		//constructor call
		SpecialInvokeExpr constructorCall = Jimple.v().newSpecialInvokeExpr(hashSetLocal, Scene.v().getMethod("<java.util.HashSet: void <init>()>").makeRef());
		InvokeStmt constructorCallStmt = Jimple.v().newInvokeStmt(constructorCall);
		generated.add(constructorCallStmt);
		
		//add categories to HashSet
		for(String cat : sourceCategories){
			InterfaceInvokeExpr addCall = Jimple.v().newInterfaceInvokeExpr(hashSetLocal, Scene.v().getMethod("<java.util.Set: boolean add(java.lang.Object)>").makeRef(), StringConstant.v(cat));
			InvokeStmt addCallStmt = Jimple.v().newInvokeStmt(addCall);
			generated.add(addCallStmt);
		}
		
		//get Intent
		Value intent = sinkExpr.getArg(0);
		List<Object> args = new ArrayList<Object>();
		args.add(RefType.v("android.content.Intent"));
		args.add(intent);
		args.add(RefType.v(hashSetType));
		args.add(hashSetLocal);
		StaticInvokeExpr sie = Instrumentation.createJimpleStaticInvokeExpr(
				Settings.INSTRUMENTATION_HELPER_JAVA,
				"addTaintInformationToIntent",
				args);
		InvokeStmt invStmt = Jimple.v().newInvokeStmt(sie);
		generated.add(invStmt);
		
		return generated;
	}
	return Collections.emptyList();
}