Convert many single-method anonymous classes to lambdas

Eclipse's automated code clean-up tool did most of the heavy lifting
here: it specifically has a clean-up option for converting functional
interfaces to lambdas.  I merely had to revert the automated changes
for a single enumeration class for which it produced invalid results,
and for a few test inputs that apparently aren't set up to be compiled
with Java 8.
This commit is contained in:
Ben Liblit 2017-11-22 19:28:36 -06:00
parent 28f0e09435
commit 790d37781b
116 changed files with 1249 additions and 2387 deletions

View File

@ -42,7 +42,6 @@ import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
@ -3476,12 +3475,7 @@ public abstract class JDTJava2CAstTranslator<T extends Position> {
constants.add(var);
// constants are unsorted by default
Collections.sort(constants, new Comparator<IVariableBinding>() {
@Override
public int compare(IVariableBinding arg0, IVariableBinding arg1) {
return arg0.getVariableId() - arg1.getVariableId();
}
});
Collections.sort(constants, (arg0, arg1) -> arg0.getVariableId() - arg1.getVariableId());
// PART II: create values()
memberEntities.add(createEnumValuesMethod(typeBinding, constants, context));

View File

@ -82,103 +82,78 @@ public abstract class JavaIRTests extends IRTests {
@Test public void testTwoClasses() throws IllegalArgumentException, CancelException, IOException {
runTest(singleTestSrc(), rtJar, simpleTestEntryPoint(), Arrays.asList(
new IRAssertion() {
(IRAssertion) cg -> {
final String typeStr = singleInputForTest();
@Override
public void check(CallGraph cg) {
final String typeStr = singleInputForTest();
final TypeReference type = findOrCreateTypeReference("Source", typeStr, cg.getClassHierarchy());
final TypeReference type = findOrCreateTypeReference("Source", typeStr, cg.getClassHierarchy());
final IClass iClass = cg.getClassHierarchy().lookupClass(type);
Assert.assertNotNull("Could not find class " + typeStr, iClass);
final IClass iClass = cg.getClassHierarchy().lookupClass(type);
Assert.assertNotNull("Could not find class " + typeStr, iClass);
/*
Assert.assertEquals("Expected two classes.", iClass.getClassLoader().getNumberOfClasses(), 2);
/*
Assert.assertEquals("Expected two classes.", iClass.getClassLoader().getNumberOfClasses(), 2);
for (Iterator<IClass> it = iClass.getClassLoader().iterateAllClasses(); it.hasNext();) {
IClass cls = it.next();
for (Iterator<IClass> it = iClass.getClassLoader().iterateAllClasses(); it.hasNext();) {
IClass cls = it.next();
Assert.assertTrue("Expected class to be either " + typeStr + " or " + "Bar", cls.getName().getClassName().toString()
.equals(typeStr)
|| cls.getName().getClassName().toString().equals("Bar"));
}
*/
Assert.assertTrue("Expected class to be either " + typeStr + " or " + "Bar", cls.getName().getClassName().toString()
.equals(typeStr)
|| cls.getName().getClassName().toString().equals("Bar"));
}
*/
}), true);
}
@Test public void testInterfaceTest1() throws IllegalArgumentException, CancelException, IOException {
runTest(singleTestSrc(), rtJar, simpleTestEntryPoint(), Arrays.asList(
/**
* IFoo is an interface
*/
new IRAssertion() {
cg -> {
final String typeStr = "IFoo";
@Override
public void check(CallGraph cg) {
final String typeStr = "IFoo";
final TypeReference type = findOrCreateTypeReference("Source", typeStr, cg.getClassHierarchy());
final TypeReference type = findOrCreateTypeReference("Source", typeStr, cg.getClassHierarchy());
final IClass iClass = cg.getClassHierarchy().lookupClass(type);
Assert.assertNotNull("Could not find class " + typeStr, iClass);
final IClass iClass = cg.getClassHierarchy().lookupClass(type);
Assert.assertNotNull("Could not find class " + typeStr, iClass);
Assert.assertTrue("Expected IFoo to be an interface.", iClass.isInterface());
}
Assert.assertTrue("Expected IFoo to be an interface.", iClass.isInterface());
},
/**
* Foo implements IFoo
*/
new IRAssertion() {
cg -> {
final String typeStr = "FooIT1";
@Override
public void check(CallGraph cg) {
final String typeStr = "FooIT1";
final TypeReference type = findOrCreateTypeReference("Source", typeStr, cg.getClassHierarchy());
final TypeReference type = findOrCreateTypeReference("Source", typeStr, cg.getClassHierarchy());
final IClass iClass = cg.getClassHierarchy().lookupClass(type);
Assert.assertNotNull("Could not find class " + typeStr, iClass);
final IClass iClass = cg.getClassHierarchy().lookupClass(type);
Assert.assertNotNull("Could not find class " + typeStr, iClass);
final Collection<? extends IClass> interfaces = iClass.getDirectInterfaces();
final Collection<? extends IClass> interfaces = iClass.getDirectInterfaces();
Assert.assertEquals("Expected one single interface.", interfaces.size(), 1);
Assert.assertEquals("Expected one single interface.", interfaces.size(), 1);
Assert.assertTrue("Expected Foo to implement IFoo", interfaces.contains(cg.getClassHierarchy().lookupClass(
findOrCreateTypeReference("Source", "IFoo", cg.getClassHierarchy()))));
}
Assert.assertTrue("Expected Foo to implement IFoo", interfaces.contains(cg.getClassHierarchy().lookupClass(
findOrCreateTypeReference("Source", "IFoo", cg.getClassHierarchy()))));
}), true);
}
@Test public void testInheritance1() throws IllegalArgumentException, CancelException, IOException {
runTest(singleTestSrc(), rtJar, simpleTestEntryPoint(), Arrays.asList(
/**
* 'Derived' extends 'Base'
*/
new IRAssertion() {
(IRAssertion) cg -> {
final String typeStr = "Derived";
@Override
public void check(CallGraph cg) {
final String typeStr = "Derived";
final TypeReference type = findOrCreateTypeReference("Source", typeStr, cg.getClassHierarchy());
final TypeReference type = findOrCreateTypeReference("Source", typeStr, cg.getClassHierarchy());
final IClass derivedClass = cg.getClassHierarchy().lookupClass(type);
Assert.assertNotNull("Could not find class " + typeStr, derivedClass);
final IClass derivedClass = cg.getClassHierarchy().lookupClass(type);
Assert.assertNotNull("Could not find class " + typeStr, derivedClass);
final TypeReference baseType = findOrCreateTypeReference("Source", "Base", cg.getClassHierarchy());
final IClass baseClass = cg.getClassHierarchy().lookupClass(baseType);
final TypeReference baseType = findOrCreateTypeReference("Source", "Base", cg.getClassHierarchy());
final IClass baseClass = cg.getClassHierarchy().lookupClass(baseType);
Assert.assertTrue("Expected 'Base' to be the superclass of 'Derived'", derivedClass.getSuperclass().equals(baseClass));
Assert.assertTrue("Expected 'Base' to be the superclass of 'Derived'", derivedClass.getSuperclass().equals(baseClass));
Collection<IClass> subclasses = cg.getClassHierarchy().computeSubClasses(baseType);
Collection<IClass> subclasses = cg.getClassHierarchy().computeSubClasses(baseType);
Assert.assertTrue("Expected subclasses of 'Base' to be 'Base' and 'Derived'.", subclasses.contains(derivedClass)
&& subclasses.contains(baseClass));
}
Assert.assertTrue("Expected subclasses of 'Base' to be 'Base' and 'Derived'.", subclasses.contains(derivedClass)
&& subclasses.contains(baseClass));
}), true);
}
@ -214,80 +189,62 @@ public abstract class JavaIRTests extends IRTests {
@Test public void testArrayLiteral1() throws IllegalArgumentException, CancelException, IOException {
runTest(singleTestSrc(), rtJar, simpleTestEntryPoint(), Arrays.asList(
/**
* 'foo' has four array instructions: - 2 SSAArrayLengthInstruction - 1
* SSAArrayLoadInstruction - 1 SSAArrayStoreInstruction
*/
new IRAssertion() {
(IRAssertion) cg -> {
@Override
public void check(CallGraph cg) {
MethodReference mref = descriptorToMethodRef("Source#ArrayLiteral1#main#([Ljava/lang/String;)V", cg.getClassHierarchy());
CGNode node = cg.getNodes(mref).iterator().next();
SSAInstruction s = node.getIR().getInstructions()[2];
Assert.assertTrue("Did not find new array instruction.", s instanceof SSANewInstruction);
Assert.assertTrue("", ((SSANewInstruction) s).getNewSite().getDeclaredType().isArrayType());
}
MethodReference mref = descriptorToMethodRef("Source#ArrayLiteral1#main#([Ljava/lang/String;)V", cg.getClassHierarchy());
CGNode node = cg.getNodes(mref).iterator().next();
SSAInstruction s = node.getIR().getInstructions()[2];
Assert.assertTrue("Did not find new array instruction.", s instanceof SSANewInstruction);
Assert.assertTrue("", ((SSANewInstruction) s).getNewSite().getDeclaredType().isArrayType());
}), true);
}
@Test public void testArrayLiteral2() throws IllegalArgumentException, CancelException, IOException {
runTest(singleTestSrc(), rtJar, simpleTestEntryPoint(), Arrays.asList(
/**
* int[] y= { 1, 2, 3, 4 } is represented in the IR as four array store
* instructions
*/
new IRAssertion() {
(IRAssertion) cg -> {
@Override
public void check(CallGraph cg) {
MethodReference mref = descriptorToMethodRef("Source#ArrayLiteral2#main#([Ljava/lang/String;)V", cg.getClassHierarchy());
MethodReference mref = descriptorToMethodRef("Source#ArrayLiteral2#main#([Ljava/lang/String;)V", cg.getClassHierarchy());
CGNode node = cg.getNodes(mref).iterator().next();
CGNode node = cg.getNodes(mref).iterator().next();
final SSAInstruction[] instructions = node.getIR().getInstructions();
// test 1
{
SSAInstruction s1 = instructions[2];
if (s1 instanceof SSANewInstruction) {
Assert.assertTrue("", ((SSANewInstruction) s1).getNewSite().getDeclaredType().isArrayType());
} else {
Assert.assertTrue("Expected 3rd to be a new array instruction.", false);
}
}
// test 2
{
SSAInstruction s2 = instructions[3];
if (s2 instanceof SSANewInstruction) {
Assert.assertTrue("", ((SSANewInstruction) s2).getNewSite().getDeclaredType().isArrayType());
} else {
Assert.assertTrue("Expected 4th to be a new array instruction.", false);
}
}
// test 3: the last 4 instructions are of the form y[i] = i+1;
{
final SymbolTable symbolTable = node.getIR().getSymbolTable();
for (int i = 4; i <= 7; i++) {
Assert.assertTrue("Expected only array stores.", instructions[i] instanceof SSAArrayStoreInstruction);
SSAArrayStoreInstruction as = (SSAArrayStoreInstruction) instructions[i];
Assert.assertEquals("Expected an array store to 'y'.", node.getIR().getLocalNames(i, as.getArrayRef())[0], "y");
final Integer valueOfArrayIndex = ((Integer) symbolTable.getConstantValue(as.getIndex()));
final Integer valueAssigned = (Integer) symbolTable.getConstantValue(as.getValue());
Assert.assertEquals("Expected an array store to 'y' with value " + (valueOfArrayIndex + 1), valueAssigned.intValue(),
valueOfArrayIndex + 1);
}
final SSAInstruction[] instructions = node.getIR().getInstructions();
// test 1
{
SSAInstruction s1 = instructions[2];
if (s1 instanceof SSANewInstruction) {
Assert.assertTrue("", ((SSANewInstruction) s1).getNewSite().getDeclaredType().isArrayType());
} else {
Assert.assertTrue("Expected 3rd to be a new array instruction.", false);
}
}
// test 2
{
SSAInstruction s2 = instructions[3];
if (s2 instanceof SSANewInstruction) {
Assert.assertTrue("", ((SSANewInstruction) s2).getNewSite().getDeclaredType().isArrayType());
} else {
Assert.assertTrue("Expected 4th to be a new array instruction.", false);
}
}
// test 3: the last 4 instructions are of the form y[i] = i+1;
{
final SymbolTable symbolTable = node.getIR().getSymbolTable();
for (int i = 4; i <= 7; i++) {
Assert.assertTrue("Expected only array stores.", instructions[i] instanceof SSAArrayStoreInstruction);
SSAArrayStoreInstruction as = (SSAArrayStoreInstruction) instructions[i];
Assert.assertEquals("Expected an array store to 'y'.", node.getIR().getLocalNames(i, as.getArrayRef())[0], "y");
final Integer valueOfArrayIndex = ((Integer) symbolTable.getConstantValue(as.getIndex()));
final Integer valueAssigned = (Integer) symbolTable.getConstantValue(as.getValue());
Assert.assertEquals("Expected an array store to 'y' with value " + (valueOfArrayIndex + 1), valueAssigned.intValue(),
valueOfArrayIndex + 1);
}
}
}), true);
}
@ -299,53 +256,41 @@ public abstract class JavaIRTests extends IRTests {
@Test public void testQualifiedStatic() throws IllegalArgumentException, CancelException, IOException {
runTest(singleTestSrc(), rtJar, simpleTestEntryPoint(), Arrays.asList(
/**
*
*/
new IRAssertion() {
(IRAssertion) cg -> {
@Override
public void check(CallGraph cg) {
MethodReference mref = descriptorToMethodRef("Source#QualifiedStatic#main#([Ljava/lang/String;)V", cg.getClassHierarchy());
MethodReference mref = descriptorToMethodRef("Source#QualifiedStatic#main#([Ljava/lang/String;)V", cg.getClassHierarchy());
CGNode node = cg.getNodes(mref).iterator().next();
SSAInstruction s = node.getIR().getInstructions()[4];
Assert.assertTrue("Did not find a getstatic instruction.", s instanceof SSAGetInstruction
&& ((SSAGetInstruction) s).isStatic());
final FieldReference field = ((SSAGetInstruction) s).getDeclaredField();
Assert.assertEquals("Expected a getstatic for 'value'.", field.getName().toString(), "value");
Assert.assertEquals("Expected a getstatic for 'value'.", field.getDeclaringClass().getName().toString(), "LFooQ");
}
CGNode node = cg.getNodes(mref).iterator().next();
SSAInstruction s = node.getIR().getInstructions()[4];
Assert.assertTrue("Did not find a getstatic instruction.", s instanceof SSAGetInstruction
&& ((SSAGetInstruction) s).isStatic());
final FieldReference field = ((SSAGetInstruction) s).getDeclaredField();
Assert.assertEquals("Expected a getstatic for 'value'.", field.getName().toString(), "value");
Assert.assertEquals("Expected a getstatic for 'value'.", field.getDeclaringClass().getName().toString(), "LFooQ");
}), true);
}
@Test public void testStaticNesting() throws IllegalArgumentException, CancelException, IOException {
runTest(singleTestSrc(), rtJar, simpleTestEntryPoint(), Arrays.asList(
new IRAssertion() {
(IRAssertion) cg -> {
final String typeStr = singleInputForTest() + "$WhatsIt";
@Override
public void check(CallGraph cg) {
final String typeStr = singleInputForTest() + "$WhatsIt";
final TypeReference type = findOrCreateTypeReference("Source", typeStr, cg.getClassHierarchy());
final TypeReference type = findOrCreateTypeReference("Source", typeStr, cg.getClassHierarchy());
final IClass iClass = cg.getClassHierarchy().lookupClass(type);
Assert.assertNotNull("Could not find class " + typeStr, iClass);
final IClass iClass = cg.getClassHierarchy().lookupClass(type);
Assert.assertNotNull("Could not find class " + typeStr, iClass);
// todo: this fails: Assert.assertNotNull("Expected to be enclosed in
// 'StaticNesting'.",
// ((JavaSourceLoaderImpl.JavaClass)iClass).getEnclosingClass());
// todo: is there the concept of CompilationUnit?
// todo: this fails: Assert.assertNotNull("Expected to be enclosed in
// 'StaticNesting'.",
// ((JavaSourceLoaderImpl.JavaClass)iClass).getEnclosingClass());
// todo: is there the concept of CompilationUnit?
/**
* {@link JavaCAst2IRTranslator#getEnclosingType} return null for static
* inner classes..?
*/
}
/**
* {@link JavaCAst2IRTranslator#getEnclosingType} return null for static
* inner classes..?
*/
}), true);
}
@ -356,21 +301,17 @@ public abstract class JavaIRTests extends IRTests {
@Test public void testInnerClass() throws IllegalArgumentException, CancelException, IOException {
runTest(singleTestSrc(), rtJar, simpleTestEntryPoint(), Arrays.asList(
new IRAssertion() {
(IRAssertion) cg -> {
final String typeStr = singleInputForTest();
@Override
public void check(CallGraph cg) {
final String typeStr = singleInputForTest();
final TypeReference type = findOrCreateTypeReference("Source", typeStr + "$WhatsIt", cg.getClassHierarchy());
final TypeReference type = findOrCreateTypeReference("Source", typeStr + "$WhatsIt", cg.getClassHierarchy());
final IClass iClass = cg.getClassHierarchy().lookupClass(type);
Assert.assertNotNull("Could not find class " + typeStr, iClass);
final IClass iClass = cg.getClassHierarchy().lookupClass(type);
Assert.assertNotNull("Could not find class " + typeStr, iClass);
Assert.assertEquals("Expected to be enclosed in 'InnerClass'.", ((JavaSourceLoaderImpl.JavaClass) iClass)
.getEnclosingClass(), // todo is there another way?
cg.getClassHierarchy().lookupClass(findOrCreateTypeReference("Source", typeStr, cg.getClassHierarchy())));
}
Assert.assertEquals("Expected to be enclosed in 'InnerClass'.", ((JavaSourceLoaderImpl.JavaClass) iClass)
.getEnclosingClass(), // todo is there another way?
cg.getClassHierarchy().lookupClass(findOrCreateTypeReference("Source", typeStr, cg.getClassHierarchy())));
}), true);
}
@ -471,61 +412,49 @@ public abstract class JavaIRTests extends IRTests {
@Test public void testLocalClass() throws IllegalArgumentException, CancelException, IOException {
runTest(singleTestSrc(), rtJar, simpleTestEntryPoint(), Arrays.asList(
new IRAssertion() {
(IRAssertion) cg -> {
final String typeStr = singleInputForTest();
final String localClassStr = "Foo";
/**
* Classes local to method are enclosed in the class the methods belong
* to.
*/
@Override
public void check(CallGraph cg) {
final String typeStr = singleInputForTest();
final String localClassStr = "Foo";
// Observe the descriptor for a class local to a method.
final TypeReference mainFooType = findOrCreateTypeReference("Source", typeStr + "/main([Ljava/lang/String;)V/"
+ localClassStr, cg.getClassHierarchy());
// Observe the descriptor for a class local to a method.
final TypeReference mainFooType = findOrCreateTypeReference("Source", typeStr + "/main([Ljava/lang/String;)V/"
+ localClassStr, cg.getClassHierarchy());
// Observe the descriptor for a class local to a method.
final IClass mainFooClass = cg.getClassHierarchy().lookupClass(mainFooType);
Assert.assertNotNull("Could not find class " + mainFooType, mainFooClass);
// Observe the descriptor for a class local to a method.
final IClass mainFooClass = cg.getClassHierarchy().lookupClass(mainFooType);
Assert.assertNotNull("Could not find class " + mainFooType, mainFooClass);
final TypeReference methodFooType = findOrCreateTypeReference("Source", typeStr + "/method()V/" + localClassStr, cg
.getClassHierarchy());
final TypeReference methodFooType = findOrCreateTypeReference("Source", typeStr + "/method()V/" + localClassStr, cg
.getClassHierarchy());
final IClass methodFooClass = cg.getClassHierarchy().lookupClass(methodFooType);
Assert.assertNotNull("Could not find class " + methodFooType, methodFooClass);
final IClass methodFooClass = cg.getClassHierarchy().lookupClass(methodFooType);
Assert.assertNotNull("Could not find class " + methodFooType, methodFooClass);
final IClass localClass = cg.getClassHierarchy().lookupClass(
findOrCreateTypeReference("Source", typeStr, cg.getClassHierarchy()));
final IClass localClass = cg.getClassHierarchy().lookupClass(
findOrCreateTypeReference("Source", typeStr, cg.getClassHierarchy()));
Assert.assertSame("'Foo' is enclosed in 'Local'", ((JavaSourceLoaderImpl.JavaClass) methodFooClass).getEnclosingClass(),
localClass);
// todo: is this failing because 'main' is static?
// Assert.assertSame("'Foo' is enclosed in 'Local'",
// ((JavaSourceLoaderImpl.JavaClass)mainFooClass).getEnclosingClass(),
// localClass);
}
Assert.assertSame("'Foo' is enclosed in 'Local'", ((JavaSourceLoaderImpl.JavaClass) methodFooClass).getEnclosingClass(),
localClass);
// todo: is this failing because 'main' is static?
// Assert.assertSame("'Foo' is enclosed in 'Local'",
// ((JavaSourceLoaderImpl.JavaClass)mainFooClass).getEnclosingClass(),
// localClass);
}), true);
}
@Test public void testAnonymousClass() throws IllegalArgumentException, CancelException, IOException {
runTest(singleTestSrc(), rtJar, simpleTestEntryPoint(), Arrays.asList(
new IRAssertion() {
(IRAssertion) cg -> {
final String typeStr = singleInputForTest();
@Override
public void check(CallGraph cg) {
final String typeStr = singleInputForTest();
final TypeReference type = findOrCreateTypeReference("Source", typeStr, cg.getClassHierarchy());
final TypeReference type = findOrCreateTypeReference("Source", typeStr, cg.getClassHierarchy());
final IClass iClass = cg.getClassHierarchy().lookupClass(type);
Assert.assertNotNull("Could not find class " + typeStr, iClass);
final IClass iClass = cg.getClassHierarchy().lookupClass(type);
Assert.assertNotNull("Could not find class " + typeStr, iClass);
// todo what to check?? could not find anything in the APIs for
// anonymous
}
// todo what to check?? could not find anything in the APIs for
// anonymous
}), true);
}

View File

@ -34,7 +34,6 @@ import com.ibm.wala.ipa.cha.ClassHierarchyException;
import com.ibm.wala.ipa.cha.ClassHierarchyFactory;
import com.ibm.wala.ipa.cha.IClassHierarchy;
import com.ibm.wala.ssa.SSAOptions;
import com.ibm.wala.ssa.SymbolTable;
import com.ibm.wala.types.ClassLoaderReference;
import com.ibm.wala.util.collections.HashSetFactory;
import com.ibm.wala.util.config.FileOfClasses;
@ -159,12 +158,7 @@ public abstract class JavaSourceAnalysisEngine<I extends InstanceKey> extends Ab
AnalysisOptions options = new AnalysisOptions(getScope(), entrypoints);
SSAOptions ssaOptions = new SSAOptions();
ssaOptions.setDefaultValues(new SSAOptions.DefaultValues() {
@Override
public int getDefaultValue(SymbolTable symtab, int valueNumber) {
return symtab.getDefaultValue(valueNumber);
}
});
ssaOptions.setDefaultValues((symtab, valueNumber) -> symtab.getDefaultValue(valueNumber));
options.setSSAOptions(ssaOptions);

View File

@ -37,7 +37,6 @@ import com.ibm.wala.ssa.SSANewInstruction;
import com.ibm.wala.ssa.SymbolTable;
import com.ibm.wala.types.MethodReference;
import com.ibm.wala.util.debug.Assertions;
import com.ibm.wala.util.intset.IntSetAction;
import com.ibm.wala.util.strings.Atom;
public class AstJavaSSAPropagationCallGraphBuilder extends AstSSAPropagationCallGraphBuilder {
@ -184,13 +183,10 @@ public class AstJavaSSAPropagationCallGraphBuilder extends AstSSAPropagationCall
public byte evaluate(PointsToSetVariable lhs, PointsToSetVariable rhs) {
IntSetVariable<?> tv = rhs;
if (tv.getValue() != null) {
tv.getValue().foreach(new IntSetAction() {
@Override
public void act(int ptr) {
InstanceKey iKey = system.getInstanceKey(ptr);
PointerKey enclosing = new EnclosingObjectReferenceKey(iKey, cls);
system.newConstraint(lvalKey, assignOperator, enclosing);
}
tv.getValue().foreach(ptr -> {
InstanceKey iKey = system.getInstanceKey(ptr);
PointerKey enclosing = new EnclosingObjectReferenceKey(iKey, cls);
system.newConstraint(lvalKey, assignOperator, enclosing);
});
}
return NOT_CHANGED;

View File

@ -76,35 +76,19 @@ public class AstJavaSlicer extends Slicer {
}
public static Set<Statement> gatherAssertions(CallGraph CG, Collection<CGNode> partialRoots) {
return gatherStatements(CG, partialRoots, new Predicate<SSAInstruction>() {
@Override public boolean test(SSAInstruction o) {
return o instanceof AstAssertInstruction;
}
});
return gatherStatements(CG, partialRoots, o -> o instanceof AstAssertInstruction);
}
public static Set<Statement> gatherMonitors(CallGraph CG, Collection<CGNode> partialRoots) {
return gatherStatements(CG, partialRoots, new Predicate<SSAInstruction>() {
@Override public boolean test(SSAInstruction o) {
return o instanceof SSAMonitorInstruction;
}
});
return gatherStatements(CG, partialRoots, o -> o instanceof SSAMonitorInstruction);
}
public static Set<Statement> gatherWrites(CallGraph CG, Collection<CGNode> partialRoots) {
return gatherStatements(CG, partialRoots, new Predicate<SSAInstruction>() {
@Override public boolean test(SSAInstruction o) {
return (o instanceof SSAPutInstruction) || (o instanceof SSAArrayStoreInstruction);
}
});
return gatherStatements(CG, partialRoots, o -> (o instanceof SSAPutInstruction) || (o instanceof SSAArrayStoreInstruction));
}
public static Set<Statement> gatherReads(CallGraph CG, Collection<CGNode> partialRoots) {
return gatherStatements(CG, partialRoots, new Predicate<SSAInstruction>() {
@Override public boolean test(SSAInstruction o) {
return (o instanceof SSAGetInstruction) || (o instanceof SSAArrayLoadInstruction);
}
});
return gatherStatements(CG, partialRoots, o -> (o instanceof SSAGetInstruction) || (o instanceof SSAArrayLoadInstruction));
}
public static Pair<Collection<Statement>, SDG<InstanceKey>> computeAssertionSlice(CallGraph CG, PointerAnalysis<InstanceKey> pa,

View File

@ -78,28 +78,22 @@ public class JavaJavaScriptHybridCallGraphBuilder extends CrossLanguageSSAPropag
@Override
protected TargetLanguageSelector<ConstraintVisitor, CGNode> makeMainVisitorSelector() {
return new TargetLanguageSelector<ConstraintVisitor, CGNode>() {
@Override
public ConstraintVisitor get(Atom language, CGNode construct) {
if (JavaScriptTypes.jsName.equals(language)) {
return new JSConstraintVisitor(JavaJavaScriptHybridCallGraphBuilder.this, construct);
} else {
return new ConstraintVisitor(JavaJavaScriptHybridCallGraphBuilder.this, construct);
}
return (language, construct) -> {
if (JavaScriptTypes.jsName.equals(language)) {
return new JSConstraintVisitor(JavaJavaScriptHybridCallGraphBuilder.this, construct);
} else {
return new ConstraintVisitor(JavaJavaScriptHybridCallGraphBuilder.this, construct);
}
};
}
@Override
protected TargetLanguageSelector<InterestingVisitor, Integer> makeInterestingVisitorSelector() {
return new TargetLanguageSelector<InterestingVisitor, Integer>() {
@Override
public InterestingVisitor get(Atom language, Integer construct) {
if (JavaScriptTypes.jsName.equals(language)) {
return new JSInterestingVisitor(construct);
} else {
return new InterestingVisitor(construct);
}
return (language, construct) -> {
if (JavaScriptTypes.jsName.equals(language)) {
return new JSInterestingVisitor(construct);
} else {
return new InterestingVisitor(construct);
}
};
}
@ -107,28 +101,22 @@ public class JavaJavaScriptHybridCallGraphBuilder extends CrossLanguageSSAPropag
@Override
protected TargetLanguageSelector<AstImplicitPointsToSetVisitor, LocalPointerKey> makeImplicitVisitorSelector(
CrossLanguagePointerAnalysisImpl analysis) {
return new TargetLanguageSelector<AstImplicitPointsToSetVisitor, LocalPointerKey>() {
@Override
public AstImplicitPointsToSetVisitor get(Atom language, LocalPointerKey construct) {
if (JavaScriptTypes.jsName.equals(language)) {
return new JSImplicitPointsToSetVisitor((AstPointerAnalysisImpl) getPointerAnalysis(), construct);
} else {
return new AstImplicitPointsToSetVisitor((AstPointerAnalysisImpl) getPointerAnalysis(), construct);
}
return (language, construct) -> {
if (JavaScriptTypes.jsName.equals(language)) {
return new JSImplicitPointsToSetVisitor((AstPointerAnalysisImpl) getPointerAnalysis(), construct);
} else {
return new AstImplicitPointsToSetVisitor((AstPointerAnalysisImpl) getPointerAnalysis(), construct);
}
};
}
@Override
protected TargetLanguageSelector<AbstractRootMethod, CrossLanguageCallGraph> makeRootNodeSelector() {
return new TargetLanguageSelector<AbstractRootMethod, CrossLanguageCallGraph>() {
@Override
public AbstractRootMethod get(Atom language, CrossLanguageCallGraph construct) {
if (JavaScriptTypes.jsName.equals(language)) {
return new JSFakeRoot(getClassHierarchy(), getOptions(), getAnalysisCache());
} else {
return new FakeRootMethod(getClassHierarchy(), getOptions(), getAnalysisCache());
}
return (language, construct) -> {
if (JavaScriptTypes.jsName.equals(language)) {
return new JSFakeRoot(getClassHierarchy(), getOptions(), getAnalysisCache());
} else {
return new FakeRootMethod(getClassHierarchy(), getOptions(), getAnalysisCache());
}
};
}

View File

@ -58,13 +58,7 @@ public class PrintIRs {
JSCallGraphUtil.setTranslatorFactory(new CAstRhinoTranslatorFactory());
// build a class hierarchy, for access to code info
IClassHierarchy cha = JSCallGraphUtil.makeHierarchyForScripts(filename);
printIRsForCHA(cha, new Predicate<String>() {
@Override
public boolean test(String t) {
return t.startsWith("Lprologue.js");
}
});
printIRsForCHA(cha, t -> t.startsWith("Lprologue.js"));
}
protected static void printIRsForCHA(IClassHierarchy cha, Predicate<String> exclude) {
@ -101,13 +95,7 @@ public class PrintIRs {
CAstAnalysisScope scope = new CAstAnalysisScope(scripts, loaders, Collections.singleton(JavaScriptLoader.JS));
IClassHierarchy cha = ClassHierarchyFactory.make(scope, loaders, JavaScriptLoader.JS);
com.ibm.wala.cast.util.Util.checkForFrontEndErrors(cha);
printIRsForCHA(cha, new Predicate<String>() {
@Override
public boolean test(String t) {
return t.startsWith("Lprologue.js") || t.startsWith("Lpreamble.js");
}
});
printIRsForCHA(cha, t -> t.startsWith("Lprologue.js") || t.startsWith("Lpreamble.js"));
}
/**

View File

@ -17,7 +17,6 @@ import org.junit.Test;
import com.ibm.wala.cast.js.html.DefaultSourceExtractor;
import com.ibm.wala.cast.js.html.IHtmlParser;
import com.ibm.wala.cast.js.html.IHtmlParserFactory;
import com.ibm.wala.cast.js.html.JSSourceExtractor;
import com.ibm.wala.cast.js.html.WebUtil;
import com.ibm.wala.cast.js.ipa.callgraph.JSCFABuilder;
@ -58,12 +57,7 @@ public abstract class TestSimplePageCallGraphShapeRhino extends TestSimplePageCa
@Before
public void setUp() {
com.ibm.wala.cast.js.ipa.callgraph.JSCallGraphUtil.setTranslatorFactory(new CAstRhinoTranslatorFactory());
WebUtil.setFactory(new IHtmlParserFactory() {
@Override
public IHtmlParser getParser() {
return TestSimplePageCallGraphShapeRhino.this.getParser();
}
});
WebUtil.setFactory(() -> TestSimplePageCallGraphShapeRhino.this.getParser());
JSSourceExtractor.USE_TEMP_NAME = false;
// JSSourceExtractor.DELETE_UPON_EXIT = false;
}

View File

@ -19,7 +19,6 @@ import static com.ibm.wala.cast.tree.CAstNode.EMPTY;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.Map;
import java.util.Map.Entry;
@ -99,12 +98,7 @@ public class CAstDumper {
scopedEntities.add(scopedEntity);
m.put(scopedEntity, e.getKey());
}
Collections.sort(scopedEntities, new Comparator<CAstEntity>() {
@Override
public int compare(CAstEntity o1, CAstEntity o2) {
return o1.getName().compareTo(o2.getName());
}
});
Collections.sort(scopedEntities, (o1, o2) -> o1.getName().compareTo(o2.getName()));
buf.append(indent(indent) + "> ");
boolean first = true;

View File

@ -33,7 +33,6 @@ import com.ibm.wala.ipa.slicer.Statement;
import com.ibm.wala.util.CancelException;
import com.ibm.wala.util.WalaException;
import com.ibm.wala.util.collections.HashSetFactory;
import com.ibm.wala.util.intset.IntSetAction;
public abstract class TestJavaScriptSlicer extends TestJSCallGraphShape {
@ -89,12 +88,7 @@ public abstract class TestJavaScriptSlicer extends TestJSCallGraphShape {
for(Iterator<CGNode> callers = CG.getPredNodes(n); callers.hasNext(); ) {
final CGNode caller = callers.next();
for(Iterator<CallSiteReference> sites = CG.getPossibleSites(caller, n); sites.hasNext(); ) {
caller.getIR().getCallInstructionIndices(sites.next()).foreach(new IntSetAction() {
@Override
public void act(int x) {
ss.add(new NormalStatement(caller, x));
}
});
caller.getIR().getCallInstructionIndices(sites.next()).foreach(x -> ss.add(new NormalStatement(caller, x)));
}
}
}

View File

@ -333,23 +333,15 @@ public abstract class TestPointerAnalyses {
CallGraph CG,
CGNode node,
int vn) {
return getPrototypeSites(fbPA, CG, new Function<ObjectVertex,Iterator<ObjectVertex>>() {
@Override
public Iterator<ObjectVertex> apply(ObjectVertex o) {
PrototypeFieldVertex proto = new PrototypeFieldVertex(PrototypeField.__proto__, o);
if (hg.containsNode(proto)) {
return
new MapIterator<>(hg.getSuccNodes(proto),
new Function<Object,ObjectVertex>() {
@Override
public ObjectVertex apply(Object object) {
return (ObjectVertex)object;
}
});
} else {
return EmptyIterator.instance();
}
}
return getPrototypeSites(fbPA, CG, o -> {
PrototypeFieldVertex proto = new PrototypeFieldVertex(PrototypeField.__proto__, o);
if (hg.containsNode(proto)) {
return
new MapIterator<>(hg.getSuccNodes(proto),
object -> (ObjectVertex)object);
} else {
return EmptyIterator.instance();
}
}, node, vn);
}
@ -357,12 +349,7 @@ public abstract class TestPointerAnalyses {
CallGraph CG,
CGNode node,
int vn) {
return getPrototypeSites(fbPA, CG, new Function<InstanceKey,Iterator<InstanceKey>>() {
@Override
public Iterator<InstanceKey> apply(InstanceKey o) {
return fbPA.getPointsToSet(new TransitivePrototypeKey(o)).iterator();
}
}, node, vn);
return getPrototypeSites(fbPA, CG, o -> fbPA.getPointsToSet(new TransitivePrototypeKey(o)).iterator(), node, vn);
}
private void testPageUserCodeEquivalent(URL page) throws WalaException, CancelException {
@ -371,13 +358,10 @@ public abstract class TestPointerAnalyses {
}
protected Predicate<MethodReference> nameFilter(final String name) {
return new Predicate<MethodReference>() {
@Override
public boolean test(MethodReference t) {
System.err.println(t + " " + name);
return t.getSelector().equals(AstMethodReference.fnSelector) &&
t.getDeclaringClass().getName().toString().startsWith("L" + name);
}
return t -> {
System.err.println(t + " " + name);
return t.getSelector().equals(AstMethodReference.fnSelector) &&
t.getDeclaringClass().getName().toString().startsWith("L" + name);
};
}

View File

@ -14,7 +14,6 @@ import java.util.Collection;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.function.Predicate;
import com.ibm.wala.analysis.pointers.HeapGraph;
import com.ibm.wala.cast.ipa.callgraph.AstHeapModel;
@ -106,32 +105,23 @@ public class FlowGraph implements Iterable<Vertex> {
private static <T> GraphReachability<Vertex, T> computeClosure(NumberedGraph<Vertex> graph, IProgressMonitor monitor, final Class<?> type) throws CancelException {
// prune flowgraph by taking out 'unknown' vertex
Graph<Vertex> pruned_flowgraph = GraphSlicer.prune(graph, new Predicate<Vertex>() {
@Override
public boolean test(Vertex t) {
return t.accept(new AbstractVertexVisitor<Boolean>() {
@Override
public Boolean visitVertex() {
return true;
}
@Override
public Boolean visitUnknownVertex(UnknownVertex unknownVertex) {
return false;
}
});
}
});
Graph<Vertex> pruned_flowgraph = GraphSlicer.prune(graph, t -> t.accept(new AbstractVertexVisitor<Boolean>() {
@Override
public Boolean visitVertex() {
return true;
}
@Override
public Boolean visitUnknownVertex(UnknownVertex unknownVertex) {
return false;
}
}));
// compute transitive closure
GraphReachability<Vertex, T> optimistic_closure =
new GraphReachability<>(
new InvertedGraph<>(pruned_flowgraph),
new Predicate<Vertex>() {
@Override public boolean test(Vertex o) {
return type.isInstance(o);
}
}
o -> type.isInstance(o)
);
optimistic_closure.solve(monitor);
@ -285,15 +275,10 @@ public class FlowGraph implements Iterable<Vertex> {
@Override
public Iterable<PointerKey> getPointerKeys() {
return new Iterable<PointerKey> () {
@Override
public Iterator<PointerKey> iterator() {
return new CompoundIterator<>(factory.getArgVertices().iterator(),
new CompoundIterator<>(factory.getRetVertices().iterator(),
new CompoundIterator<PointerKey>(factory.getVarVertices().iterator(),
factory.getPropVertices().iterator())));
}
};
return () -> new CompoundIterator<>(factory.getArgVertices().iterator(),
new CompoundIterator<>(factory.getRetVertices().iterator(),
new CompoundIterator<PointerKey>(factory.getVarVertices().iterator(),
factory.getPropVertices().iterator())));
}
@Override
@ -548,11 +533,7 @@ public class FlowGraph implements Iterable<Vertex> {
@Override
public Collection<Object> getReachableInstances(Set<Object> roots) {
return DFS.getReachableNodes(this, roots, new Predicate<Object>() {
@Override public boolean test(Object o) {
return o instanceof ObjectVertex;
}
});
return DFS.getReachableNodes(this, roots, o -> o instanceof ObjectVertex);
}
@Override

View File

@ -27,12 +27,7 @@ import com.ibm.wala.util.collections.Pair;
public class DefaultSourceExtractor extends DomLessSourceExtractor{
public static Supplier<JSSourceExtractor> factory = new Supplier<JSSourceExtractor>() {
@Override
public JSSourceExtractor get() {
return new DefaultSourceExtractor();
}
};
public static Supplier<JSSourceExtractor> factory = () -> new DefaultSourceExtractor();
protected static class HtmlCallBack extends DomLessSourceExtractor.HtmlCallback{

View File

@ -42,12 +42,7 @@ public class DomLessSourceExtractor extends JSSourceExtractor {
private static final Pattern LEGAL_JS_IDENTIFIER_REGEXP = Pattern.compile("^[a-zA-Z$_][a-zA-Z\\d$_]*$");
private static final Pattern LEGAL_JS_KEYWORD_REGEXP = Pattern.compile("^((break)|(case)|(catch)|(continue)|(debugger)|(default)|(delete)|(do)|(else)|(finally)|(for)|(function)|(if)|(in)|(instanceof)|(new)|(return)|(switch)|(this)|(throw)|(try)|(typeof)|(var)|(void)|(while)|(with))$");
public static Supplier<JSSourceExtractor> factory = new Supplier<JSSourceExtractor>() {
@Override
public JSSourceExtractor get() {
return new DomLessSourceExtractor();
}
};
public static Supplier<JSSourceExtractor> factory = () -> new DomLessSourceExtractor();
protected interface IGeneratorCallback extends IHtmlCallback {
void writeToFinalRegion(SourceRegion finalRegion);

View File

@ -28,12 +28,7 @@ public class WebUtil {
public static final String preamble = "preamble.js";
private static IHtmlParserFactory factory = new IHtmlParserFactory() {
@Override
public IHtmlParser getParser() {
return new JerichoHtmlParser();
}
};
private static IHtmlParserFactory factory = () -> new JerichoHtmlParser();
public static void setFactory(IHtmlParserFactory factory) {
WebUtil.factory = factory;

View File

@ -601,23 +601,20 @@ public class JSSSAPropagationCallGraphBuilder extends AstSSAPropagationCallGraph
@Override
public byte evaluate(PointsToSetVariable lhs, PointsToSetVariable ptrs) {
if (ptrs.getValue() != null) {
ptrs.getValue().foreachExcluding(previous, new IntSetAction() {
@Override
public void act(int x) {
final InstanceKey functionObj = system.getInstanceKey(x);
visitInvokeInternal(instruction, new DefaultInvariantComputer() {
@Override
public InstanceKey[][] computeInvariantParameters(SSAAbstractInvokeInstruction call) {
InstanceKey[][] x = super.computeInvariantParameters(call);
if (x == null) {
x = new InstanceKey[call.getNumberOfUses()][];
}
x[0] = new InstanceKey[]{ functionObj };
x[1] = new InstanceKey[]{ receiverType };
return x;
ptrs.getValue().foreachExcluding(previous, x -> {
final InstanceKey functionObj = system.getInstanceKey(x);
visitInvokeInternal(instruction, new DefaultInvariantComputer() {
@Override
public InstanceKey[][] computeInvariantParameters(SSAAbstractInvokeInstruction call) {
InstanceKey[][] x = super.computeInvariantParameters(call);
if (x == null) {
x = new InstanceKey[call.getNumberOfUses()][];
}
});
}
x[0] = new InstanceKey[]{ functionObj };
x[1] = new InstanceKey[]{ receiverType };
return x;
}
});
});
previous.addAll(ptrs.getValue());
}
@ -682,17 +679,14 @@ public class JSSSAPropagationCallGraphBuilder extends AstSSAPropagationCallGraph
@Override
public byte evaluate(PointsToSetVariable lhs, PointsToSetVariable rhs) {
if (rhs.getValue() != null) {
rhs.getValue().foreachExcluding(previous, new IntSetAction() {
@Override
public void act(int x) {
try {
MonitorUtil.throwExceptionIfCanceled(getBuilder().monitor);
} catch (CancelException e) {
throw new CancelRuntimeException(e);
}
InstanceKey ik = system.getInstanceKey(x);
handleJavascriptDispatch(instruction, ik);
rhs.getValue().foreachExcluding(previous, x -> {
try {
MonitorUtil.throwExceptionIfCanceled(getBuilder().monitor);
} catch (CancelException e) {
throw new CancelRuntimeException(e);
}
InstanceKey ik = system.getInstanceKey(x);
handleJavascriptDispatch(instruction, ik);
});
previous.addAll(rhs.getValue());
}
@ -775,12 +769,7 @@ public class JSSSAPropagationCallGraphBuilder extends AstSSAPropagationCallGraph
return new InstanceKey[0];
} else {
final Set<InstanceKey> temp = HashSetFactory.make();
v.getValue().foreach(new IntSetAction() {
@Override
public void act(int keyIndex) {
temp.add(system.getInstanceKey(keyIndex));
}
});
v.getValue().foreach(keyIndex -> temp.add(system.getInstanceKey(keyIndex)));
return temp.toArray(new InstanceKey[temp.size()]);
}

View File

@ -13,10 +13,6 @@ package com.ibm.wala.cast.js.translator;
import com.ibm.wala.cast.ir.translator.TranslatorToCAst;
import com.ibm.wala.cast.tree.CAst;
import com.ibm.wala.cast.tree.rewrite.AstLoopUnwinder;
import com.ibm.wala.cast.tree.rewrite.AstLoopUnwinder.UnwindKey;
import com.ibm.wala.cast.tree.rewrite.CAstRewriter;
import com.ibm.wala.cast.tree.rewrite.CAstRewriter.RewriteContext;
import com.ibm.wala.cast.tree.rewrite.CAstRewriterFactory;
import com.ibm.wala.classLoader.ModuleEntry;
import com.ibm.wala.classLoader.SourceFileModule;
import com.ibm.wala.classLoader.SourceModule;
@ -46,12 +42,7 @@ public abstract class JavaScriptLoopUnwindingTranslatorFactory
}
TranslatorToCAst xlator = translateInternal(ast, (SourceModule)M, N);
xlator.addRewriter(new CAstRewriterFactory<CAstRewriter.RewriteContext<AstLoopUnwinder.UnwindKey>,AstLoopUnwinder.UnwindKey>() {
@Override
public CAstRewriter<RewriteContext<UnwindKey>, UnwindKey> createCAstRewriter(CAst ast) {
return new AstLoopUnwinder(ast, true, unwindFactor);
}
}, false);
xlator.addRewriter(ast1 -> new AstLoopUnwinder(ast1, true, unwindFactor), false);
return xlator;
}

View File

@ -13,7 +13,6 @@ import java.util.ArrayList;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.function.Function;
import com.ibm.wala.cast.js.loader.JavaScriptLoader;
import com.ibm.wala.cast.js.types.JavaScriptMethods;
@ -75,12 +74,7 @@ public class CallGraph2JSON {
for(Iterator<CallSiteReference> iter = nd.iterateCallSites(); iter.hasNext();) {
CallSiteReference callsite = iter.next();
Set<IMethod> targets = Util.mapToSet(cg.getPossibleTargets(nd, callsite), new Function<CGNode, IMethod>() {
@Override
public IMethod apply(CGNode nd) {
return nd.getMethod();
}
});
Set<IMethod> targets = Util.mapToSet(cg.getPossibleTargets(nd, callsite), nd1 -> nd1.getMethod());
serializeCallSite(method, callsite, targets, edges);
}
}
@ -137,23 +131,15 @@ public class CallGraph2JSON {
public static String toJSON(Map<String, Set<String>> map) {
StringBuffer res = new StringBuffer();
res.append("{\n");
res.append(joinWith(Util.mapToSet(map.entrySet(), new Function<Map.Entry<String, Set<String>>, String>() {
@Override
public String apply(Map.Entry<String, Set<String>> e) {
StringBuffer res = new StringBuffer();
if(e.getValue().size() > 0) {
res.append(" \"" + e.getKey() + "\": [\n");
res.append(joinWith(Util.mapToSet(e.getValue(), new Function<String, String>() {
@Override
public String apply(String str) {
return " \"" + str + "\"";
}
}), ",\n"));
res.append("\n ]");
}
return res.length() == 0 ? null : res.toString();
}
}), ",\n"));
res.append(joinWith(Util.mapToSet(map.entrySet(), e -> {
StringBuffer res1 = new StringBuffer();
if(e.getValue().size() > 0) {
res1.append(" \"" + e.getKey() + "\": [\n");
res1.append(joinWith(Util.mapToSet(e.getValue(), str -> " \"" + str + "\""), ",\n"));
res1.append("\n ]");
}
return res1.length() == 0 ? null : res1.toString();
}), ",\n"));
res.append("\n}");
return res.toString();
}

View File

@ -18,7 +18,6 @@ import com.ibm.wala.ssa.IR;
import com.ibm.wala.ssa.SSAInstruction;
import com.ibm.wala.ssa.SSAPhiInstruction;
import com.ibm.wala.util.intset.IntSet;
import com.ibm.wala.util.intset.IntSetAction;
import com.ibm.wala.util.intset.IntSetUtil;
import com.ibm.wala.util.intset.MutableIntSet;
@ -35,14 +34,11 @@ public class Util {
int size;
do {
size = result.size();
result.foreach(new IntSetAction() {
@Override
public void act(int vn) {
for(Iterator<SSAInstruction> insts = du.getUses(vn); insts.hasNext(); ) {
SSAInstruction inst = insts.next();
if (inst instanceof PrototypeLookup || inst instanceof SSAPhiInstruction) {
result.add(inst.getDef());
}
result.foreach(vn -> {
for(Iterator<SSAInstruction> insts = du.getUses(vn); insts.hasNext(); ) {
SSAInstruction inst = insts.next();
if (inst instanceof PrototypeLookup || inst instanceof SSAPhiInstruction) {
result.add(inst.getDef());
}
}
});

View File

@ -69,7 +69,6 @@ import com.ibm.wala.util.collections.HashSetFactory;
import com.ibm.wala.util.collections.Pair;
import com.ibm.wala.util.debug.Assertions;
import com.ibm.wala.util.intset.IntSet;
import com.ibm.wala.util.intset.IntSetAction;
import com.ibm.wala.util.intset.IntSetUtil;
import com.ibm.wala.util.intset.MutableIntSet;
import com.ibm.wala.util.intset.MutableMapping;
@ -473,15 +472,12 @@ public abstract class AstSSAPropagationCallGraphBuilder extends SSAPropagationCa
public byte evaluate(PointsToSetVariable lhs, PointsToSetVariable rhs) {
final IntSetVariable<?> objects = rhs;
if (objects.getValue() != null) {
objects.getValue().foreach(new IntSetAction() {
@Override
public void act(int optr) {
InstanceKey object = system.getInstanceKey(optr);
if (!getBuilder().isUncataloguedField(object.getConcreteType(), hack)) {
PointerKey cat = getPointerKeyForObjectCatalog(object);
if (cat != null) {
system.newConstraint(cat, fieldNameKeys[0]);
}
objects.getValue().foreach(optr -> {
InstanceKey object = system.getInstanceKey(optr);
if (!getBuilder().isUncataloguedField(object.getConcreteType(), hack)) {
PointerKey cat = getPointerKeyForObjectCatalog(object);
if (cat != null) {
system.newConstraint(cat, fieldNameKeys[0]);
}
}
});
@ -539,14 +535,11 @@ public abstract class AstSSAPropagationCallGraphBuilder extends SSAPropagationCa
public byte evaluate(PointsToSetVariable lhs, PointsToSetVariable rhs) {
final IntSetVariable<?> objects = rhs;
if (objects.getValue() != null) {
objects.getValue().foreach(new IntSetAction() {
@Override
public void act(int optr) {
InstanceKey object = system.getInstanceKey(optr);
PointerKey objCatalog = getPointerKeyForObjectCatalog(object);
if (objCatalog != null) {
system.newConstraint(lk, assignOperator, objCatalog);
}
objects.getValue().foreach(optr -> {
InstanceKey object = system.getInstanceKey(optr);
PointerKey objCatalog = getPointerKeyForObjectCatalog(object);
if (objCatalog != null) {
system.newConstraint(lk, assignOperator, objCatalog);
}
});
}
@ -718,19 +711,16 @@ public abstract class AstSSAPropagationCallGraphBuilder extends SSAPropagationCa
} else {
PointsToSetVariable FV = system.findOrCreatePointsToSet(F);
if (FV.getValue() != null) {
FV.getValue().foreach(new IntSetAction() {
@Override
public void act(int ptr) {
InstanceKey iKey = system.getInstanceKey(ptr);
if (iKey instanceof ScopeMappingInstanceKey) {
ScopeMappingInstanceKey K = (ScopeMappingInstanceKey) iKey;
Iterator<CGNode> x = K.getFunargNodes(definer);
while (x.hasNext()) {
result.add(x.next());
}
} else {
Assertions.UNREACHABLE("unexpected instance key " + iKey);
FV.getValue().foreach(ptr -> {
InstanceKey iKey = system.getInstanceKey(ptr);
if (iKey instanceof ScopeMappingInstanceKey) {
ScopeMappingInstanceKey K = (ScopeMappingInstanceKey) iKey;
Iterator<CGNode> x = K.getFunargNodes(definer);
while (x.hasNext()) {
result.add(x.next());
}
} else {
Assertions.UNREACHABLE("unexpected instance key " + iKey);
}
});
}
@ -957,34 +947,28 @@ public abstract class AstSSAPropagationCallGraphBuilder extends SSAPropagationCa
final IntSetVariable<?> receivers = rhs[0];
final IntSetVariable<?> fields = rhs[1];
if (receivers.getValue() != null && fields.getValue() != null) {
receivers.getValue().foreach(new IntSetAction() {
@Override
public void act(final int rptr) {
final InstanceKey receiver = system.getInstanceKey(rptr);
receivers.getValue().foreach(rptr -> {
final InstanceKey receiver = system.getInstanceKey(rptr);
if (!isLoadOperation) {
PointerKey cat = getPointerKeyForObjectCatalog(receiver);
if (cat != null) {
system.newConstraint(cat, assignOperator, fieldKey);
if (!isLoadOperation) {
PointerKey cat = getPointerKeyForObjectCatalog(receiver);
if (cat != null) {
system.newConstraint(cat, assignOperator, fieldKey);
}
}
fields.getValue().foreach(fptr -> {
if (!doneField.contains(fptr) || !doneReceiver.contains(rptr)) {
InstanceKey field = system.getInstanceKey(fptr);
for (Iterator<PointerKey> keys = isLoadOperation ? getPointerKeysForReflectedFieldRead(receiver, field)
: getPointerKeysForReflectedFieldWrite(receiver, field); keys.hasNext();) {
AbstractFieldPointerKey key = (AbstractFieldPointerKey) keys.next();
if (DEBUG_PROPERTIES)
action.dump(key, false, false);
action.action(key);
}
}
fields.getValue().foreach(new IntSetAction() {
@Override
public void act(int fptr) {
if (!doneField.contains(fptr) || !doneReceiver.contains(rptr)) {
InstanceKey field = system.getInstanceKey(fptr);
for (Iterator<PointerKey> keys = isLoadOperation ? getPointerKeysForReflectedFieldRead(receiver, field)
: getPointerKeysForReflectedFieldWrite(receiver, field); keys.hasNext();) {
AbstractFieldPointerKey key = (AbstractFieldPointerKey) keys.next();
if (DEBUG_PROPERTIES)
action.dump(key, false, false);
action.action(key);
}
}
}
});
}
});
});
doneReceiver.addAll(receivers.getValue());
doneField.addAll(fields.getValue());
@ -1017,29 +1001,26 @@ public abstract class AstSSAPropagationCallGraphBuilder extends SSAPropagationCa
public byte evaluate(PointsToSetVariable lhs, PointsToSetVariable rhs) {
final IntSetVariable<?> objects = rhs;
if (objects.getValue() != null) {
objects.getValue().foreach(new IntSetAction() {
@Override
public void act(int optr) {
InstanceKey object = system.getInstanceKey(optr);
PointerKey objCatalog = getPointerKeyForObjectCatalog(object);
for (int f = 0; f < fieldsKeys.length; f++) {
if (isLoadOperation) {
for (Iterator<PointerKey> keys = getPointerKeysForReflectedFieldRead(object, fieldsKeys[f]); keys.hasNext();) {
AbstractFieldPointerKey key = (AbstractFieldPointerKey) keys.next();
if (DEBUG_PROPERTIES)
action.dump(key, true, false);
action.action(key);
}
} else {
if (objCatalog != null) {
system.newConstraint(objCatalog, fieldsKeys[f]);
}
for (Iterator<PointerKey> keys = getPointerKeysForReflectedFieldWrite(object, fieldsKeys[f]); keys.hasNext();) {
AbstractFieldPointerKey key = (AbstractFieldPointerKey) keys.next();
if (DEBUG_PROPERTIES)
action.dump(key, true, false);
action.action(key);
}
objects.getValue().foreach(optr -> {
InstanceKey object = system.getInstanceKey(optr);
PointerKey objCatalog = getPointerKeyForObjectCatalog(object);
for (int f = 0; f < fieldsKeys.length; f++) {
if (isLoadOperation) {
for (Iterator<PointerKey> keys1 = getPointerKeysForReflectedFieldRead(object, fieldsKeys[f]); keys1.hasNext();) {
AbstractFieldPointerKey key1 = (AbstractFieldPointerKey) keys1.next();
if (DEBUG_PROPERTIES)
action.dump(key1, true, false);
action.action(key1);
}
} else {
if (objCatalog != null) {
system.newConstraint(objCatalog, fieldsKeys[f]);
}
for (Iterator<PointerKey> keys2 = getPointerKeysForReflectedFieldWrite(object, fieldsKeys[f]); keys2.hasNext();) {
AbstractFieldPointerKey key2 = (AbstractFieldPointerKey) keys2.next();
if (DEBUG_PROPERTIES)
action.dump(key2, true, false);
action.action(key2);
}
}
}
@ -1081,18 +1062,15 @@ public abstract class AstSSAPropagationCallGraphBuilder extends SSAPropagationCa
public byte evaluate(PointsToSetVariable lhs, PointsToSetVariable rhs) {
final IntSetVariable<?> fields = rhs;
if (fields.getValue() != null) {
fields.getValue().foreach(new IntSetAction() {
@Override
public void act(int fptr) {
InstanceKey field = system.getInstanceKey(fptr);
for (int o = 0; o < objKeys.length; o++) {
for (Iterator<PointerKey> keys = isLoadOperation ? getPointerKeysForReflectedFieldRead(objKeys[o], field)
: getPointerKeysForReflectedFieldWrite(objKeys[o], field); keys.hasNext();) {
AbstractFieldPointerKey key = (AbstractFieldPointerKey) keys.next();
if (DEBUG_PROPERTIES)
action.dump(key, false, true);
action.action(key);
}
fields.getValue().foreach(fptr -> {
InstanceKey field = system.getInstanceKey(fptr);
for (int o = 0; o < objKeys.length; o++) {
for (Iterator<PointerKey> keys = isLoadOperation ? getPointerKeysForReflectedFieldRead(objKeys[o], field)
: getPointerKeysForReflectedFieldWrite(objKeys[o], field); keys.hasNext();) {
AbstractFieldPointerKey key = (AbstractFieldPointerKey) keys.next();
if (DEBUG_PROPERTIES)
action.dump(key, false, true);
action.action(key);
}
}
});

View File

@ -12,7 +12,6 @@ package com.ibm.wala.cast.ipa.callgraph;
import java.util.Collection;
import java.util.Iterator;
import java.util.function.Predicate;
import com.ibm.wala.classLoader.IClass;
import com.ibm.wala.classLoader.NewSiteReference;
@ -139,11 +138,7 @@ abstract public class ScopeMappingInstanceKeys implements InstanceKeyFactory {
public Iterator<Pair<CGNode, NewSiteReference>> getCreationSites(CallGraph CG) {
return new FilterIterator<>(
base.getCreationSites(CG),
new Predicate<Pair<CGNode, NewSiteReference>>() {
@Override public boolean test(Pair<CGNode, NewSiteReference> o) {
return o.fst.equals(creator);
}
});
o -> o.fst.equals(creator));
}
}

View File

@ -12,7 +12,6 @@ package com.ibm.wala.cast.ipa.lexical;
import java.util.Collection;
import java.util.Map;
import java.util.function.Function;
import com.ibm.wala.cast.ipa.callgraph.ScopeMappingInstanceKeys.ScopeMappingInstanceKey;
import com.ibm.wala.cast.ir.ssa.AstLexicalAccess.Access;
@ -56,13 +55,7 @@ public class LexicalModRef {
*/
public Map<CGNode, OrdinalSet<Pair<CGNode, String>>> computeLexicalRef() {
Map<CGNode, Collection<Pair<CGNode, String>>> scan = CallGraphTransitiveClosure.collectNodeResults(cg,
new Function<CGNode, Collection<Pair<CGNode, String>>>() {
@Override
public Collection<Pair<CGNode, String>> apply(CGNode n) {
return scanNodeForLexReads(n);
}
});
n -> scanNodeForLexReads(n));
return CallGraphTransitiveClosure.transitiveClosure(cg, scan);
}
@ -73,13 +66,7 @@ public class LexicalModRef {
*/
public Map<CGNode, OrdinalSet<Pair<CGNode, String>>> computeLexicalMod() {
Map<CGNode, Collection<Pair<CGNode, String>>> scan = CallGraphTransitiveClosure.collectNodeResults(cg,
new Function<CGNode, Collection<Pair<CGNode, String>>>() {
@Override
public Collection<Pair<CGNode, String>> apply(CGNode n) {
return scanNodeForLexWrites(n);
}
});
n -> scanNodeForLexWrites(n));
return CallGraphTransitiveClosure.transitiveClosure(cg, scan);
}

View File

@ -1196,22 +1196,16 @@ public abstract class AstTranslator extends CAstVisitor<AstTranslator.WalkContex
final Map<PreBasicBlock, Collection<PreBasicBlock>> exceptionalEdges =
hasDeadBlocks? HashMapFactory.<PreBasicBlock,Collection<PreBasicBlock>>make() : null;
if (hasDeadBlocks) {
transferEdges(liveBlocks, icfg, new EdgeOperation() {
@Override
public void act(PreBasicBlock src, PreBasicBlock dst) {
if (! normalEdges.containsKey(src)) {
normalEdges.put(src, HashSetFactory.<PreBasicBlock>make());
}
normalEdges.get(src).add(dst);
transferEdges(liveBlocks, icfg, (src, dst) -> {
if (! normalEdges.containsKey(src)) {
normalEdges.put(src, HashSetFactory.<PreBasicBlock>make());
}
}, new EdgeOperation() {
@Override
public void act(PreBasicBlock src, PreBasicBlock dst) {
if (! exceptionalEdges.containsKey(src)) {
exceptionalEdges.put(src, HashSetFactory.<PreBasicBlock>make());
}
exceptionalEdges.get(src).add(dst);
}
normalEdges.get(src).add(dst);
}, (src, dst) -> {
if (! exceptionalEdges.containsKey(src)) {
exceptionalEdges.put(src, HashSetFactory.<PreBasicBlock>make());
}
exceptionalEdges.get(src).add(dst);
});
}
@ -1268,17 +1262,7 @@ public abstract class AstTranslator extends CAstVisitor<AstTranslator.WalkContex
}
}
} else {
transferEdges(liveBlocks, icfg, new EdgeOperation() {
@Override
public void act(PreBasicBlock src, PreBasicBlock dst) {
addNormalEdge(src, dst);
}
}, new EdgeOperation() {
@Override
public void act(PreBasicBlock src, PreBasicBlock dst) {
addExceptionalEdge(src, dst);
}
});
transferEdges(liveBlocks, icfg, (src, dst) -> addNormalEdge(src, dst), (src, dst) -> addExceptionalEdge(src, dst));
}
int x = 0;

View File

@ -17,10 +17,7 @@ import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.function.Function;
import java.util.function.Predicate;
import com.ibm.wala.cast.tree.CAstSourcePositionMap.Position;
import com.ibm.wala.classLoader.IClass;
@ -82,21 +79,14 @@ public abstract class CAstAbstractLoader implements IClassLoader {
}
private Iterator<ModuleEntry> getMessages(final byte severity) {
return new MapIterator<>(new FilterIterator<>(errors.entrySet().iterator(), new Predicate<Map.Entry<ModuleEntry,Set<Warning>>>() {
@Override public boolean test(Entry<ModuleEntry, Set<Warning>> o) {
for(Warning w : o.getValue()) {
if (w.getLevel() == severity) {
return true;
}
return new MapIterator<>(new FilterIterator<>(errors.entrySet().iterator(), o -> {
for(Warning w : o.getValue()) {
if (w.getLevel() == severity) {
return true;
}
return false;
}
}), new Function<Map.Entry<ModuleEntry,Set<Warning>>, ModuleEntry>() {
@Override
public ModuleEntry apply(Entry<ModuleEntry, Set<Warning>> object) {
return object.getKey();
}
});
}
return false;
}), object -> object.getKey());
}
public Iterator<ModuleEntry> getModulesWithParseErrors() {

View File

@ -41,11 +41,7 @@ public class PathFinderTest {
}
private static DFSAllPathsFinder<String> makeFinder(Graph<String> g, String start, final String end) {
return new DFSAllPathsFinder<>(g, start, new Predicate<String>() {
@Override public boolean test(String o) {
return end.equals(o);
}
});
return new DFSAllPathsFinder<>(g, start, (Predicate<String>) o -> end.equals(o));
}
private static void checkPaths(DFSAllPathsFinder<String> paths, int expectedCount) {

View File

@ -33,12 +33,7 @@ public class CHACallGraphTest {
}
public static CallGraph testCHA(String scopeFile, final String mainClass, final String exclusionsFile) throws ClassHierarchyException, IllegalArgumentException, CancelException, IOException {
return testCHA(scopeFile, exclusionsFile, new Function<IClassHierarchy, Iterable<Entrypoint>>() {
@Override
public Iterable<Entrypoint> apply(IClassHierarchy cha) {
return Util.makeMainEntrypoints(cha.getScope(), cha, mainClass);
}
});
return testCHA(scopeFile, exclusionsFile, cha -> Util.makeMainEntrypoints(cha.getScope(), cha, mainClass));
}
public static CallGraph testCHA(String scopeFile,

View File

@ -242,12 +242,7 @@ public class CallGraphTest extends WalaTestCase {
}
}
}
return new Iterable<Entrypoint>() {
@Override
public Iterator<Entrypoint> iterator() {
return result.iterator();
}
};
return () -> result.iterator();
}
@Test public void testPrimordial() throws ClassHierarchyException, IllegalArgumentException, CancelException, IOException {
@ -299,12 +294,7 @@ public class CallGraphTest extends WalaTestCase {
result.add(new DefaultEntrypoint(m, cha));
}
}
return new Iterable<Entrypoint>() {
@Override
public Iterator<Entrypoint> iterator() {
return result.iterator();
}
};
return () -> result.iterator();
}
public static void doCallGraphs(AnalysisOptions options, IAnalysisCacheView cache, IClassHierarchy cha, AnalysisScope scope)

View File

@ -13,7 +13,6 @@ package com.ibm.wala.core.tests.callGraph;
import java.io.File;
import java.io.IOException;
import java.util.function.Predicate;
import java.util.jar.JarFile;
import org.junit.Test;
@ -35,7 +34,6 @@ import com.ibm.wala.ipa.cha.ClassHierarchyFactory;
import com.ibm.wala.shrikeBT.analysis.Analyzer.FailureException;
import com.ibm.wala.shrikeCT.InvalidClassFileException;
import com.ibm.wala.types.ClassLoaderReference;
import com.ibm.wala.types.MethodReference;
import com.ibm.wala.util.CancelException;
import com.ibm.wala.util.io.TemporaryFile;
@ -69,12 +67,9 @@ public class Java7CallGraphTest extends DynamicCallGraphTestBase {
instrument(F.getAbsolutePath());
run("pack.ocamljavaMain", null, args);
checkNodes(cg, new Predicate<MethodReference>() {
@Override
public boolean test(MethodReference t) {
String s = t.toString();
return s.contains("Lpack/") || s.contains("Locaml/stdlib/");
}
checkNodes(cg, t -> {
String s = t.toString();
return s.contains("Lpack/") || s.contains("Locaml/stdlib/");
});
}

View File

@ -152,20 +152,17 @@ public abstract class DynamicCallGraphTestBase extends WalaTestCase {
protected void checkEdges(CallGraph staticCG, Predicate<MethodReference> filter) throws IOException {
final Set<Pair<CGNode,CGNode>> edges = HashSetFactory.make();
check(staticCG, new EdgesTest() {
@Override
public void edgesTest(CallGraph staticCG, CGNode caller, MethodReference calleeRef) {
Set<CGNode> nodes = staticCG.getNodes(calleeRef);
Assert.assertEquals("expected one node for " + calleeRef, 1, nodes.size());
CGNode callee = nodes.iterator().next();
Assert.assertTrue("no edge for " + caller + " --> " + callee, staticCG.getPossibleSites(caller, callee).hasNext());
Pair<CGNode,CGNode> x = Pair.make(caller, callee);
if (! edges.contains(x)) {
edges.add(x);
System.err.println("found expected edge " + caller + " --> " + callee);
}
}
check(staticCG, (staticCG1, caller, calleeRef) -> {
Set<CGNode> nodes = staticCG1.getNodes(calleeRef);
Assert.assertEquals("expected one node for " + calleeRef, 1, nodes.size());
CGNode callee = nodes.iterator().next();
Assert.assertTrue("no edge for " + caller + " --> " + callee, staticCG1.getPossibleSites(caller, callee).hasNext());
Pair<CGNode,CGNode> x = Pair.make(caller, callee);
if (! edges.contains(x)) {
edges.add(x);
System.err.println("found expected edge " + caller + " --> " + callee);
}
}, filter);
}
@ -175,15 +172,12 @@ public abstract class DynamicCallGraphTestBase extends WalaTestCase {
protected void checkNodes(CallGraph staticCG, Predicate<MethodReference> filter) throws IOException {
final Set<MethodReference> notFound = HashSetFactory.make();
check(staticCG, new EdgesTest() {
@Override
public void edgesTest(CallGraph staticCG, CGNode caller, MethodReference callee) {
boolean checkForCallee = !staticCG.getNodes(callee).isEmpty();
if (!checkForCallee) {
notFound.add(callee);
} else {
System.err.println("found expected node " + callee);
}
check(staticCG, (staticCG1, caller, callee) -> {
boolean checkForCallee = !staticCG1.getNodes(callee).isEmpty();
if (!checkForCallee) {
notFound.add(callee);
} else {
System.err.println("found expected node " + callee);
}
}, filter);

View File

@ -165,44 +165,38 @@ public class PDFSDG {
}
private static Graph<Statement> pruneSDG(final SDG<?> sdg) {
Predicate<Statement> f = new Predicate<Statement>() {
@Override public boolean test(Statement s) {
if (s.getNode().equals(sdg.getCallGraph().getFakeRootNode())) {
return false;
} else if (s instanceof MethodExitStatement || s instanceof MethodEntryStatement) {
return false;
} else {
return true;
}
Predicate<Statement> f = s -> {
if (s.getNode().equals(sdg.getCallGraph().getFakeRootNode())) {
return false;
} else if (s instanceof MethodExitStatement || s instanceof MethodEntryStatement) {
return false;
} else {
return true;
}
};
return GraphSlicer.prune(sdg, f);
}
private static NodeDecorator<Statement> makeNodeDecorator() {
return new NodeDecorator<Statement>() {
@Override
public String getLabel(Statement s) throws WalaException {
switch (s.getKind()) {
case HEAP_PARAM_CALLEE:
case HEAP_PARAM_CALLER:
case HEAP_RET_CALLEE:
case HEAP_RET_CALLER:
HeapStatement h = (HeapStatement) s;
return s.getKind() + "\\n" + h.getNode() + "\\n" + h.getLocation();
case EXC_RET_CALLEE:
case EXC_RET_CALLER:
case NORMAL:
case NORMAL_RET_CALLEE:
case NORMAL_RET_CALLER:
case PARAM_CALLEE:
case PARAM_CALLER:
case PHI:
default:
return s.toString();
}
return s -> {
switch (s.getKind()) {
case HEAP_PARAM_CALLEE:
case HEAP_PARAM_CALLER:
case HEAP_RET_CALLEE:
case HEAP_RET_CALLER:
HeapStatement h = (HeapStatement) s;
return s.getKind() + "\\n" + h.getNode() + "\\n" + h.getLocation();
case EXC_RET_CALLEE:
case EXC_RET_CALLER:
case NORMAL:
case NORMAL_RET_CALLEE:
case NORMAL_RET_CALLER:
case PARAM_CALLEE:
case PARAM_CALLER:
case PHI:
default:
return s.toString();
}
};
}

View File

@ -249,11 +249,7 @@ public class PDFSlice {
* return a view of the sdg restricted to the statements in the slice
*/
public static Graph<Statement> pruneSDG(SDG<InstanceKey> sdg, final Collection<Statement> slice) {
Predicate<Statement> f = new Predicate<Statement>() {
@Override public boolean test(Statement o) {
return slice.contains(o);
}
};
Predicate<Statement> f = o -> slice.contains(o);
return GraphSlicer.prune(sdg, f);
}
@ -261,36 +257,32 @@ public class PDFSlice {
* @return a NodeDecorator that decorates statements in a slice for a dot-ted representation
*/
public static NodeDecorator<Statement> makeNodeDecorator() {
return new NodeDecorator<Statement>() {
@Override
public String getLabel(Statement s) throws WalaException {
switch (s.getKind()) {
case HEAP_PARAM_CALLEE:
case HEAP_PARAM_CALLER:
case HEAP_RET_CALLEE:
case HEAP_RET_CALLER:
HeapStatement h = (HeapStatement) s;
return s.getKind() + "\\n" + h.getNode() + "\\n" + h.getLocation();
case NORMAL:
NormalStatement n = (NormalStatement) s;
return n.getInstruction() + "\\n" + n.getNode().getMethod().getSignature();
case PARAM_CALLEE:
ParamCallee paramCallee = (ParamCallee) s;
return s.getKind() + " " + paramCallee.getValueNumber() + "\\n" + s.getNode().getMethod().getName();
case PARAM_CALLER:
ParamCaller paramCaller = (ParamCaller) s;
return s.getKind() + " " + paramCaller.getValueNumber() + "\\n" + s.getNode().getMethod().getName() + "\\n"
+ paramCaller.getInstruction().getCallSite().getDeclaredTarget().getName();
case EXC_RET_CALLEE:
case EXC_RET_CALLER:
case NORMAL_RET_CALLEE:
case NORMAL_RET_CALLER:
case PHI:
default:
return s.toString();
}
return s -> {
switch (s.getKind()) {
case HEAP_PARAM_CALLEE:
case HEAP_PARAM_CALLER:
case HEAP_RET_CALLEE:
case HEAP_RET_CALLER:
HeapStatement h = (HeapStatement) s;
return s.getKind() + "\\n" + h.getNode() + "\\n" + h.getLocation();
case NORMAL:
NormalStatement n = (NormalStatement) s;
return n.getInstruction() + "\\n" + n.getNode().getMethod().getSignature();
case PARAM_CALLEE:
ParamCallee paramCallee = (ParamCallee) s;
return s.getKind() + " " + paramCallee.getValueNumber() + "\\n" + s.getNode().getMethod().getName();
case PARAM_CALLER:
ParamCaller paramCaller = (ParamCaller) s;
return s.getKind() + " " + paramCaller.getValueNumber() + "\\n" + s.getNode().getMethod().getName() + "\\n"
+ paramCaller.getInstruction().getCallSite().getDeclaredTarget().getName();
case EXC_RET_CALLEE:
case EXC_RET_CALLER:
case NORMAL_RET_CALLEE:
case NORMAL_RET_CALLER:
case PHI:
default:
return s.toString();
}
};
}

View File

@ -103,11 +103,7 @@ public class PDFTypeHierarchy {
* Restrict g to nodes from the Application loader
*/
public static Graph<IClass> pruneForAppLoader(Graph<IClass> g) {
Predicate<IClass> f = new Predicate<IClass>() {
@Override public boolean test(IClass c) {
return (c.getClassLoader().getReference().equals(ClassLoaderReference.Application));
}
};
Predicate<IClass> f = c -> (c.getClassLoader().getReference().equals(ClassLoaderReference.Application));
return pruneGraph(g, f);
}

View File

@ -135,12 +135,7 @@ public class BasicHeapGraph<T extends InstanceKey> extends HeapGraphImpl<T> {
};
final IBinaryNaturalRelation pred = computePredecessors(nodeMgr);
final IntFunction<Object> toNode = new IntFunction<Object>() {
@Override
public Object apply(int i) {
return nodeMgr.getNode(i);
}
};
final IntFunction<Object> toNode = i -> nodeMgr.getNode(i);
this.G = new AbstractNumberedGraph<Object>() {
private final NumberedEdgeManager<Object> edgeMgr = new NumberedEdgeManager<Object>() {

View File

@ -52,11 +52,7 @@ public abstract class HeapGraphImpl<T extends InstanceKey> implements HeapGraph<
@Override
public Collection<Object> getReachableInstances(Set<Object> roots) {
Predicate<Object> f = new Predicate<Object>() {
@Override public boolean test(Object o) {
return (o instanceof InstanceKey);
}
};
Predicate<Object> f = o -> (o instanceof InstanceKey);
return DFS.getReachableNodes(this, roots, f);
}

View File

@ -13,7 +13,6 @@ package com.ibm.wala.analysis.reflection.java7;
import java.lang.ref.SoftReference;
import java.util.Iterator;
import java.util.Map;
import java.util.function.Function;
import java.util.function.Predicate;
import com.ibm.wala.cfg.ControlFlowGraph;
@ -212,30 +211,17 @@ public class MethodHandles {
return
new MapIterator<SSAInstruction,FieldReference>(
new FilterIterator<SSAInstruction>(getIR(node).iterateNormalInstructions(), filter),
new Function<SSAInstruction,FieldReference>() {
@Override
public FieldReference apply(SSAInstruction object) {
return ((SSAFieldAccessInstruction)object).getDeclaredField();
}
});
object -> ((SSAFieldAccessInstruction)object).getDeclaredField());
}
@Override
public Iterator<FieldReference> iterateFieldsRead(CGNode node) {
return iterateFields(node, new Predicate<SSAInstruction>() {
@Override public boolean test(SSAInstruction o) {
return o instanceof SSAGetInstruction;
}
});
return iterateFields(node, o -> o instanceof SSAGetInstruction);
}
@Override
public Iterator<FieldReference> iterateFieldsWritten(CGNode node) {
return iterateFields(node, new Predicate<SSAInstruction>() {
@Override public boolean test(SSAInstruction o) {
return o instanceof SSAPutInstruction;
}
});
return iterateFields(node, o -> o instanceof SSAPutInstruction);
}
@Override

View File

@ -15,7 +15,6 @@ import java.util.Collection;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.function.Predicate;
import com.ibm.wala.classLoader.IMethod;
import com.ibm.wala.shrikeBT.Constants;
@ -228,12 +227,9 @@ public abstract class AbstractCFG<I, T extends IBasicBlock<I>> implements Contro
throw new IllegalArgumentException("N is null");
}
if (N.equals(exit())) {
return new FilterIterator<>(iterator(), new Predicate<T>() {
@Override
public boolean test(T o) {
int i = getNumber(o);
return normalToExit.get(i) || exceptionalToExit.get(i);
}
return new FilterIterator<>(iterator(), o -> {
int i = getNumber(o);
return normalToExit.get(i) || exceptionalToExit.get(i);
});
} else {
int number = getNumber(N);
@ -341,12 +337,9 @@ public abstract class AbstractCFG<I, T extends IBasicBlock<I>> implements Contro
Iterator<T> iterateExceptionalPredecessors(T N) {
if (N.equals(exit())) {
return new FilterIterator<>(iterator(), new Predicate<T>() {
@Override
public boolean test(T o) {
int i = getNumber(o);
return exceptionalToExit.get(i);
}
return new FilterIterator<>(iterator(), o -> {
int i = getNumber(o);
return exceptionalToExit.get(i);
});
} else {
return exceptionalEdgeManager.getPredNodes(N);
@ -355,12 +348,9 @@ public abstract class AbstractCFG<I, T extends IBasicBlock<I>> implements Contro
Iterator<T> iterateNormalPredecessors(T N) {
if (N.equals(exit())) {
return new FilterIterator<>(iterator(), new Predicate<T>() {
@Override
public boolean test(T o) {
int i = getNumber(o);
return normalToExit.get(i);
}
return new FilterIterator<>(iterator(), o -> {
int i = getNumber(o);
return normalToExit.get(i);
});
} else {
int number = getNumber(N);

View File

@ -347,30 +347,15 @@ public final class ShrikeCTMethod extends ShrikeBTMethod implements IBytecodeMet
}
private CodeReader getCodeReader() {
return getReader("Code", new GetReader<CodeReader>() {
@Override
public CodeReader getReader(AttrIterator iter) throws InvalidClassFileException {
return new CodeReader(iter);
}
});
return getReader("Code", iter -> new CodeReader(iter));
}
private ExceptionsReader getExceptionReader() {
return getReader("Exceptions", new GetReader<ExceptionsReader>() {
@Override
public ExceptionsReader getReader(AttrIterator iter) throws InvalidClassFileException {
return new ExceptionsReader(iter);
}
});
return getReader("Exceptions", iter -> new ExceptionsReader(iter));
}
private SignatureReader getSignatureReader() {
return getReader("Signature", new GetReader<SignatureReader>() {
@Override
public SignatureReader getReader(AttrIterator iter) throws InvalidClassFileException {
return new SignatureReader(iter);
}
});
return getReader("Signature", iter -> new SignatureReader(iter));
}
private AnnotationsReader getAnnotationsReader(AnnotationType type) {

View File

@ -343,12 +343,7 @@ public final class ShrikeClass extends JVMClass<IClassLoader> {
ClassReader.AttrIterator attrs = new ClassReader.AttrIterator();
getReader().initClassAttributeIterator(attrs);
return getReader(attrs, "SourceFile", new GetReader<SourceFileReader>() {
@Override
public SourceFileReader getReader(AttrIterator iter) throws InvalidClassFileException {
return new SourceFileReader(iter);
}
});
return getReader(attrs, "SourceFile", iter -> new SourceFileReader(iter));
}
private AnnotationsReader getFieldAnnotationsReader(boolean runtimeInvisible, int fieldIndex) throws InvalidClassFileException {

View File

@ -125,12 +125,7 @@ public abstract class AbstractAnalysisEngine<I extends InstanceKey> implements A
*/
private HeapGraph heapGraph;
private EntrypointBuilder entrypointBuilder = new EntrypointBuilder() {
@Override
public Iterable<Entrypoint> createEntrypoints(AnalysisScope scope, IClassHierarchy cha) {
return makeDefaultEntrypoints(scope, cha);
}
};
private EntrypointBuilder entrypointBuilder = (scope, cha) -> makeDefaultEntrypoints(scope, cha);
protected abstract CallGraphBuilder<I> getCallGraphBuilder(IClassHierarchy cha, AnalysisOptions options, IAnalysisCacheView cache2);

View File

@ -110,18 +110,9 @@ public class BackwardsSupergraph<T, P> implements ISupergraph<T, P> {
@Override
public Iterator<T> getNormalSuccessors(final T ret) {
Iterator<T> allPreds = delegate.getPredNodes(ret);
Predicate<T> sameProc = new Predicate<T>() {
@Override public boolean test(T o) {
// throw out the exit node, which can be a predecessor due to tail recursion.
return getProcOf(ret).equals(getProcOf(o)) && !delegate.isExit(o);
}
};
Predicate<T> sameProc = o -> getProcOf(ret).equals(getProcOf(o)) && !delegate.isExit(o);
Iterator<T> sameProcPreds = new FilterIterator<>(allPreds, sameProc);
Predicate<T> notCall = new Predicate<T>() {
@Override public boolean test(T o) {
return !delegate.isCall(o);
}
};
Predicate<T> notCall = o -> !delegate.isCall(o);
return new FilterIterator<T>(sameProcPreds, notCall);
}

View File

@ -95,11 +95,7 @@ public class ICFGSupergraph implements ISupergraph<BasicBlockInContext<IExploded
@Override
public Iterator<? extends BasicBlockInContext<IExplodedBasicBlock>> getCalledNodes(BasicBlockInContext<IExplodedBasicBlock> call) {
final Predicate<BasicBlockInContext<IExplodedBasicBlock>> isEntryFilter = new Predicate<BasicBlockInContext<IExplodedBasicBlock>>() {
@Override public boolean test(BasicBlockInContext<IExplodedBasicBlock> o) {
return o.isEntryBlock();
}
};
final Predicate<BasicBlockInContext<IExplodedBasicBlock>> isEntryFilter = o -> o.isEntryBlock();
return new FilterIterator<BasicBlockInContext<IExplodedBasicBlock>>(getSuccNodes(call), isEntryFilter);
}

View File

@ -343,12 +343,9 @@ public class TabulationSolver<T, P, F> {
System.err.println(" reached: " + D3);
}
if (D3 != null) {
D3.foreach(new IntSetAction() {
@Override
public void act(int d3) {
newNormalExplodedEdge(edge, m, d3);
propagate(edge.entry, edge.d1, m, d3);
}
D3.foreach(d3 -> {
newNormalExplodedEdge(edge, m, d3);
propagate(edge.entry, edge.d1, m, d3);
});
}
}
@ -437,12 +434,7 @@ public class TabulationSolver<T, P, F> {
System.err.println("D4" + D4);
System.err.println("D5 " + D5);
}
IntSetAction action = new IntSetAction() {
@Override
public void act(final int d4) {
propToReturnSite(c, entries, retSite, d4, D5, edge);
}
};
IntSetAction action = d4 -> propToReturnSite(c, entries, retSite, d4, D5, edge);
D4.foreach(action);
}
}
@ -462,13 +454,9 @@ public class TabulationSolver<T, P, F> {
*/
private void propagateToReturnSiteWithBinaryFlowFunction(final PathEdge<T> edge, final T c, final IntSet D4, final T[] entries,
final T retSite, final IFlowFunction retf) {
D4.foreach(new IntSetAction() {
@Override
public void act(final int d4) {
final IntSet D5 = computeBinaryFlow(d4, edge.d2, (IBinaryReturnFlowFunction) retf);
propToReturnSite(c, entries, retSite, d4, D5, edge);
}
D4.foreach(d4 -> {
final IntSet D5 = computeBinaryFlow(d4, edge.d2, (IBinaryReturnFlowFunction) retf);
propToReturnSite(c, entries, retSite, d4, D5, edge);
});
}
@ -508,14 +496,11 @@ public class TabulationSolver<T, P, F> {
System.err.println("D3" + D3);
}
if (D3 != null) {
D3.foreach(new IntSetAction() {
@Override
public void act(int d3) {
// set curPathEdge to be consistent with its setting in processCall() when applying a summary edge
curPathEdge = PathEdge.createPathEdge(s_p, d3, c, d4);
newSummaryEdge(curPathEdge, edge, retSite, d5);
propagate(s_p, d3, retSite, d5);
}
D3.foreach(d3 -> {
// set curPathEdge to be consistent with its setting in processCall() when applying a summary edge
curPathEdge = PathEdge.createPathEdge(s_p, d3, c, d4);
newSummaryEdge(curPathEdge, edge, retSite, d5);
propagate(s_p, d3, retSite, d5);
});
}
}
@ -576,12 +561,9 @@ public class TabulationSolver<T, P, F> {
System.err.println("normal successor reached: " + D3);
}
if (D3 != null) {
D3.foreach(new IntSetAction() {
@Override
public void act(int d3) {
newNormalExplodedEdge(edge, m, d3);
propagate(edge.entry, edge.d1, m, d3);
}
D3.foreach(d3 -> {
newNormalExplodedEdge(edge, m, d3);
propagate(edge.entry, edge.d1, m, d3);
});
}
}
@ -603,14 +585,11 @@ public class TabulationSolver<T, P, F> {
System.err.println("reached: " + reached);
}
if (reached != null) {
reached.foreach(new IntSetAction() {
@Override
public void act(int x) {
assert x >= 0;
assert edge.d1 >= 0;
newNormalExplodedEdge(edge, returnSite, x);
propagate(edge.entry, edge.d1, returnSite, x);
}
reached.foreach(x -> {
assert x >= 0;
assert edge.d1 >= 0;
newNormalExplodedEdge(edge, returnSite, x);
propagate(edge.entry, edge.d1, returnSite, x);
});
}
}
@ -658,69 +637,57 @@ public class TabulationSolver<T, P, F> {
final CallFlowEdges callFlow = findOrCreateCallFlowEdges(calleeEntry);
final int s_p_num = supergraph.getLocalBlockNumber(calleeEntry);
reached.foreach(new IntSetAction() {
@Override
public void act(final int d1) {
// we get reuse if we _don't_ propagate a new fact to the callee entry
final boolean gotReuse = !propagate(calleeEntry, d1, calleeEntry, d1);
recordCall(edge.target, calleeEntry, d1, gotReuse);
newCallExplodedEdge(edge, calleeEntry, d1);
// cache the fact that we've flowed <c, d2> -> <callee, d1> by a
// call flow
callFlow.addCallEdge(callNodeNum, edge.d2, d1);
// handle summary edges now as well. this is different from the PoPL
// 95 paper.
if (summaries != null) {
// for each exit from the callee
P p = supergraph.getProcOf(calleeEntry);
T[] exits = supergraph.getExitsForProcedure(p);
for (int e = 0; e < exits.length; e++) {
final T exit = exits[e];
if (DEBUG_LEVEL > 0) {
assert supergraph.containsNode(exit);
}
int x_num = supergraph.getLocalBlockNumber(exit);
// reachedBySummary := {d2} s.t. <callee,d1> -> <exit,d2>
// was recorded as a summary edge
IntSet reachedBySummary = summaries.getSummaryEdges(s_p_num, x_num, d1);
if (reachedBySummary != null) {
for (final T returnSite : returnSitesForCallee) {
// if "exit" is a valid exit from the callee to the return
// site being processed
if (supergraph.hasEdge(exit, returnSite)) {
final IFlowFunction retf = flowFunctionMap.getReturnFlowFunction(edge.target, exit, returnSite);
reachedBySummary.foreach(new IntSetAction() {
@Override
public void act(final int d2) {
assert curSummaryEdge == null : "curSummaryEdge should be null here";
curSummaryEdge = PathEdge.createPathEdge(calleeEntry, d1, exit, d2);
if (retf instanceof IBinaryReturnFlowFunction) {
final IntSet D5 = computeBinaryFlow(edge.d2, d2, (IBinaryReturnFlowFunction) retf);
if (D5 != null) {
D5.foreach(new IntSetAction() {
@Override
public void act(int d5) {
newSummaryEdge(edge, curSummaryEdge, returnSite, d5);
propagate(edge.entry, edge.d1, returnSite, d5);
}
});
}
} else {
final IntSet D5 = computeFlow(d2, (IUnaryFlowFunction) retf);
if (D5 != null) {
D5.foreach(new IntSetAction() {
@Override
public void act(int d5) {
newSummaryEdge(edge, curSummaryEdge, returnSite, d5);
propagate(edge.entry, edge.d1, returnSite, d5);
}
});
}
}
curSummaryEdge = null;
reached.foreach(d1 -> {
// we get reuse if we _don't_ propagate a new fact to the callee entry
final boolean gotReuse = !propagate(calleeEntry, d1, calleeEntry, d1);
recordCall(edge.target, calleeEntry, d1, gotReuse);
newCallExplodedEdge(edge, calleeEntry, d1);
// cache the fact that we've flowed <c, d2> -> <callee, d1> by a
// call flow
callFlow.addCallEdge(callNodeNum, edge.d2, d1);
// handle summary edges now as well. this is different from the PoPL
// 95 paper.
if (summaries != null) {
// for each exit from the callee
P p = supergraph.getProcOf(calleeEntry);
T[] exits = supergraph.getExitsForProcedure(p);
for (int e = 0; e < exits.length; e++) {
final T exit = exits[e];
if (DEBUG_LEVEL > 0) {
assert supergraph.containsNode(exit);
}
int x_num = supergraph.getLocalBlockNumber(exit);
// reachedBySummary := {d2} s.t. <callee,d1> -> <exit,d2>
// was recorded as a summary edge
IntSet reachedBySummary = summaries.getSummaryEdges(s_p_num, x_num, d1);
if (reachedBySummary != null) {
for (final T returnSite : returnSitesForCallee) {
// if "exit" is a valid exit from the callee to the return
// site being processed
if (supergraph.hasEdge(exit, returnSite)) {
final IFlowFunction retf = flowFunctionMap.getReturnFlowFunction(edge.target, exit, returnSite);
reachedBySummary.foreach(d2 -> {
assert curSummaryEdge == null : "curSummaryEdge should be null here";
curSummaryEdge = PathEdge.createPathEdge(calleeEntry, d1, exit, d2);
if (retf instanceof IBinaryReturnFlowFunction) {
final IntSet D51 = computeBinaryFlow(edge.d2, d2, (IBinaryReturnFlowFunction) retf);
if (D51 != null) {
D51.foreach(d5 -> {
newSummaryEdge(edge, curSummaryEdge, returnSite, d5);
propagate(edge.entry, edge.d1, returnSite, d5);
});
}
});
}
} else {
final IntSet D52 = computeFlow(d2, (IUnaryFlowFunction) retf);
if (D52 != null) {
D52.foreach(d5 -> {
newSummaryEdge(edge, curSummaryEdge, returnSite, d5);
propagate(edge.entry, edge.d1, returnSite, d5);
});
}
}
curSummaryEdge = null;
});
}
}
}
@ -948,16 +915,13 @@ public class TabulationSolver<T, P, F> {
StringBuffer result = new StringBuffer();
TreeMap<Object, TreeSet<T>> map = new TreeMap<Object, TreeSet<T>>(ToStringComparator.instance());
Comparator<Object> c = new Comparator<Object>() {
@Override
public int compare(Object o1, Object o2) {
if (!(o1 instanceof IBasicBlock)) {
return -1;
}
IBasicBlock bb1 = (IBasicBlock) o1;
IBasicBlock bb2 = (IBasicBlock) o2;
return bb1.getNumber() - bb2.getNumber();
Comparator<Object> c = (o1, o2) -> {
if (!(o1 instanceof IBasicBlock)) {
return -1;
}
IBasicBlock bb1 = (IBasicBlock) o1;
IBasicBlock bb2 = (IBasicBlock) o2;
return bb1.getNumber() - bb2.getNumber();
};
for (Iterator<? extends T> it = supergraph.iterator(); it.hasNext();) {
T n = it.next();

View File

@ -129,7 +129,6 @@ import com.ibm.wala.util.collections.Util;
import com.ibm.wala.util.debug.Assertions;
import com.ibm.wala.util.debug.UnimplementedError;
import com.ibm.wala.util.intset.IntSet;
import com.ibm.wala.util.intset.IntSetAction;
import com.ibm.wala.util.intset.MutableIntSet;
import com.ibm.wala.util.intset.MutableIntSetFactory;
import com.ibm.wala.util.intset.MutableMapping;
@ -286,13 +285,7 @@ public class DemandRefinementPointsTo extends AbstractDemandPointsTo {
throw new IllegalArgumentException("p2SetWithStates == null");
}
Collection<T> finalP2Set = Iterator2Collection.toSet(new MapIterator<WithState<T>, T>(p2SetWithStates.iterator(),
new Function<WithState<T>, T>() {
@Override
public T apply(WithState<T> object) {
return object.getWrapped();
}
}));
object -> object.getWrapped()));
return finalP2Set;
}
@ -502,13 +495,7 @@ public class DemandRefinementPointsTo extends AbstractDemandPointsTo {
* do all instance keys in p2set pass ikeyPred?
*/
private static boolean passesPred(Collection<InstanceKeyAndState> curP2Set, final Predicate<InstanceKey> ikeyPred) {
return Util.forAll(curP2Set, new Predicate<InstanceKeyAndState>() {
@Override
public boolean test(InstanceKeyAndState t) {
return ikeyPred.test(t.getInstanceKey());
}
});
return Util.forAll(curP2Set, t -> ikeyPred.test(t.getInstanceKey()));
}
/**
@ -910,47 +897,32 @@ public class DemandRefinementPointsTo extends AbstractDemandPointsTo {
if (typeFilter instanceof SingleClassFilter) {
final IClass concreteType = ((SingleClassFilter) typeFilter).getConcreteType();
final MutableIntSet tmp = intSetFactory.make();
vals.foreach(new IntSetAction() {
@Override
public void act(int x) {
InstanceKeyAndState ikAndState = ikAndStates.getMappedObject(x);
if (cha.isAssignableFrom(concreteType, ikAndState.getInstanceKey().getConcreteType())) {
tmp.add(x);
}
vals.foreach(x -> {
InstanceKeyAndState ikAndState = ikAndStates.getMappedObject(x);
if (cha.isAssignableFrom(concreteType, ikAndState.getInstanceKey().getConcreteType())) {
tmp.add(x);
}
});
vals = tmp;
} else if (typeFilter instanceof MultipleClassesFilter) {
final MutableIntSet tmp = intSetFactory.make();
vals.foreach(new IntSetAction() {
@Override
public void act(int x) {
InstanceKeyAndState ikAndState = ikAndStates.getMappedObject(x);
for (IClass t : ((MultipleClassesFilter) typeFilter).getConcreteTypes()) {
if (cha.isAssignableFrom(t, ikAndState.getInstanceKey().getConcreteType())) {
tmp.add(x);
}
vals.foreach(x -> {
InstanceKeyAndState ikAndState = ikAndStates.getMappedObject(x);
for (IClass t : ((MultipleClassesFilter) typeFilter).getConcreteTypes()) {
if (cha.isAssignableFrom(t, ikAndState.getInstanceKey().getConcreteType())) {
tmp.add(x);
}
}
});
vals = tmp;
} else if (typeFilter instanceof SingleInstanceFilter) {
final InstanceKey theOnlyInstanceKey = ((SingleInstanceFilter) typeFilter).getInstance();
final MutableIntSet tmp = intSetFactory.make();
vals.foreach(new IntSetAction() {
@Override
public void act(int x) {
InstanceKeyAndState ikAndState = ikAndStates.getMappedObject(x);
if (ikAndState.getInstanceKey().equals(theOnlyInstanceKey)) {
tmp.add(x);
}
vals.foreach(x -> {
InstanceKeyAndState ikAndState = ikAndStates.getMappedObject(x);
if (ikAndState.getInstanceKey().equals(theOnlyInstanceKey)) {
tmp.add(x);
}
});
vals = tmp;
} else {
@ -983,15 +955,10 @@ public class DemandRefinementPointsTo extends AbstractDemandPointsTo {
void handleCopy(final PointerKeyAndState curPkAndState, final PointerKey succPk, final IFlowLabel label) {
assert !label.isBarred();
State curState = curPkAndState.getState();
doTransition(curState, label, new Function<State, Object>() {
@Override
public Object apply(State nextState) {
PointerKeyAndState succPkAndState = new PointerKeyAndState(succPk, nextState);
handleCopy(curPkAndState, succPkAndState, label);
return null;
}
doTransition(curState, label, nextState -> {
PointerKeyAndState succPkAndState = new PointerKeyAndState(succPk, nextState);
handleCopy(curPkAndState, succPkAndState, label);
return null;
});
}
@ -1153,43 +1120,28 @@ public class DemandRefinementPointsTo extends AbstractDemandPointsTo {
final PointerKeyAndState defAndState = new PointerKeyAndState(heapModel.getPointerKeyForLocal(caller, invokeInstr
.getDef()), receiverState);
final PointerKey ret = heapModel.getPointerKeyForReturnValue(targetForCall);
doTransition(receiverState, returnLabel, new Function<State, Object>() {
@Override
public Object apply(State retState) {
repropCallArg(defAndState, new PointerKeyAndState(ret, retState), returnLabel.bar());
return null;
}
doTransition(receiverState, returnLabel, retState -> {
repropCallArg(defAndState, new PointerKeyAndState(ret, retState), returnLabel.bar());
return null;
});
}
final PointerKeyAndState exc = new PointerKeyAndState(heapModel.getPointerKeyForLocal(caller, invokeInstr
.getException()), receiverState);
final PointerKey excRet = heapModel.getPointerKeyForExceptionalReturnValue(targetForCall);
doTransition(receiverState, returnLabel, new Function<State, Object>() {
@Override
public Object apply(State excRetState) {
repropCallArg(exc, new PointerKeyAndState(excRet, excRetState), returnLabel.bar());
return null;
}
doTransition(receiverState, returnLabel, excRetState -> {
repropCallArg(exc, new PointerKeyAndState(excRet, excRetState), returnLabel.bar());
return null;
});
for (Iterator<Integer> iter = new PointerParamValueNumIterator(targetForCall); iter.hasNext();) {
final int formalNum = iter.next();
final int actualNum = formalNum - 1;
final ParamBarLabel paramBarLabel = ParamBarLabel.make(new CallerSiteContext(caller, call));
doTransition(receiverState, paramBarLabel, new Function<State, Object>() {
@Override
public Object apply(State formalState) {
repropCallArg(
new PointerKeyAndState(heapModel.getPointerKeyForLocal(targetForCall, formalNum), formalState),
new PointerKeyAndState(heapModel.getPointerKeyForLocal(caller, invokeInstr.getUse(actualNum)), receiverState),
paramBarLabel);
return null;
}
doTransition(receiverState, paramBarLabel, formalState -> {
repropCallArg(
new PointerKeyAndState(heapModel.getPointerKeyForLocal(targetForCall, formalNum), formalState),
new PointerKeyAndState(heapModel.getPointerKeyForLocal(caller, invokeInstr.getUse(actualNum)), receiverState),
paramBarLabel);
return null;
});
}
}
@ -1250,17 +1202,12 @@ public class DemandRefinementPointsTo extends AbstractDemandPointsTo {
if (DEBUG) {
System.err.println("alloc " + ik + " assigned to " + curPk);
}
doTransition(curState, label, new Function<State, Object>() {
@Override
public Object apply(State newState) {
InstanceKeyAndState ikAndState = new InstanceKeyAndState(ik, newState);
int n = ikAndStates.add(ikAndState);
findOrCreate(pkToP2Set, curPkAndState).add(n);
addToPToWorklist(curPkAndState);
return null;
}
doTransition(curState, label, newState -> {
InstanceKeyAndState ikAndState = new InstanceKeyAndState(ik, newState);
int n = ikAndStates.add(ikAndState);
findOrCreate(pkToP2Set, curPkAndState).add(n);
addToPToWorklist(curPkAndState);
return null;
});
}
@ -1775,15 +1722,10 @@ public class DemandRefinementPointsTo extends AbstractDemandPointsTo {
public void visitAssignGlobal(final AssignGlobalLabel label, Object dst) {
for (Iterator<? extends Object> readIter = g.getReadsOfStaticField((StaticFieldKey) dst); readIter.hasNext();) {
final PointerKey predPk = (PointerKey) readIter.next();
doTransition(curState, AssignGlobalBarLabel.v(), new Function<State, Object>() {
@Override
public Object apply(State predPkState) {
PointerKeyAndState predPkAndState = new PointerKeyAndState(predPk, predPkState);
handleTrackedPred(trackedSet, predPkAndState, AssignGlobalBarLabel.v());
return null;
}
doTransition(curState, AssignGlobalBarLabel.v(), predPkState -> {
PointerKeyAndState predPkAndState = new PointerKeyAndState(predPk, predPkState);
handleTrackedPred(trackedSet, predPkAndState, AssignGlobalBarLabel.v());
return null;
});
}
}
@ -1807,15 +1749,10 @@ public class DemandRefinementPointsTo extends AbstractDemandPointsTo {
// send to all getfield sources
for (Iterator<PointerKey> readIter = g.getReadsOfInstanceField(storeBase, field); readIter.hasNext();) {
final PointerKey predPk = readIter.next();
doTransition(curState, MatchBarLabel.v(), new Function<State, Object>() {
@Override
public Object apply(State predPkState) {
PointerKeyAndState predPkAndState = new PointerKeyAndState(predPk, predPkState);
handleTrackedPred(trackedSet, predPkAndState, MatchBarLabel.v());
return null;
}
doTransition(curState, MatchBarLabel.v(), predPkState -> {
PointerKeyAndState predPkAndState = new PointerKeyAndState(predPk, predPkState);
handleTrackedPred(trackedSet, predPkAndState, MatchBarLabel.v());
return null;
});
}
@ -1846,15 +1783,10 @@ public class DemandRefinementPointsTo extends AbstractDemandPointsTo {
@Override
public void visitAssign(final AssignLabel label, Object dst) {
final PointerKey predPk = (PointerKey) dst;
doTransition(curState, label.bar(), new Function<State, Object>() {
@Override
public Object apply(State predPkState) {
PointerKeyAndState predPkAndState = new PointerKeyAndState(predPk, predPkState);
handleTrackedPred(trackedSet, predPkAndState, label.bar());
return null;
}
doTransition(curState, label.bar(), predPkState -> {
PointerKeyAndState predPkAndState = new PointerKeyAndState(predPk, predPkState);
handleTrackedPred(trackedSet, predPkAndState, label.bar());
return null;
});
}
@ -1865,14 +1797,10 @@ public class DemandRefinementPointsTo extends AbstractDemandPointsTo {
@Override
void handle(PointerKeyAndState src, final PointerKey dst, final IFlowLabel label) {
assert src == curPkAndState;
doTransition(curState, label, new Function<State, Object>() {
@Override
public Object apply(State dstState) {
PointerKeyAndState dstAndState = new PointerKeyAndState(dst, dstState);
handleTrackedPred(trackedSet, dstAndState, label);
return null;
}
doTransition(curState, label, dstState -> {
PointerKeyAndState dstAndState = new PointerKeyAndState(dst, dstState);
handleTrackedPred(trackedSet, dstAndState, label);
return null;
});
}
@ -2127,13 +2055,9 @@ public class DemandRefinementPointsTo extends AbstractDemandPointsTo {
final PointerKey actualPk = heapModel.getPointerKeyForLocal(caller, callInstr.getUse(paramPos));
assert g.containsNode(actualPk);
assert g.containsNode(localPk);
doTransition(curState, paramLabel, new Function<State, Object>() {
@Override
public Object apply(State nextState) {
propagate(new PointerKeyAndState(actualPk, nextState));
return null;
}
doTransition(curState, paramLabel, nextState -> {
propagate(new PointerKeyAndState(actualPk, nextState));
return null;
});
}
}
@ -2180,14 +2104,9 @@ public class DemandRefinementPointsTo extends AbstractDemandPointsTo {
final PointerKey retVal = isExceptional ? heapModel.getPointerKeyForExceptionalReturnValue(callee) : heapModel
.getPointerKeyForReturnValue(callee);
assert g.containsNode(retVal);
doTransition(curState, ReturnLabel.make(callSiteAndCGNode), new Function<State, Object>() {
@Override
public Object apply(State nextState) {
propagate(new PointerKeyAndState(retVal, nextState));
return null;
}
doTransition(curState, ReturnLabel.make(callSiteAndCGNode), nextState -> {
propagate(new PointerKeyAndState(retVal, nextState));
return null;
});
}
} else {
@ -2202,14 +2121,9 @@ public class DemandRefinementPointsTo extends AbstractDemandPointsTo {
final PointerKey retVal = isExceptional ? heapModel.getPointerKeyForExceptionalReturnValue(callee) : heapModel
.getPointerKeyForReturnValue(callee);
assert g.containsNode(retVal);
doTransition(curState, ReturnLabel.make(callSiteAndCGNode), new Function<State, Object>() {
@Override
public Object apply(State nextState) {
propagate(new PointerKeyAndState(retVal, nextState));
return null;
}
doTransition(curState, ReturnLabel.make(callSiteAndCGNode), nextState -> {
propagate(new PointerKeyAndState(retVal, nextState));
return null;
});
}
}
@ -2305,17 +2219,12 @@ public class DemandRefinementPointsTo extends AbstractDemandPointsTo {
if (DEBUG_TOPLEVEL) {
System.err.println("toplevel alloc " + ik + " assigned to " + curPk);
}
doTransition(curState, label, new Function<State, Object>() {
@Override
public Object apply(State newState) {
// just check if ik violates the pred
if (!pred.test(ik)) {
foundBadInstanceKey = true;
}
return null;
doTransition(curState, label, newState -> {
// just check if ik violates the pred
if (!pred.test(ik)) {
foundBadInstanceKey = true;
}
return null;
});
}
@ -2360,14 +2269,9 @@ public class DemandRefinementPointsTo extends AbstractDemandPointsTo {
for (Iterator<PointerKey> writesToInstanceField = g.getWritesToInstanceField(loadBase, field); writesToInstanceField
.hasNext();) {
final PointerKey writtenPk = writesToInstanceField.next();
doTransition(curState, MatchLabel.v(), new Function<State, Object>() {
@Override
public Object apply(State nextState) {
h.propagate(new PointerKeyAndState(writtenPk, nextState));
return null;
}
doTransition(curState, MatchLabel.v(), nextState -> {
h.propagate(new PointerKeyAndState(writtenPk, nextState));
return null;
});
}
}
@ -2418,14 +2322,9 @@ public class DemandRefinementPointsTo extends AbstractDemandPointsTo {
for (Iterator<? extends Object> writesToStaticField = g.getWritesToStaticField((StaticFieldKey) dst); writesToStaticField
.hasNext();) {
final PointerKey writtenPk = (PointerKey) writesToStaticField.next();
doTransition(curState, label, new Function<State, Object>() {
@Override
public Object apply(State nextState) {
h.propagate(new PointerKeyAndState(writtenPk, nextState));
return null;
}
doTransition(curState, label, nextState -> {
h.propagate(new PointerKeyAndState(writtenPk, nextState));
return null;
});
}
@ -2434,14 +2333,9 @@ public class DemandRefinementPointsTo extends AbstractDemandPointsTo {
@Override
public void visitAssign(AssignLabel label, Object dst) {
final PointerKey succPk = (PointerKey) dst;
doTransition(curState, label, new Function<State, Object>() {
@Override
public Object apply(State nextState) {
h.propagate(new PointerKeyAndState(succPk, nextState));
return null;
}
doTransition(curState, label, nextState -> {
h.propagate(new PointerKeyAndState(succPk, nextState));
return null;
});
}

View File

@ -57,11 +57,7 @@ public class LocalLiveRangeAnalysis {
final Collection<BasicBlock> uses = findBlocks(ir, du.getUses(v));
// a filter which accepts everything but the block which defs v
Predicate<Object> notDef = new Predicate<Object>() {
@Override public boolean test(Object o) {
return (defBlock == null || !defBlock.equals(o));
}
};
Predicate<Object> notDef = o -> (defBlock == null || !defBlock.equals(o));
if (defBlock != null && defBlock.equals(queryBlock)) {
// for now, conservatively say it's live. fix this later if necessary.

View File

@ -20,8 +20,6 @@ import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.jar.Attributes;
import java.util.jar.JarFile;
import java.util.jar.Manifest;
@ -379,16 +377,7 @@ public class AnalysisScope {
private JarFile getRtJar() {
return RtJar.getRtJar(
new MapIterator<Module,JarFile>(
new FilterIterator<Module>(getModules(getPrimordialLoader()).iterator(), new Predicate<Module>() {
@Override
public boolean test(Module M) {
return M instanceof JarFileModule;
} }), new Function<Module,JarFile>() {
@Override
public JarFile apply(Module M) {
return ((JarFileModule) M).getJarFile();
} }));
new FilterIterator<Module>(getModules(getPrimordialLoader()).iterator(), M -> M instanceof JarFileModule), M -> ((JarFileModule) M).getJarFile()));
}
public String getJavaLibraryVersion() throws IllegalStateException {

View File

@ -16,7 +16,6 @@ import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.Stack;
import java.util.function.Function;
import java.util.function.Predicate;
import com.ibm.wala.classLoader.CallSiteReference;
@ -163,21 +162,14 @@ public class CHACallGraph extends BasicCallGraph<CHAContextInterpreter> {
new MapIterator<IMethod,CGNode>(
new FilterIterator<IMethod>(
getPossibleTargets(site),
new Predicate<IMethod>() {
@Override public boolean test(IMethod o) {
return isRelevantMethod(o);
}
}
o -> isRelevantMethod(o)
),
new Function<IMethod,CGNode>() {
@Override
public CGNode apply(IMethod object) {
try {
return findOrCreateNode(object, Everywhere.EVERYWHERE);
} catch (CancelException e) {
assert false : e.toString();
return null;
}
object -> {
try {
return findOrCreateNode(object, Everywhere.EVERYWHERE);
} catch (CancelException e) {
assert false : e.toString();
return null;
}
}));
}
@ -191,11 +183,7 @@ public class CHACallGraph extends BasicCallGraph<CHAContextInterpreter> {
public Iterator<CallSiteReference> getPossibleSites(final CGNode src, final CGNode target) {
return
new FilterIterator<CallSiteReference>(getInterpreter(src).iterateCallSites(src),
new Predicate<CallSiteReference>() {
@Override public boolean test(CallSiteReference o) {
return getPossibleTargets(src, o).contains(target);
}
});
o -> getPossibleTargets(src, o).contains(target));
}
private class CHARootNode extends CHANode {

View File

@ -16,7 +16,6 @@ import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import java.util.function.IntFunction;
import java.util.function.Predicate;
import com.ibm.wala.cfg.ControlFlowGraph;
import com.ibm.wala.classLoader.CallSiteReference;
@ -187,11 +186,9 @@ public class ExplicitCallGraph extends BasicCallGraph<SSAContextInterpreter> imp
*/
protected Iterator<CallSiteReference> getPossibleSites(final CGNode to) {
final int n = getCallGraph().getNumber(to);
return new FilterIterator<CallSiteReference>(iterateCallSites(), new Predicate<CallSiteReference>() {
@Override public boolean test(CallSiteReference o) {
IntSet s = getPossibleTargetNumbers(o);
return s == null ? false : s.contains(n);
}
return new FilterIterator<CallSiteReference>(iterateCallSites(), o -> {
IntSet s = getPossibleTargetNumbers(o);
return s == null ? false : s.contains(n);
});
}
@ -356,15 +353,12 @@ public class ExplicitCallGraph extends BasicCallGraph<SSAContextInterpreter> imp
protected class ExplicitEdgeManager implements NumberedEdgeManager<CGNode> {
final IntFunction<CGNode> toNode = new IntFunction<CGNode>() {
@Override
public CGNode apply(int i) {
CGNode result = getNode(i);
// if (Assertions.verifyAssertions && result == null) {
// Assertions.UNREACHABLE("uh oh " + i);
// }
return result;
}
final IntFunction<CGNode> toNode = i -> {
CGNode result = getNode(i);
// if (Assertions.verifyAssertions && result == null) {
// Assertions.UNREACHABLE("uh oh " + i);
// }
return result;
};
/**

View File

@ -13,7 +13,6 @@ package com.ibm.wala.ipa.callgraph.impl;
import java.util.Collection;
import java.util.Iterator;
import java.util.Set;
import java.util.function.Predicate;
import com.ibm.wala.classLoader.CallSiteReference;
import com.ibm.wala.classLoader.IMethod;
@ -53,11 +52,7 @@ public class PartialCallGraph extends DelegatingGraph<CGNode> implements CallGra
* @param nodes set of nodes that will be included in the new, partial call graph
*/
public static PartialCallGraph make(final CallGraph cg, final Collection<CGNode> partialRoots, final Collection<CGNode> nodes) {
Graph<CGNode> partialGraph = GraphSlicer.prune(cg, new Predicate<CGNode>() {
@Override public boolean test(CGNode o) {
return nodes.contains(o);
}
});
Graph<CGNode> partialGraph = GraphSlicer.prune(cg, o -> nodes.contains(o));
return new PartialCallGraph(cg, partialRoots, partialGraph);
}
@ -69,11 +64,7 @@ public class PartialCallGraph extends DelegatingGraph<CGNode> implements CallGra
*/
public static PartialCallGraph make(CallGraph cg, Collection<CGNode> partialRoots) {
final Set<CGNode> nodes = DFS.getReachableNodes(cg, partialRoots);
Graph<CGNode> partialGraph = GraphSlicer.prune(cg, new Predicate<CGNode>() {
@Override public boolean test(CGNode o) {
return nodes.contains(o);
}
});
Graph<CGNode> partialGraph = GraphSlicer.prune(cg, o -> nodes.contains(o));
return new PartialCallGraph(cg, partialRoots, partialGraph);
}
@ -122,11 +113,7 @@ public class PartialCallGraph extends DelegatingGraph<CGNode> implements CallGra
@Override
public Iterator<CGNode> iterateNodes(IntSet nodes) {
return new FilterIterator<CGNode>(cg.iterateNodes(nodes), new Predicate<CGNode>() {
@Override public boolean test(CGNode o) {
return containsNode(o);
}
});
return new FilterIterator<CGNode>(cg.iterateNodes(nodes), o -> containsNode(o));
}
@Override

View File

@ -167,12 +167,7 @@ public class Util {
}
}
}
return new Iterable<Entrypoint>() {
@Override
public Iterator<Entrypoint> iterator() {
return result.iterator();
}
};
return () -> result.iterator();
}
/**
@ -218,32 +213,29 @@ public class Util {
}
}
return new Iterable<Entrypoint>() {
@Override
public Iterator<Entrypoint> iterator() {
final Atom mainMethod = Atom.findOrCreateAsciiAtom("main");
return new Iterator<Entrypoint>() {
private int index = 0;
return () -> {
final Atom mainMethod = Atom.findOrCreateAsciiAtom("main");
return new Iterator<Entrypoint>() {
private int index = 0;
@Override
public void remove() {
Assertions.UNREACHABLE();
}
@Override
public void remove() {
Assertions.UNREACHABLE();
}
@Override
public boolean hasNext() {
return index < classNames.length;
}
@Override
public boolean hasNext() {
return index < classNames.length;
}
@Override
public Entrypoint next() {
TypeReference T = TypeReference.findOrCreate(loaderRef, TypeName.string2TypeName(classNames[index++]));
MethodReference mainRef = MethodReference.findOrCreate(T, mainMethod, Descriptor
.findOrCreateUTF8("([Ljava/lang/String;)V"));
return new DefaultEntrypoint(mainRef, cha);
}
};
}
@Override
public Entrypoint next() {
TypeReference T = TypeReference.findOrCreate(loaderRef, TypeName.string2TypeName(classNames[index++]));
MethodReference mainRef = MethodReference.findOrCreate(T, mainMethod, Descriptor
.findOrCreateUTF8("([Ljava/lang/String;)V"));
return new DefaultEntrypoint(mainRef, cha);
}
};
};
}

View File

@ -11,8 +11,6 @@
package com.ibm.wala.ipa.callgraph.propagation;
import java.util.Iterator;
import java.util.function.Function;
import java.util.function.Predicate;
import com.ibm.wala.classLoader.IClass;
import com.ibm.wala.classLoader.IMethod;
@ -96,17 +94,8 @@ public class AllocationSite implements InstanceKey {
return new MapIterator<CGNode, Pair<CGNode, NewSiteReference>>(
new FilterIterator<CGNode>(
CG.getNodes(method.getReference()).iterator(),
new Predicate<CGNode>() {
@Override public boolean test(CGNode o) {
return o.getMethod().equals(method);
}
}
o -> o.getMethod().equals(method)
),
new Function<CGNode, Pair<CGNode, NewSiteReference>>() {
@Override
public Pair<CGNode, NewSiteReference> apply(CGNode object) {
return Pair.make(object, site);
}
});
object -> Pair.make(object, site));
}
}

View File

@ -12,8 +12,6 @@ package com.ibm.wala.ipa.callgraph.propagation;
import java.util.Collection;
import java.util.Iterator;
import java.util.function.Function;
import java.util.function.Predicate;
import com.ibm.wala.classLoader.IClass;
import com.ibm.wala.classLoader.NewSiteReference;
@ -110,18 +108,9 @@ public final class ConcreteTypeKey implements InstanceKey {
return new MapIterator<NewSiteReference, Pair<CGNode, NewSiteReference>>(
new FilterIterator<NewSiteReference>(
outer.iterateNewSites(),
new Predicate<NewSiteReference>() {
@Override public boolean test(NewSiteReference o) {
return o.getDeclaredType().equals(type.getReference());
}
}
o -> o.getDeclaredType().equals(type.getReference())
),
new Function<NewSiteReference, Pair<CGNode, NewSiteReference>>() {
@Override
public Pair<CGNode, NewSiteReference> apply(NewSiteReference object) {
return Pair.make(outer, object);
}
});
object -> Pair.make(outer, object));
}
};
}

View File

@ -11,7 +11,6 @@
package com.ibm.wala.ipa.callgraph.propagation;
import java.util.Iterator;
import java.util.function.Predicate;
import com.ibm.wala.util.collections.FilterIterator;
import com.ibm.wala.util.collections.IVector;
@ -201,11 +200,7 @@ public class PointsToMap {
* @return {@link Iterator}&lt;{@link PointerKey}&gt;
*/
public Iterator<PointerKey> getTransitiveRoots() {
return new FilterIterator<PointerKey>(iterateKeys(), new Predicate<PointerKey>() {
@Override public boolean test(PointerKey o) {
return isTransitiveRoot(o);
}
});
return new FilterIterator<PointerKey>(iterateKeys(), o -> isTransitiveRoot(o));
}
/**

View File

@ -19,7 +19,6 @@ import com.ibm.wala.ssa.IR;
import com.ibm.wala.types.TypeReference;
import com.ibm.wala.util.debug.Assertions;
import com.ibm.wala.util.intset.IntSet;
import com.ibm.wala.util.intset.IntSetAction;
import com.ibm.wala.util.intset.MutableMapping;
import com.ibm.wala.util.intset.MutableSparseIntSet;
@ -120,21 +119,16 @@ public class PointsToSetVariable extends IntSetVariable<PointsToSetVariable> {
if (cha.isAssignableFrom(cha.lookupClass(TypeReference.JavaLangThrowable), type)) {
return;
}
b.foreach(new IntSetAction() {
@Override
public void act(int x) {
InstanceKey ik = instanceKeys.getMappedObject(x);
IClass concreteType = ik.getConcreteType();
if (!cha.isAssignableFrom(type, concreteType)) {
System.err.println("BOOM");
System.err.println(ir);
System.err.println(lpk + " type " + type);
System.err.println(ik + " type " + concreteType);
Assertions.UNREACHABLE();
}
b.foreach(x -> {
InstanceKey ik = instanceKeys.getMappedObject(x);
IClass concreteType = ik.getConcreteType();
if (!cha.isAssignableFrom(type, concreteType)) {
System.err.println("BOOM");
System.err.println(ir);
System.err.println(lpk + " type " + type);
System.err.println(ik + " type " + concreteType);
Assertions.UNREACHABLE();
}
});
}

View File

@ -839,27 +839,24 @@ public abstract class PropagationCallGraphBuilder implements CallGraphBuilder<In
final PointerKey dVal = def.getPointerKey();
final MutableBoolean sideEffect = new MutableBoolean();
IntSetAction action = new IntSetAction() {
@Override
public void act(int i) {
InstanceKey I = system.getInstanceKey(i);
if (!I.getConcreteType().isArrayClass()) {
return;
}
TypeReference C = I.getConcreteType().getReference().getArrayElementType();
if (C.isPrimitiveType()) {
return;
}
PointerKey p = getPointerKeyForArrayContents(I);
if (p == null) {
return;
}
if (DEBUG_ARRAY_LOAD) {
System.err.println("ArrayLoad add assign: " + dVal + " " + p);
}
sideEffect.b |= system.newFieldRead(dVal, assignOperator, p);
IntSetAction action = i -> {
InstanceKey I = system.getInstanceKey(i);
if (!I.getConcreteType().isArrayClass()) {
return;
}
TypeReference C = I.getConcreteType().getReference().getArrayElementType();
if (C.isPrimitiveType()) {
return;
}
PointerKey p = getPointerKeyForArrayContents(I);
if (p == null) {
return;
}
if (DEBUG_ARRAY_LOAD) {
System.err.println("ArrayLoad add assign: " + dVal + " " + p);
}
sideEffect.b |= system.newFieldRead(dVal, assignOperator, p);
};
if (priorInstances != null) {
rhs.getValue().foreachExcluding(priorInstances, action);
@ -1022,20 +1019,17 @@ public abstract class PropagationCallGraphBuilder implements CallGraphBuilder<In
}
}
final MutableBoolean sideEffect = new MutableBoolean();
IntSetAction action = new IntSetAction() {
@Override
public void act(int i) {
InstanceKey I = system.getInstanceKey(i);
if (!representsNullType(I)) {
PointerKey p = getPointerKeyForInstanceField(I, getField());
IntSetAction action = i -> {
InstanceKey I = system.getInstanceKey(i);
if (!representsNullType(I)) {
PointerKey p = getPointerKeyForInstanceField(I, getField());
if (p != null) {
if (DEBUG_GET) {
String S = "Getfield add constraint " + dVal + " " + p;
System.err.println(S);
}
sideEffect.b |= system.newFieldRead(dVal, assignOperator, p);
if (p != null) {
if (DEBUG_GET) {
String S = "Getfield add constraint " + dVal + " " + p;
System.err.println(S);
}
sideEffect.b |= system.newFieldRead(dVal, assignOperator, p);
}
}
};
@ -1137,23 +1131,20 @@ public abstract class PropagationCallGraphBuilder implements CallGraphBuilder<In
Assertions.UNREACHABLE();
}
final MutableBoolean sideEffect = new MutableBoolean();
IntSetAction action = new IntSetAction() {
@Override
public void act(int i) {
InstanceKey I = system.getInstanceKey(i);
if (!representsNullType(I)) {
IntSetAction action = i -> {
InstanceKey I = system.getInstanceKey(i);
if (!representsNullType(I)) {
if (DEBUG_PUT) {
String S1 = "Putfield consider instance " + I;
System.err.println(S1);
}
PointerKey p = getPointerKeyForInstanceField(I, getField());
if (p != null) {
if (DEBUG_PUT) {
String S = "Putfield consider instance " + I;
System.err.println(S);
}
PointerKey p = getPointerKeyForInstanceField(I, getField());
if (p != null) {
if (DEBUG_PUT) {
String S = "Putfield add constraint " + p + " " + pVal;
System.err.println(S);
}
sideEffect.b |= system.newFieldWrite(p, assign, pVal);
String S2 = "Putfield add constraint " + p + " " + pVal;
System.err.println(S2);
}
sideEffect.b |= system.newFieldWrite(p, assign, pVal);
}
}
};
@ -1240,15 +1231,12 @@ public abstract class PropagationCallGraphBuilder implements CallGraphBuilder<In
}
IntSet value = ref.getValue();
final MutableBoolean sideEffect = new MutableBoolean();
IntSetAction action = new IntSetAction() {
@Override
public void act(int i) {
InstanceKey I = system.getInstanceKey(i);
if (!representsNullType(I)) {
PointerKey p = getPointerKeyForInstanceField(I, field);
if (p != null) {
sideEffect.b |= system.newConstraint(p, instance);
}
IntSetAction action = i -> {
InstanceKey I = system.getInstanceKey(i);
if (!representsNullType(I)) {
PointerKey p = getPointerKeyForInstanceField(I, field);
if (p != null) {
sideEffect.b |= system.newConstraint(p, instance);
}
}
};
@ -1314,33 +1302,30 @@ public abstract class PropagationCallGraphBuilder implements CallGraphBuilder<In
}
IntSet value = arrayref.getValue();
final MutableBoolean sideEffect = new MutableBoolean();
IntSetAction action = new IntSetAction() {
@Override
public void act(int i) {
InstanceKey I = system.getInstanceKey(i);
if (!I.getConcreteType().isArrayClass()) {
return;
IntSetAction action = i -> {
InstanceKey I = system.getInstanceKey(i);
if (!I.getConcreteType().isArrayClass()) {
return;
}
if (I instanceof ZeroLengthArrayInNode) {
return;
}
TypeReference C = I.getConcreteType().getReference().getArrayElementType();
if (C.isPrimitiveType()) {
return;
}
IClass contents = getClassHierarchy().lookupClass(C);
if (contents == null) {
assert false : "null type for " + C + " " + I.getConcreteType();
}
PointerKey p = getPointerKeyForArrayContents(I);
if (contents.isInterface()) {
if (getClassHierarchy().implementsInterface(instance.getConcreteType(), contents)) {
sideEffect.b |= system.newConstraint(p, instance);
}
if (I instanceof ZeroLengthArrayInNode) {
return;
}
TypeReference C = I.getConcreteType().getReference().getArrayElementType();
if (C.isPrimitiveType()) {
return;
}
IClass contents = getClassHierarchy().lookupClass(C);
if (contents == null) {
assert false : "null type for " + C + " " + I.getConcreteType();
}
PointerKey p = getPointerKeyForArrayContents(I);
if (contents.isInterface()) {
if (getClassHierarchy().implementsInterface(instance.getConcreteType(), contents)) {
sideEffect.b |= system.newConstraint(p, instance);
}
} else {
if (getClassHierarchy().isSubclassOf(instance.getConcreteType(), contents)) {
sideEffect.b |= system.newConstraint(p, instance);
}
} else {
if (getClassHierarchy().isSubclassOf(instance.getConcreteType(), contents)) {
sideEffect.b |= system.newConstraint(p, instance);
}
}
};

View File

@ -16,7 +16,6 @@ import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.function.Predicate;
import com.ibm.wala.fixedpoint.impl.GeneralStatement;
import com.ibm.wala.fixpoint.AbstractOperator;
@ -271,11 +270,7 @@ public class PropagationGraph implements IFixedPointSystem<PointsToSetVariable>
@Override
public Iterator<AbstractStatement> getStatements() {
Iterator<INodeWithNumber> it = new FilterIterator<>(delegateGraph.iterator(), new Predicate<INodeWithNumber>() {
@Override public boolean test(INodeWithNumber x) {
return x instanceof AbstractStatement;
}
});
Iterator<INodeWithNumber> it = new FilterIterator<>(delegateGraph.iterator(), x -> x instanceof AbstractStatement);
Iterator<AbstractStatement> converted = new MapIterator<>(it, AbstractStatement.class::cast);
return new CompoundIterator<AbstractStatement>(converted, new GlobalImplicitIterator());
}
@ -762,11 +757,7 @@ public class PropagationGraph implements IFixedPointSystem<PointsToSetVariable>
@Override
public Iterator<PointsToSetVariable> getVariables() {
Iterator<INodeWithNumber> it = new FilterIterator<>(delegateGraph.iterator(), new Predicate<INodeWithNumber>() {
@Override public boolean test(INodeWithNumber x) {
return x instanceof IVariable;
}
});
Iterator<INodeWithNumber> it = new FilterIterator<>(delegateGraph.iterator(), x -> x instanceof IVariable);
Iterator<PointsToSetVariable> converted = new MapIterator<INodeWithNumber, PointsToSetVariable>(it, PointsToSetVariable.class::cast);
return converted;
}

View File

@ -46,7 +46,6 @@ import com.ibm.wala.util.graph.NumberedGraph;
import com.ibm.wala.util.heapTrace.HeapTracer;
import com.ibm.wala.util.intset.IntIterator;
import com.ibm.wala.util.intset.IntSet;
import com.ibm.wala.util.intset.IntSetAction;
import com.ibm.wala.util.intset.IntSetUtil;
import com.ibm.wala.util.intset.MutableIntSet;
import com.ibm.wala.util.intset.MutableMapping;
@ -644,14 +643,11 @@ public class PropagationSystem extends DefaultFixedPointSolver<PointsToSetVariab
PointsToSetVariable rhs = (PointsToSetVariable) u.getRightHandSide();
IntSet value = rhs.getValue();
final int[] topFive = new int[5];
value.foreach(new IntSetAction() {
@Override
public void act(int x) {
for (int i = 0; i < 4; i++) {
topFive[i] = topFive[i + 1];
}
topFive[4] = x;
value.foreach(x -> {
for (int i = 0; i < 4; i++) {
topFive[i] = topFive[i + 1];
}
topFive[4] = x;
});
StringBuffer result = new StringBuffer();
for (int i = 0; i < 5; i++) {

View File

@ -70,14 +70,11 @@ public class ReflectionHandler {
System.err.println(" " + x);
}
}
Predicate<Statement> f = new Predicate<Statement>() {
@Override
public boolean test(Statement s) {
if (s.getKind() == Kind.NORMAL) {
return ((NormalStatement) s).getInstruction() instanceof SSACheckCastInstruction;
} else {
return false;
}
Predicate<Statement> f = s -> {
if (s.getKind() == Kind.NORMAL) {
return ((NormalStatement) s).getInstruction() instanceof SSACheckCastInstruction;
} else {
return false;
}
};
Collection<Statement> casts = Iterator2Collection.toSet(new FilterIterator<>(slice.iterator(), f));

View File

@ -550,12 +550,9 @@ public abstract class SSAPropagationCallGraphBuilder extends PropagationCallGrap
} else {
IntSet s = getParamObjects(pi, rhsi);
if (s != null && !s.isEmpty()) {
s.foreach(new IntSetAction() {
@Override
public void act(int x) {
keys[pi] = system.getInstanceKey(x);
rec(pi + 1, rhsi + 1);
}
s.foreach(x -> {
keys[pi] = system.getInstanceKey(x);
rec(pi + 1, rhsi + 1);
});
} /*else {
if (!site.isDispatch() || p != 0) {
@ -1174,12 +1171,9 @@ public abstract class SSAPropagationCallGraphBuilder extends PropagationCallGrap
}
final List<PointerKey> pks = new ArrayList<PointerKey>(params.size());
params.foreach(new IntSetAction() {
@Override
public void act(int x) {
if (!contentsAreInvariant(symbolTable, du, instruction.getUse(x))) {
pks.add(getBuilder().getPointerKeyForLocal(node, instruction.getUse(x)));
}
params.foreach(x -> {
if (!contentsAreInvariant(symbolTable, du, instruction.getUse(x))) {
pks.add(getBuilder().getPointerKeyForLocal(node, instruction.getUse(x)));
}
});
@ -1739,42 +1733,34 @@ public abstract class SSAPropagationCallGraphBuilder extends PropagationCallGrap
IntSet currentObjs = rhs[rhsIndex].getValue();
if (currentObjs != null) {
final IntSet oldObjs = previousPtrs[rhsIndex];
currentObjs.foreachExcluding(oldObjs, new IntSetAction() {
@Override
public void act(final int x) {
new CrossProductRec(constParams, call, node,
new Consumer<InstanceKey[]>() {
@Override
public void accept(InstanceKey[] v) {
IClass recv = null;
if (call.getCallSite().isDispatch()) {
recv = v[0].getConcreteType();
}
CGNode target = getTargetForCall(node, call.getCallSite(), recv, v);
if (target != null) {
changed.b = true;
processResolvedCall(node, call, target, constParams, uniqueCatch);
if (!haveAlreadyVisited(target)) {
markDiscovered(target);
}
}
}
}) {
{
rec(0, 0);
currentObjs.foreachExcluding(oldObjs, x -> new CrossProductRec(constParams, call, node,
v -> {
IClass recv = null;
if (call.getCallSite().isDispatch()) {
recv = v[0].getConcreteType();
}
@Override
protected IntSet getParamObjects(int paramVn, int rhsi) {
if (rhsi == y) {
return IntSetUtil.make(new int[]{ x });
} else {
return previousPtrs[rhsi];
CGNode target = getTargetForCall(node, call.getCallSite(), recv, v);
if (target != null) {
changed.b = true;
processResolvedCall(node, call, target, constParams, uniqueCatch);
if (!haveAlreadyVisited(target)) {
markDiscovered(target);
}
}
};
}
}) {
{
rec(0, 0);
}
@Override
protected IntSet getParamObjects(int paramVn, int rhsi) {
if (rhsi == y) {
return IntSetUtil.make(new int[]{ x });
} else {
return previousPtrs[rhsi];
}
}
});
previousPtrs[rhsIndex].addAll(currentObjs);
}
@ -2022,17 +2008,14 @@ public abstract class SSAPropagationCallGraphBuilder extends PropagationCallGrap
// associated with the instruction
final CallSiteReference site = instruction.getCallSite();
final Set<CGNode> targets = HashSetFactory.make();
Consumer<InstanceKey[]> f = new Consumer<InstanceKey[]>() {
@Override
public void accept(InstanceKey[] v) {
IClass recv = null;
if (site.isDispatch()) {
recv = v[0].getConcreteType();
}
CGNode target = getTargetForCall(caller, site, recv, v);
if (target != null) {
targets.add(target);
}
Consumer<InstanceKey[]> f = v -> {
IClass recv = null;
if (site.isDispatch()) {
recv = v[0].getConcreteType();
}
CGNode target = getTargetForCall(caller, site, recv, v);
if (target != null) {
targets.add(target);
}
};
iterateCrossProduct(caller, instruction, invs, f);

View File

@ -11,8 +11,6 @@
package com.ibm.wala.ipa.callgraph.propagation;
import java.util.Iterator;
import java.util.function.Function;
import java.util.function.Predicate;
import com.ibm.wala.classLoader.IClass;
import com.ibm.wala.classLoader.NewSiteReference;
@ -59,16 +57,7 @@ public class SmushedAllocationSiteInNode extends AbstractTypeInNode {
return new MapIterator<NewSiteReference,Pair<CGNode, NewSiteReference>>(
new FilterIterator<NewSiteReference>(
getNode().iterateNewSites(),
new Predicate<NewSiteReference>() {
@Override public boolean test(NewSiteReference o) {
return o.getDeclaredType().equals(getConcreteType().getReference());
}
}),
new Function<NewSiteReference,Pair<CGNode, NewSiteReference>>() {
@Override
public Pair<CGNode, NewSiteReference> apply(NewSiteReference object) {
return Pair.make(getNode(), object);
}
});
o -> o.getDeclaredType().equals(getConcreteType().getReference())),
object -> Pair.make(getNode(), object));
}
}

View File

@ -149,46 +149,43 @@ public class BasicRTABuilder extends AbstractRTABuilder {
if (DEBUG_LEVEL >= 2) {
System.err.println(("filtered value: " + value));
}
IntSetAction action = new IntSetAction() {
@Override
public void act(int ptr) {
IntSetAction action = ptr -> {
if (DEBUG) {
System.err.println((" dispatch to ptr " + ptr));
}
InstanceKey iKey = system.getInstanceKey(ptr);
CGNode target = getTargetForCall(caller, site, iKey.getConcreteType(), new InstanceKey[]{iKey});
if (target == null) {
// This indicates an error; I sure hope getTargetForCall
// raised a warning about this!
if (DEBUG) {
System.err.println((" dispatch to ptr " + ptr));
System.err.println(("Warning: null target for call " + site + " " + iKey));
}
InstanceKey iKey = system.getInstanceKey(ptr);
CGNode target = getTargetForCall(caller, site, iKey.getConcreteType(), new InstanceKey[]{iKey});
if (target == null) {
// This indicates an error; I sure hope getTargetForCall
// raised a warning about this!
if (DEBUG) {
System.err.println(("Warning: null target for call " + site + " " + iKey));
}
return;
}
if (clone2Assign) {
if (target.getMethod().getReference().equals(CloneInterpreter.CLONE)) {
// (mostly) ignore a call to clone: it won't affect the
// solution, but we should probably at least have a call
// edge
caller.addTarget(site, target);
return;
}
if (clone2Assign) {
if (target.getMethod().getReference().equals(CloneInterpreter.CLONE)) {
// (mostly) ignore a call to clone: it won't affect the
// solution, but we should probably at least have a call
// edge
caller.addTarget(site, target);
return;
}
}
}
IntSet targets = getCallGraph().getPossibleTargetNumbers(caller, site);
if (targets != null && targets.contains(target.getGraphNodeId())) {
// do nothing; we've previously discovered and handled this
// receiver for this call site.
return;
}
IntSet targets = getCallGraph().getPossibleTargetNumbers(caller, site);
if (targets != null && targets.contains(target.getGraphNodeId())) {
// do nothing; we've previously discovered and handled this
// receiver for this call site.
return;
}
// process the newly discovered target for this call
processResolvedCall(caller, site, target);
// process the newly discovered target for this call
processResolvedCall(caller, site, target);
if (!haveAlreadyVisited(target)) {
markDiscovered(target);
}
if (!haveAlreadyVisited(target)) {
markDiscovered(target);
}
};

View File

@ -14,7 +14,6 @@ import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.Map;
import java.util.function.Predicate;
import com.ibm.wala.analysis.typeInference.TypeAbstraction;
import com.ibm.wala.analysis.typeInference.TypeInference;
@ -176,12 +175,7 @@ public class TypeBasedHeapModel implements HeapModel {
@Override
public Iterator<PointerKey> iteratePointerKeys() {
initAllPKeys();
Iterator<Object> filtered = new FilterIterator<Object>(pKeys.values().iterator(), new Predicate<Object>() {
@Override
public boolean test(Object o) {
return o instanceof PointerKey;
}
});
Iterator<Object> filtered = new FilterIterator<Object>(pKeys.values().iterator(), o -> o instanceof PointerKey);
return new MapIterator<Object, PointerKey>(filtered, PointerKey.class::cast);
}

View File

@ -842,11 +842,7 @@ public abstract class AbstractInterproceduralCFG<T extends ISSABasicBlock> imple
// a successor node is a return site if it is in the same
// procedure, and is not the entry() node.
Predicate<BasicBlockInContext> isReturn = new Predicate<BasicBlockInContext>() {
@Override public boolean test(BasicBlockInContext other) {
return !other.isEntryBlock() && node.equals(other.getNode());
}
};
Predicate<BasicBlockInContext> isReturn = other -> !other.isEntryBlock() && node.equals(other.getNode());
return new FilterIterator<BasicBlockInContext<T>>(getSuccNodes(callBlock), isReturn);
}
@ -862,37 +858,28 @@ public abstract class AbstractInterproceduralCFG<T extends ISSABasicBlock> imple
Iterator<? extends T> it = cfg.getPredNodes(returnBlock.getDelegate());
final CGNode node = returnBlock.getNode();
Predicate<T> dispatchFilter = new Predicate<T>() {
@Override public boolean test(T callBlock) {
BasicBlockInContext<T> bb = new BasicBlockInContext<T>(node, callBlock);
if (!hasCall(bb, cfg)) {
return false;
}
if (callee != null) {
return getCallTargets(bb).contains(callee);
} else {
return getCallTargets(bb).isEmpty();
}
Predicate<T> dispatchFilter = callBlock -> {
BasicBlockInContext<T> bb = new BasicBlockInContext<T>(node, callBlock);
if (!hasCall(bb, cfg)) {
return false;
}
if (callee != null) {
return getCallTargets(bb).contains(callee);
} else {
return getCallTargets(bb).isEmpty();
}
};
it = new FilterIterator<T>(it, dispatchFilter);
Function<T, BasicBlockInContext<T>> toContext = new Function<T, BasicBlockInContext<T>>() {
@Override
public BasicBlockInContext<T> apply(T object) {
T b = object;
return new BasicBlockInContext<T>(node, b);
}
Function<T, BasicBlockInContext<T>> toContext = object -> {
T b = object;
return new BasicBlockInContext<T>(node, b);
};
MapIterator<T, BasicBlockInContext<T>> m = new MapIterator<T, BasicBlockInContext<T>>(it, toContext);
return new FilterIterator<BasicBlockInContext<T>>(m, isCall);
}
private final Predicate<BasicBlockInContext<T>> isCall = new Predicate<BasicBlockInContext<T>>() {
@Override public boolean test(BasicBlockInContext<T> o) {
return hasCall(o);
}
};
private final Predicate<BasicBlockInContext<T>> isCall = o -> hasCall(o);
public boolean isReturn(BasicBlockInContext<T> bb) throws IllegalArgumentException {
if (bb == null) {

View File

@ -17,7 +17,6 @@ import java.util.Iterator;
import java.util.List;
import java.util.NoSuchElementException;
import java.util.Set;
import java.util.function.Predicate;
import com.ibm.wala.cfg.ControlFlowGraph;
import com.ibm.wala.cfg.IBasicBlock;
@ -69,44 +68,24 @@ public class PrunedCFG<I, T extends IBasicBlock<I>> extends AbstractNumberedGrap
}
public Iterator<T> getExceptionalSuccessors(final T N) {
return new FilterIterator<T>(cfg.getExceptionalSuccessors(N).iterator(), new Predicate<T>() {
@Override public boolean test(T o) {
return currentCFGNodes.containsNode(o) && filter.hasExceptionalEdge(N, o);
}
});
return new FilterIterator<T>(cfg.getExceptionalSuccessors(N).iterator(), o -> currentCFGNodes.containsNode(o) && filter.hasExceptionalEdge(N, o));
}
public Iterator<T> getNormalSuccessors(final T N) {
return new FilterIterator<T>(cfg.getNormalSuccessors(N).iterator(), new Predicate<T>() {
@Override public boolean test(T o) {
return currentCFGNodes.containsNode(o) && filter.hasNormalEdge(N, o);
}
});
return new FilterIterator<T>(cfg.getNormalSuccessors(N).iterator(), o -> currentCFGNodes.containsNode(o) && filter.hasNormalEdge(N, o));
}
public Iterator<T> getExceptionalPredecessors(final T N) {
return new FilterIterator<T>(cfg.getExceptionalPredecessors(N).iterator(), new Predicate<T>() {
@Override public boolean test(T o) {
return currentCFGNodes.containsNode(o) && filter.hasExceptionalEdge(o, N);
}
});
return new FilterIterator<T>(cfg.getExceptionalPredecessors(N).iterator(), o -> currentCFGNodes.containsNode(o) && filter.hasExceptionalEdge(o, N));
}
public Iterator<T> getNormalPredecessors(final T N) {
return new FilterIterator<T>(cfg.getNormalPredecessors(N).iterator(), new Predicate<T>() {
@Override public boolean test(T o) {
return currentCFGNodes.containsNode(o) && filter.hasNormalEdge(o, N);
}
});
return new FilterIterator<T>(cfg.getNormalPredecessors(N).iterator(), o -> currentCFGNodes.containsNode(o) && filter.hasNormalEdge(o, N));
}
@Override
public Iterator<T> getSuccNodes(final T N) {
return new FilterIterator<T>(cfg.getSuccNodes(N), new Predicate<T>() {
@Override public boolean test(T o) {
return currentCFGNodes.containsNode(o) && (filter.hasNormalEdge(N, o) || filter.hasExceptionalEdge(N, o));
}
});
return new FilterIterator<T>(cfg.getSuccNodes(N), o -> currentCFGNodes.containsNode(o) && (filter.hasNormalEdge(N, o) || filter.hasExceptionalEdge(N, o)));
}
@Override
@ -126,11 +105,7 @@ public class PrunedCFG<I, T extends IBasicBlock<I>> extends AbstractNumberedGrap
@Override
public Iterator<T> getPredNodes(final T N) {
return new FilterIterator<T>(cfg.getPredNodes(N), new Predicate<T>() {
@Override public boolean test(T o) {
return currentCFGNodes.containsNode(o) && (filter.hasNormalEdge(o, N) || filter.hasExceptionalEdge(o, N));
}
});
return new FilterIterator<T>(cfg.getPredNodes(N), o -> currentCFGNodes.containsNode(o) && (filter.hasNormalEdge(o, N) || filter.hasExceptionalEdge(o, N)));
}
@Override
@ -226,11 +201,7 @@ public class PrunedCFG<I, T extends IBasicBlock<I>> extends AbstractNumberedGrap
}
private Iterator<T> filterNodes(Iterator<T> nodeIterator) {
return new FilterIterator<T>(nodeIterator, new Predicate<T>() {
@Override public boolean test(T o) {
return subset.contains(o);
}
});
return new FilterIterator<T>(nodeIterator, o -> subset.contains(o));
}
@Override

View File

@ -1085,12 +1085,7 @@ public class ClassHierarchy implements IClassHierarchy {
@Override
public Iterator<IClass> iterator() {
Function<Node, IClass> toClass = new Function<Node, IClass>() {
@Override
public IClass apply(Node n) {
return n.klass;
}
};
Function<Node, IClass> toClass = n -> n.klass;
return new MapIterator<Node, IClass>(map.values().iterator(), toClass);
}
@ -1147,12 +1142,7 @@ public class ClassHierarchy implements IClassHierarchy {
if (klass.isArrayClass()) {
return getImmediateArraySubclasses((ArrayClass)klass);
}
Function<Node, IClass> node2Class = new Function<Node, IClass>() {
@Override
public IClass apply(Node n) {
return n.klass;
}
};
Function<Node, IClass> node2Class = n -> n.klass;
return Iterator2Collection.toSet(new MapIterator<Node, IClass>(findNode(klass).children.iterator(), node2Class));
}

View File

@ -14,7 +14,6 @@ import java.util.Collection;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.function.Function;
import com.ibm.wala.classLoader.IClass;
import com.ibm.wala.classLoader.IField;
@ -103,13 +102,7 @@ public class ModRef<T extends InstanceKey> {
*/
private Map<CGNode, Collection<PointerKey>> scanForMod(CallGraph cg, final PointerAnalysis<T> pa, final HeapExclusions heapExclude) {
return CallGraphTransitiveClosure.collectNodeResults(cg, new Function<CGNode, Collection<PointerKey>>() {
@Override
public Collection<PointerKey> apply(CGNode n) {
return scanNodeForMod(n, pa, heapExclude);
}
});
return CallGraphTransitiveClosure.collectNodeResults(cg, n -> scanNodeForMod(n, pa, heapExclude));
}
/**
@ -119,13 +112,7 @@ public class ModRef<T extends InstanceKey> {
* @param heapExclude
*/
private Map<CGNode, Collection<PointerKey>> scanForRef(CallGraph cg, final PointerAnalysis<T> pa, final HeapExclusions heapExclude) {
return CallGraphTransitiveClosure.collectNodeResults(cg, new Function<CGNode, Collection<PointerKey>>() {
@Override
public Collection<PointerKey> apply(CGNode n) {
return scanNodeForRef(n, pa, heapExclude);
}
});
return CallGraphTransitiveClosure.collectNodeResults(cg, n -> scanNodeForRef(n, pa, heapExclude));
}
public ExtendedHeapModel makeHeapModel(PointerAnalysis<T> pa) {

View File

@ -644,27 +644,20 @@ public class HeapReachingDefs<T extends InstanceKey> {
return null;
} else {
// only static fields are actually killed
Predicate<PointerKey> staticFilter = new Predicate<PointerKey>() {
@Override public boolean test(PointerKey o) {
return o instanceof StaticFieldKey;
}
};
Predicate<PointerKey> staticFilter = o -> o instanceof StaticFieldKey;
final Collection<PointerKey> kill = Iterator2Collection
.toSet(new FilterIterator<PointerKey>(mod.iterator(), staticFilter));
if (kill.isEmpty()) {
return null;
} else {
Predicate<Statement> f = new Predicate<Statement>() {
// accept any statement which writes a killed location.
@Override public boolean test(Statement s) {
Collection m = getMod(s, node, heapModel, pa, exclusions);
for (PointerKey k : kill) {
if (m.contains(k)) {
return true;
}
Predicate<Statement> f = s1 -> {
Collection m = getMod(s1, node, heapModel, pa, exclusions);
for (PointerKey k : kill) {
if (m.contains(k)) {
return true;
}
return false;
}
return false;
};
BitVector result = new BitVector();
for (Statement k : Iterator2Iterable.make(new FilterIterator<Statement>(domain.iterator(), f))) {

View File

@ -674,14 +674,12 @@ public class PDG<T extends InstanceKey> implements NumberedGraph<Statement> {
// in reaching defs calculation, exclude heap statements that are
// irrelevant.
Predicate<Statement> f = new Predicate<Statement>() {
@Override public boolean test(Statement o) {
if (o instanceof HeapStatement) {
HeapStatement h = (HeapStatement) o;
return h.getLocation().equals(pk);
} else {
return true;
}
Predicate<Statement> f = o -> {
if (o instanceof HeapStatement) {
HeapStatement h = (HeapStatement) o;
return h.getLocation().equals(pk);
} else {
return true;
}
};
Collection<Statement> relevantStatements = Iterator2Collection.toSet(new FilterIterator<Statement>(iterator(), f));
@ -766,15 +764,13 @@ public class PDG<T extends InstanceKey> implements NumberedGraph<Statement> {
* @return Statements representing each return instruction in the ir
*/
private Collection<NormalStatement> computeReturnStatements(final IR ir) {
Predicate<Statement> filter = new Predicate<Statement>() {
@Override public boolean test(Statement o) {
if (o instanceof NormalStatement) {
NormalStatement s = (NormalStatement) o;
SSAInstruction st = ir.getInstructions()[s.getInstructionIndex()];
return st instanceof SSAReturnInstruction;
} else {
return false;
}
Predicate<Statement> filter = o -> {
if (o instanceof NormalStatement) {
NormalStatement s = (NormalStatement) o;
SSAInstruction st = ir.getInstructions()[s.getInstructionIndex()];
return st instanceof SSAReturnInstruction;
} else {
return false;
}
};
return Iterator2Collection.toSet(

View File

@ -97,11 +97,7 @@ class SDGSupergraph implements ISupergraph<Statement, PDG<? extends InstanceKey>
public Iterator<? extends Statement> getCalledNodes(Statement call) {
switch (call.getKind()) {
case NORMAL:
Predicate<Statement> f = new Predicate<Statement>() {
@Override public boolean test(Statement s) {
return isEntry(s);
}
};
Predicate<Statement> f = s -> isEntry(s);
return new FilterIterator<Statement>(getSuccNodes(call), f);
case PARAM_CALLER:
case HEAP_PARAM_CALLER:

View File

@ -1034,12 +1034,7 @@ public class SSACFG implements ControlFlowGraph<SSAInstruction, ISSABasicBlock>,
throw new IllegalArgumentException("b is null");
}
IBasicBlock<IInstruction> n = delegate.getNode(b.getNumber());
Function<IBasicBlock<IInstruction>, ISSABasicBlock> f = new Function<IBasicBlock<IInstruction>, ISSABasicBlock>() {
@Override
public ISSABasicBlock apply(IBasicBlock<IInstruction> object) {
return basicBlocks[delegate.getNumber(object)];
}
};
Function<IBasicBlock<IInstruction>, ISSABasicBlock> f = object -> basicBlocks[delegate.getNumber(object)];
return Iterator2Collection.toSet(new MapIterator<IBasicBlock<IInstruction>, ISSABasicBlock>(delegate
.getExceptionalPredecessors(n).iterator(), f));
}

View File

@ -18,7 +18,6 @@ import java.lang.management.MemoryType;
import javax.management.InstanceNotFoundException;
import javax.management.ListenerNotFoundException;
import javax.management.Notification;
import javax.management.NotificationListener;
import javax.management.openmbean.CompositeData;
@ -169,18 +168,15 @@ public class ProgressMaster implements IProgressMonitor {
final Thread nannyThread = this;
gcbean = ManagementFactory.getMemoryMXBean();
listener = new NotificationListener() {
@Override
public void handleNotification(Notification notification, Object arg1) {
MemoryNotificationInfo info = MemoryNotificationInfo.from((CompositeData) notification.getUserData());
long used = info.getUsage().getUsed();
long max = Runtime.getRuntime().maxMemory();
listener = (notification, arg1) -> {
MemoryNotificationInfo info = MemoryNotificationInfo.from((CompositeData) notification.getUserData());
long used = info.getUsage().getUsed();
long max = Runtime.getRuntime().maxMemory();
if (((double)used/(double)max) > MAX_USED_MEM_BEFORE_BACKING_OUT) {
System.err.println("used " + used + " of " + max);
tooMuchMemory = true;
nannyThread.interrupt();
}
if (((double)used/(double)max) > MAX_USED_MEM_BEFORE_BACKING_OUT) {
System.err.println("used " + used + " of " + max);
tooMuchMemory = true;
nannyThread.interrupt();
}
};
try {

View File

@ -67,12 +67,7 @@ public class JUnitEntryPoints {
}
}
}
return new Iterable<Entrypoint>() {
@Override
public Iterator<Entrypoint> iterator() {
return result.iterator();
}
};
return () -> result.iterator();
}
/**
@ -120,12 +115,7 @@ public class JUnitEntryPoints {
}
}
}
return new Iterable<Entrypoint>() {
@Override
public Iterator<Entrypoint> iterator() {
return entryPts.iterator();
}
};
return () -> entryPts.iterator();
}
/**

View File

@ -79,12 +79,7 @@ public class PDFViewUtil {
SSACFG.BasicBlock bb = (SSACFG.BasicBlock) it.next();
labelMap.put(bb, getNodeLabel(ir, bb));
}
NodeDecorator<ISSABasicBlock> labels = new NodeDecorator<ISSABasicBlock>() {
@Override
public String getLabel(ISSABasicBlock bb) {
return labelMap.get(bb);
}
};
NodeDecorator<ISSABasicBlock> labels = bb -> labelMap.get(bb);
return labels;
}

View File

@ -20,8 +20,6 @@ import javax.swing.JSplitPane;
import javax.swing.JTree;
import javax.swing.event.TreeExpansionEvent;
import javax.swing.event.TreeExpansionListener;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.TreePath;
@ -45,24 +43,21 @@ public class CgPanel extends JSplitPane{
final IrAndSourceViewer irViewer = new IrAndSourceViewer();
this.setRightComponent(irViewer.getComponent());
tree.addTreeSelectionListener(new TreeSelectionListener() {
@Override
public void valueChanged(TreeSelectionEvent e) {
TreePath newLeadSelectionPath = e.getNewLeadSelectionPath();
if (null == newLeadSelectionPath){
return;
}
DefaultMutableTreeNode treeNode = (DefaultMutableTreeNode) newLeadSelectionPath.getLastPathComponent();
Object userObject = treeNode.getUserObject();
if (userObject instanceof CGNode) {
CGNode node = (CGNode) userObject;
IR ir = node.getIR();
irViewer.setIR(ir);
} else if (userObject instanceof CallSiteReference){
CGNode parentNode = (CGNode) ((DefaultMutableTreeNode) treeNode.getParent()).getUserObject();
IR ir = parentNode.getIR();
irViewer.setIRAndPc(ir, ((CallSiteReference) userObject).getProgramCounter());
}
tree.addTreeSelectionListener(e -> {
TreePath newLeadSelectionPath = e.getNewLeadSelectionPath();
if (null == newLeadSelectionPath){
return;
}
DefaultMutableTreeNode treeNode = (DefaultMutableTreeNode) newLeadSelectionPath.getLastPathComponent();
Object userObject = treeNode.getUserObject();
if (userObject instanceof CGNode) {
CGNode node = (CGNode) userObject;
IR ir1 = node.getIR();
irViewer.setIR(ir1);
} else if (userObject instanceof CallSiteReference){
CGNode parentNode = (CGNode) ((DefaultMutableTreeNode) treeNode.getParent()).getUserObject();
IR ir2 = parentNode.getIR();
irViewer.setIRAndPc(ir2, ((CallSiteReference) userObject).getProgramCounter());
}
});

View File

@ -19,8 +19,6 @@ import javax.swing.JSplitPane;
import javax.swing.JTree;
import javax.swing.event.TreeExpansionEvent;
import javax.swing.event.TreeExpansionListener;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.TreePath;
@ -44,19 +42,16 @@ public class ChaPanel extends JSplitPane {
JList methodList = new JList<String>(methodListModel);
this.setRightComponent(methodList);
tree.addTreeSelectionListener(new TreeSelectionListener(){
@Override
public void valueChanged(TreeSelectionEvent e) {
TreePath newLeadSelectionPath = e.getNewLeadSelectionPath();
if (null == newLeadSelectionPath){
return;
}
DefaultMutableTreeNode treeNode = (DefaultMutableTreeNode) newLeadSelectionPath.getLastPathComponent();
IClass klass = (IClass) treeNode.getUserObject();
methodListModel.clear();
for (IMethod m : klass.getDeclaredMethods()){
methodListModel.addElement(m.toString());
}
tree.addTreeSelectionListener(e -> {
TreePath newLeadSelectionPath = e.getNewLeadSelectionPath();
if (null == newLeadSelectionPath){
return;
}
DefaultMutableTreeNode treeNode = (DefaultMutableTreeNode) newLeadSelectionPath.getLastPathComponent();
IClass klass = (IClass) treeNode.getUserObject();
methodListModel.clear();
for (IMethod m : klass.getDeclaredMethods()){
methodListModel.addElement(m.toString());
}
});

View File

@ -20,7 +20,6 @@ import javax.swing.JSplitPane;
import com.ibm.wala.classLoader.IClassLoader;
import com.ibm.wala.classLoader.IMethod;
import com.ibm.wala.ssa.IR;
import com.ibm.wala.viz.viewer.IrViewer.SelectedPcListner;
public class IrAndSourceViewer {
@ -39,35 +38,30 @@ public class IrAndSourceViewer {
sourceViewer = new SourceViewer();
splitPane.setRightComponent(sourceViewer);
irViewer.addSelectedPcListner(new SelectedPcListner(){
@Override
public void valueChanged(int pc) {
IMethod method = ir.getMethod();
int sourceLineNumber = IrViewer.NA;
String sourceFileName = null;
if (pc != IrViewer.NA){
try{
sourceLineNumber = method.getLineNumber(pc);
IClassLoader loader = method.getDeclaringClass().getClassLoader();
sourceFileName = loader.getSourceFileName(method, pc);
} catch (Exception e){
e.printStackTrace();
}
}
if (sourceFileName != null){
URL url;
try {
url = (new File(sourceFileName)).toURI().toURL();
sourceViewer.setSource(url, sourceLineNumber);
} catch (MalformedURLException e) {
e.printStackTrace();
}
} else {
sourceViewer.removeSource();
irViewer.addSelectedPcListner(pc -> {
IMethod method = ir.getMethod();
int sourceLineNumber = IrViewer.NA;
String sourceFileName = null;
if (pc != IrViewer.NA){
try{
sourceLineNumber = method.getLineNumber(pc);
IClassLoader loader = method.getDeclaringClass().getClassLoader();
sourceFileName = loader.getSourceFileName(method, pc);
} catch (Exception e1){
e1.printStackTrace();
}
}
if (sourceFileName != null){
URL url;
try {
url = (new File(sourceFileName)).toURI().toURL();
sourceViewer.setSource(url, sourceLineNumber);
} catch (MalformedURLException e2) {
e2.printStackTrace();
}
} else {
sourceViewer.removeSource();
}
});
return splitPane;

View File

@ -24,8 +24,6 @@ import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.ScrollPaneConstants;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import com.ibm.wala.classLoader.IMethod;
import com.ibm.wala.ssa.IR;
@ -58,17 +56,14 @@ public class IrViewer extends JPanel{
ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED), BorderLayout.CENTER);
irLines.addListSelectionListener(new ListSelectionListener() {
@Override
public void valueChanged(ListSelectionEvent e) {
int index = irLines.getSelectedIndex();
Integer pc = lineToPc.get(index);
if (pc == null) {
pc = NA;
}
for (SelectedPcListner selectedPcListner : selectedPcListners) {
selectedPcListner.valueChanged(pc);
}
irLines.addListSelectionListener(e -> {
int index = irLines.getSelectedIndex();
Integer pc = lineToPc.get(index);
if (pc == null) {
pc = NA;
}
for (SelectedPcListner selectedPcListner : selectedPcListners) {
selectedPcListner.valueChanged(pc);
}
});
}

View File

@ -22,8 +22,6 @@ import javax.swing.JTextField;
import javax.swing.JTree;
import javax.swing.event.TreeExpansionEvent;
import javax.swing.event.TreeExpansionListener;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.TreeNode;
import javax.swing.tree.TreePath;
@ -118,51 +116,47 @@ public class PaPanel extends JSplitPane {
}
});
heapTree.addTreeSelectionListener(new TreeSelectionListener() {
@Override
public void valueChanged(TreeSelectionEvent e) {
TreePath newLeadSelectionPath = e.getNewLeadSelectionPath();
if (null == newLeadSelectionPath){
return;
}
DefaultMutableTreeNode treeNode = (DefaultMutableTreeNode) newLeadSelectionPath.getLastPathComponent();
Object userObject = treeNode.getUserObject();
fullName.setText(userObject.toString());
if (userObject instanceof LocalPointerKey){
LocalPointerKey lpk = (LocalPointerKey) userObject;
IR ir = lpk.getNode().getIR();
SSAInstruction def = lpk.getNode().getDU().getDef(lpk.getValueNumber());
int pc = IrViewer.NA;
if (def != null){
SSAInstruction[] instructions = ir.getInstructions();
for (int i = 0; i < instructions.length; i++) {
SSAInstruction instruction = instructions[i];
if (def == instruction){
pc = i;
}
heapTree.addTreeSelectionListener(e -> {
TreePath newLeadSelectionPath = e.getNewLeadSelectionPath();
if (null == newLeadSelectionPath){
return;
}
DefaultMutableTreeNode treeNode = (DefaultMutableTreeNode) newLeadSelectionPath.getLastPathComponent();
Object userObject = treeNode.getUserObject();
fullName.setText(userObject.toString());
if (userObject instanceof LocalPointerKey){
LocalPointerKey lpk = (LocalPointerKey) userObject;
IR ir1 = lpk.getNode().getIR();
SSAInstruction def = lpk.getNode().getDU().getDef(lpk.getValueNumber());
int pc1 = IrViewer.NA;
if (def != null){
SSAInstruction[] instructions = ir1.getInstructions();
for (int i = 0; i < instructions.length; i++) {
SSAInstruction instruction = instructions[i];
if (def == instruction){
pc1 = i;
}
}
irViewer.setIRAndPc(ir, pc);
} else if (userObject instanceof InstanceFieldPointerKey){
InstanceKey ik = ((InstanceFieldPointerKey) userObject).getInstanceKey();
if (ik instanceof NormalAllocationInNode){
NormalAllocationInNode normalIk = (NormalAllocationInNode) ik;
IR ir = normalIk.getNode().getIR();
int pc = normalIk.getSite().getProgramCounter();
irViewer.setIRAndPc(ir, pc);
}
} else if (userObject instanceof NormalAllocationInNode){
NormalAllocationInNode normalIk = (NormalAllocationInNode) userObject;
IR ir = normalIk.getNode().getIR();
int pc = normalIk.getSite().getProgramCounter();
irViewer.setIRAndPc(ir, pc);
} else if (userObject instanceof CGNode){
irViewer.setIR(((CGNode)userObject).getIR());
}
irViewer.setIRAndPc(ir1, pc1);
} else if (userObject instanceof InstanceFieldPointerKey){
InstanceKey ik = ((InstanceFieldPointerKey) userObject).getInstanceKey();
if (ik instanceof NormalAllocationInNode){
NormalAllocationInNode normalIk1 = (NormalAllocationInNode) ik;
IR ir2 = normalIk1.getNode().getIR();
int pc2 = normalIk1.getSite().getProgramCounter();
irViewer.setIRAndPc(ir2, pc2);
}
} else if (userObject instanceof NormalAllocationInNode){
NormalAllocationInNode normalIk2 = (NormalAllocationInNode) userObject;
IR ir3 = normalIk2.getNode().getIR();
int pc3 = normalIk2.getSite().getProgramCounter();
irViewer.setIRAndPc(ir3, pc3);
} else if (userObject instanceof CGNode){
irViewer.setIR(((CGNode)userObject).getIR());
}
});
}

View File

@ -4,8 +4,6 @@ import java.io.File;
import java.net.URI;
import java.util.Collections;
import java.util.Set;
import java.util.function.Predicate;
import java.util.function.Consumer;
import com.ibm.wala.classLoader.IClass;
import com.ibm.wala.classLoader.IMethod;
@ -55,102 +53,93 @@ public class APKCallGraphDriver {
} catch (Throwable e) {
// no timeout specified
}
FileUtil.recurseFiles(new Consumer<File>() {
FileUtil.recurseFiles(apk1 -> {
System.gc();
System.err.println("Analyzing " + apk1 + "...");
try {
long time = System.currentTimeMillis();
Pair<CallGraph, PointerAnalysis<InstanceKey>> CG;
final long startTime = System.currentTimeMillis();
IProgressMonitor pm = new IProgressMonitor() {
private boolean cancelled = false;
@Override
public void accept(File apk) {
System.gc();
System.err.println("Analyzing " + apk + "...");
try {
long time = System.currentTimeMillis();
Pair<CallGraph, PointerAnalysis<InstanceKey>> CG;
final long startTime = System.currentTimeMillis();
IProgressMonitor pm = new IProgressMonitor() {
private boolean cancelled = false;
@Override
public void beginTask(String task, int totalWork) {
// TODO Auto-generated method stub
}
@Override
public void beginTask(String task, int totalWork) {
// TODO Auto-generated method stub
}
@Override
public void subTask(String subTask) {
// TODO Auto-generated method stub
}
@Override
public void subTask(String subTask) {
// TODO Auto-generated method stub
}
@Override
public void cancel() {
cancelled = true;
}
@Override
public void cancel() {
cancelled = true;
}
@Override
public boolean isCanceled() {
if (System.currentTimeMillis() - startTime > timeout) {
cancelled = true;
}
return cancelled;
}
@Override
public boolean isCanceled() {
if (System.currentTimeMillis() - startTime > timeout) {
cancelled = true;
}
return cancelled;
}
@Override
public void done() {
// TODO Auto-generated method stub
}
@Override
public void done() {
// TODO Auto-generated method stub
}
@Override
public void worked(int units) {
// TODO Auto-generated method stub
}
@Override
public void worked(int units) {
// TODO Auto-generated method stub
}
@Override
public String getCancelMessage() {
return "timeout";
}
};
CG = DalvikCallGraphTestBase.makeAPKCallGraph(libs(), null, apk1.getAbsolutePath(), pm, ReflectionOptions.NONE);
System.err.println("Analyzed " + apk1 + " in " + (System.currentTimeMillis() - time));
@Override
public String getCancelMessage() {
return "timeout";
}
};
CG = DalvikCallGraphTestBase.makeAPKCallGraph(libs(), null, apk.getAbsolutePath(), pm, ReflectionOptions.NONE);
System.err.println("Analyzed " + apk + " in " + (System.currentTimeMillis() - time));
System.err.println(new SDG<>(CG.fst, CG.snd, DataDependenceOptions.NO_BASE_NO_HEAP_NO_EXCEPTIONS, ControlDependenceOptions.NONE));
if (dumpIR) {
for(CGNode n1 : CG.fst) {
System.err.println(n1.getIR());
System.err.println();
}
} else {
Set<IMethod> code = HashSetFactory.make();
for(CGNode n2 : CG.fst) {
code.add(n2.getMethod());
}
System.err.println(new SDG<>(CG.fst, CG.snd, DataDependenceOptions.NO_BASE_NO_HEAP_NO_EXCEPTIONS, ControlDependenceOptions.NONE));
if (dumpIR) {
for(CGNode n : CG.fst) {
System.err.println(n.getIR());
System.err.println();
}
} else {
Set<IMethod> code = HashSetFactory.make();
for(CGNode n : CG.fst) {
code.add(n.getMethod());
}
if (addAbstract) {
for(IClass cls : CG.fst.getClassHierarchy()) {
for(IMethod m1 : cls.getDeclaredMethods()) {
if (m1.isAbstract() && !Collections.disjoint(CG.fst.getClassHierarchy().getPossibleTargets(m1.getReference()), code)) {
code.add(m1);
}
}
}
}
if (addAbstract) {
for(IClass cls : CG.fst.getClassHierarchy()) {
for(IMethod m : cls.getDeclaredMethods()) {
if (m.isAbstract() && !Collections.disjoint(CG.fst.getClassHierarchy().getPossibleTargets(m.getReference()), code)) {
code.add(m);
}
}
}
}
System.err.println("reachable methods for " + apk1);
for(IMethod m2 : code) {
System.err.println("" + m2.getDeclaringClass().getName() + " " + m2.getName() + m2.getDescriptor());
System.err.println("reachable methods for " + apk);
for(IMethod m : code) {
System.err.println("" + m.getDeclaringClass().getName() + " " + m.getName() + m.getDescriptor());
}
System.err.println("end of methods");
}
}
System.err.println("end of methods");
}
} catch (Throwable e) {
e.printStackTrace(System.err);
}
}
},
new Predicate<File>() {
@Override
public boolean test(File file) {
return file.getName().endsWith("apk");
}
},
} catch (Throwable e) {
e.printStackTrace(System.err);
}
},
file -> file.getName().endsWith("apk"),
apk);
}
}

View File

@ -75,18 +75,8 @@ public class DalvikCallGraphTestBase extends DynamicCallGraphTestBase {
protected static Set<MethodReference> applicationMethods(CallGraph cg) {
return processCG(cg,
new Predicate<CGNode>() {
@Override
public boolean test(CGNode t) {
return t.getMethod().getReference().getDeclaringClass().getClassLoader().equals(ClassLoaderReference.Application);
}
},
new Function<CGNode,MethodReference>() {
@Override
public MethodReference apply(CGNode object) {
return object.getMethod().getReference();
}
});
t -> t.getMethod().getReference().getDeclaringClass().getClassLoader().equals(ClassLoaderReference.Application),
object -> object.getMethod().getReference());
}
@ -110,18 +100,8 @@ public class DalvikCallGraphTestBase extends DynamicCallGraphTestBase {
new MapIterator<SSAInstruction,NewSiteReference>(
new FilterIterator<SSAInstruction>(
node.getIR().iterateAllInstructions(),
new Predicate<SSAInstruction>() {
@Override
public boolean test(SSAInstruction t) {
return t instanceof SSANewInstruction;
}
}),
new Function<SSAInstruction,NewSiteReference>() {
@Override
public NewSiteReference apply(SSAInstruction object) {
return ((SSANewInstruction)object).getNewSite();
}
}
t -> t instanceof SSANewInstruction),
object -> ((SSANewInstruction)object).getNewSite()
);
}
};

View File

@ -21,8 +21,6 @@ import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Consumer;
import java.util.function.Predicate;
import org.junit.Assert;
import org.junit.Test;
@ -161,20 +159,13 @@ public abstract class DroidBenchCGTest extends DalvikCallGraphTestBase {
public static Collection<Object[]> generateData(String droidBenchRoot, final URI[] androidLibs, final File androidJavaJar, final String filter) {
final List<Object[]> files = new LinkedList<>();
FileUtil.recurseFiles(new Consumer<File>() {
@Override
public void accept(File f) {
Set<MethodReference> uncalled = uncalledFunctions.get(f.getName());
if (uncalled == null) {
uncalled = Collections.emptySet();
}
files.add(new Object[]{ androidLibs, androidJavaJar, f.getAbsolutePath(), uncalled });
}
}, new Predicate<File>() {
@Override
public boolean test(File t) {
return (filter == null || t.getAbsolutePath().contains(filter)) && t.getName().endsWith("apk") && ! skipTests.contains(t.getName().toString());
} }, new File(droidBenchRoot + "/apk/"));
FileUtil.recurseFiles(f -> {
Set<MethodReference> uncalled = uncalledFunctions.get(f.getName());
if (uncalled == null) {
uncalled = Collections.emptySet();
}
files.add(new Object[]{ androidLibs, androidJavaJar, f.getAbsolutePath(), uncalled });
}, t -> (filter == null || t.getAbsolutePath().contains(filter)) && t.getName().endsWith("apk") && ! skipTests.contains(t.getName().toString()), new File(droidBenchRoot + "/apk/"));
return files;
}
}

View File

@ -16,7 +16,6 @@ import static com.ibm.wala.dalvik.test.util.Util.getJavaJar;
import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.util.function.Predicate;
import com.ibm.wala.core.tests.callGraph.CallGraphTestUtil;
import com.ibm.wala.ipa.callgraph.AnalysisScope;
@ -27,7 +26,6 @@ import com.ibm.wala.ipa.cha.ClassHierarchyException;
import com.ibm.wala.shrikeBT.analysis.Analyzer.FailureException;
import com.ibm.wala.shrikeCT.InvalidClassFileException;
import com.ibm.wala.types.ClassLoaderReference;
import com.ibm.wala.types.MethodReference;
import com.ibm.wala.util.CancelException;
import com.ibm.wala.util.collections.Pair;
import com.ibm.wala.util.io.TemporaryFile;
@ -42,12 +40,7 @@ public abstract class DynamicDalvikComparisonTest extends DalvikCallGraphTestBas
dynamicCG(new File(javaJarPath), mainClass, args);
checkEdges(android.fst, new Predicate<MethodReference>() {
@Override
public boolean test(MethodReference t) {
return t.getDeclaringClass().getClassLoader().equals(ClassLoaderReference.Application);
}
});
checkEdges(android.fst, t -> t.getDeclaringClass().getClassLoader().equals(ClassLoaderReference.Application));
}
protected File testFile(String file) throws IOException {

View File

@ -81,24 +81,16 @@ public class Util {
libs.add(new File(System.getenv("ANDROID_BOOT_OAT")).toURI());
} else if (walaProperties != null && walaProperties.getProperty(ANDROID_RT_DEX_DIR) != null) {
for(File lib : new File(walaProperties.getProperty(ANDROID_RT_DEX_DIR)).listFiles(new FilenameFilter() {
@Override
public boolean accept(File dir, String name) {
return name.startsWith("boot") && name.endsWith("oat");
}
})) {
for(File lib : new File(walaProperties.getProperty(ANDROID_RT_DEX_DIR)).listFiles((FilenameFilter) (dir, name) -> name.startsWith("boot") && name.endsWith("oat"))) {
libs.add(lib.toURI());
}
} else {
assert "Dalvik".equals(System.getProperty("java.vm.name"));
for(File f : new File("/system/framework/").listFiles(new FileFilter() {
@Override
public boolean accept(File pathname) {
String name = pathname.getName();
return
(name.startsWith("core") || name.startsWith("framework")) &&
(name.endsWith("jar") || name.endsWith("apk"));
}
for(File f : new File("/system/framework/").listFiles((FileFilter) pathname -> {
String name = pathname.getName();
return
(name.startsWith("core") || name.startsWith("framework")) &&
(name.endsWith("jar") || name.endsWith("apk"));
}))
{
System.out.println("adding " + f);

View File

@ -188,14 +188,12 @@ public class AndroidManifestXMLReader {
Collections.EMPTY_SET,
IntentItem.class),
ACTION("action",
new ISubTags() { @Override public Set<Tag> getSubTags() {
return Collections.EMPTY_SET; }},
() -> Collections.emptySet(),
EnumSet.of(Attr.NAME),
FinalItem.class), //(new ITagDweller() {
//public Tag getTag() { return Tag.ACTION; }})),
DATA("data",
new ISubTags() { @Override public Set<Tag> getSubTags() {
return Collections.EMPTY_SET; }},
() -> Collections.emptySet(),
EnumSet.of(Attr.SCHEME, Attr.HOST, Attr.PATH, Attr.MIME),
FinalItem.class), //(new ITagDweller() {
//public Tag getTag() { return Tag.DATA; }})),

View File

@ -258,19 +258,14 @@ public class DemandCastChecker {
System.err.println("CHECKING " + castInstr + " in " + node.getMethod());
PointerKey castedPk = heapModel.getPointerKeyForLocal(node, castInstr.getUse(0));
Predicate<InstanceKey> castPred = new Predicate<InstanceKey>() {
@Override
public boolean test(InstanceKey ik) {
TypeReference ikTypeRef = ik.getConcreteType().getReference();
for (TypeReference t : declaredResultTypes) {
if (cha.isAssignableFrom(cha.lookupClass(t), cha.lookupClass(ikTypeRef))) {
return true;
}
Predicate<InstanceKey> castPred = ik -> {
TypeReference ikTypeRef = ik.getConcreteType().getReference();
for (TypeReference t : declaredResultTypes) {
if (cha.isAssignableFrom(cha.lookupClass(t), cha.lookupClass(ikTypeRef))) {
return true;
}
return false;
}
return false;
};
long startTime = System.currentTimeMillis();
Pair<PointsToResult, Collection<InstanceKey>> queryResult = dmp.getPointsTo(castedPk, castPred);

View File

@ -148,14 +148,11 @@ public class EclipseJavaScriptAnalysisEngine<I extends InstanceKey> extends Ecli
scripts.add(scriptName);
}
final Function<IMethod, Boolean> filter = new Function<IMethod, Boolean>() {
@Override
public Boolean apply(IMethod object) {
if (object instanceof AstMethod) {
return scripts.contains(getScriptName((AstMethod)object));
} else {
return true;
}
final Function<IMethod, Boolean> filter = object -> {
if (object instanceof AstMethod) {
return scripts.contains(getScriptName((AstMethod)object));
} else {
return true;
}
};

View File

@ -10,9 +10,6 @@
*******************************************************************************/
package com.ibm.wala.ide.util;
import java.util.function.Function;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.wst.jsdt.core.IJavaScriptProject;
import org.eclipse.wst.jsdt.core.JavaScriptCore;
@ -20,22 +17,19 @@ import org.eclipse.wst.jsdt.core.JavaScriptCore;
public class JavaScriptHeadlessUtil extends HeadlessUtil {
public static IJavaScriptProject getJavaScriptProjectFromWorkspace(final String projectName) {
IJavaScriptProject jp = getProjectFromWorkspace(new Function<IProject, IJavaScriptProject>() {
@Override
public IJavaScriptProject apply(IProject p) {
try {
if (p.hasNature(JavaScriptCore.NATURE_ID)) {
IJavaScriptProject jp = JavaScriptCore.create(p);
if (jp != null && jp.getElementName().equals(projectName)) {
return jp;
}
}
} catch (CoreException e) {
}
// failed to match
return null;
}
});
IJavaScriptProject jp = getProjectFromWorkspace(p -> {
try {
if (p.hasNature(JavaScriptCore.NATURE_ID)) {
IJavaScriptProject jp1 = JavaScriptCore.create(p);
if (jp1 != null && jp1.getElementName().equals(projectName)) {
return jp1;
}
}
} catch (CoreException e) {
}
// failed to match
return null;
});
return jp;
}

View File

@ -106,11 +106,7 @@ public class SWTTypeHierarchy {
* Restrict g to nodes from the Application loader
*/
static Graph<IClass> pruneForAppLoader(Graph<IClass> g) {
Predicate<IClass> f = new Predicate<IClass>() {
@Override public boolean test(IClass c) {
return (c.getClassLoader().getReference().equals(ClassLoaderReference.Application));
}
};
Predicate<IClass> f = c -> (c.getClassLoader().getReference().equals(ClassLoaderReference.Application));
return pruneGraph(g, f);
}

View File

@ -105,12 +105,7 @@ public class EclipseTestUtil {
protected static <T> void importProject(IImportStructureProvider provider, IProgressMonitor monitor, String projectName, T root) {
IPath containerPath = getWorkspacePath().append(projectName).addTrailingSeparator();
ImportOperation importOp = new ImportOperation(containerPath, root, provider, new IOverwriteQuery() {
@Override
public String queryOverwrite(String pathString) {
return IOverwriteQuery.ALL;
}
});
ImportOperation importOp = new ImportOperation(containerPath, root, provider, pathString -> IOverwriteQuery.ALL);
importOp.setCreateContainerStructure(false);
importOp.setOverwriteResources(true);

View File

@ -19,7 +19,6 @@ import com.ibm.wala.ipa.callgraph.Entrypoint;
import com.ibm.wala.ipa.callgraph.IAnalysisCacheView;
import com.ibm.wala.ipa.callgraph.propagation.InstanceKey;
import com.ibm.wala.ssa.SSAOptions;
import com.ibm.wala.ssa.SymbolTable;
import com.ibm.wala.types.ClassLoaderReference;
import com.ibm.wala.util.debug.Assertions;
import com.ibm.wala.util.io.FileProvider;
@ -70,12 +69,7 @@ abstract public class EclipseProjectSourceAnalysisEngine<P, I extends InstanceKe
AnalysisOptions options = new AnalysisOptions(getScope(), entrypoints);
SSAOptions ssaOptions = new SSAOptions();
ssaOptions.setDefaultValues(new SSAOptions.DefaultValues() {
@Override
public int getDefaultValue(SymbolTable symtab, int valueNumber) {
return symtab.getDefaultValue(valueNumber);
}
});
ssaOptions.setDefaultValues((symtab, valueNumber) -> symtab.getDefaultValue(valueNumber));
options.setSSAOptions(ssaOptions);

View File

@ -108,14 +108,11 @@ public class SWTTreeViewer extends AbstractJFaceRunner {
if (PlatformUI.isWorkbenchRunning()) {
// run the code on the UI thread
Display d = PlatformUI.getWorkbench().getDisplay();
Runnable r = new Runnable() {
@Override
public void run() {
try {
w.open();
} catch (Exception e) {
e.printStackTrace();
}
Runnable r = () -> {
try {
w.open();
} catch (Exception e) {
e.printStackTrace();
}
};
if (isBlockInput()) {
@ -130,12 +127,9 @@ public class SWTTreeViewer extends AbstractJFaceRunner {
w.open();
Display.getCurrent().dispose();
} else {
Runnable r = new Runnable() {
@Override
public void run() {
w.open();
Display.getCurrent().dispose();
}
Runnable r = () -> {
w.open();
Display.getCurrent().dispose();
};
Thread t = new Thread(r);
t.start();

View File

@ -176,11 +176,7 @@ public class ViewIFDSLocalAction<T, P, F> extends Action {
try {
final P proc = getProcedureForSelection();
Predicate<T> filter = new Predicate<T>() {
@Override public boolean test(T o) {
return supergraph.getProcOf(o).equals(proc);
}
};
Predicate<T> filter = o -> supergraph.getProcOf(o).equals(proc);
Graph<T> localGraph = GraphSlicer.prune(supergraph, filter);
// spawn the viewer

View File

@ -103,24 +103,21 @@ public class HeadlessUtil {
for (final Map.Entry<IProject,Map<Unit,EclipseSourceFileModule>> proj : projectsFiles.entrySet()) {
parser.setProject(proj.getKey());
parser.processASTs(proj.getValue(), new Function<Object[],Boolean>() {
@Override
public Boolean apply(Object[] problems) {
int length = problems.length;
if (length > 0) {
StringBuffer buffer = new StringBuffer();
for (int i = 0; i < length; i++) {
buffer.append(problems[i].toString());
buffer.append('\n');
}
if (length != 0) {
System.err.println(buffer.toString());
return true;
}
parser.processASTs(proj.getValue(), problems -> {
int length = problems.length;
if (length > 0) {
StringBuffer buffer = new StringBuffer();
for (int i = 0; i < length; i++) {
buffer.append(problems[i].toString());
buffer.append('\n');
}
return false;
}
});
if (length != 0) {
System.err.println(buffer.toString());
return true;
}
}
return false;
});
}
}
}

View File

@ -462,20 +462,15 @@ implements IFlowFunctionMap<BasicBlockInContext<E>> {
}
}
return new IUnaryFlowFunction() {
@Override
public IntSet getTargets(int d1) {
BitVectorIntSet set = new BitVectorIntSet();
if(d1 == 0 || !(domain.getMappedObject(d1).codeElement instanceof LocalElement)) {
set.add(d1);
}
DomainElement de = domain.getMappedObject(d1);
if(de!=null && parameterMap.containsKey(de.codeElement))
set.add(domain.getMappedIndex(new DomainElement(parameterMap.get(de.codeElement),de.taintSource)));
return set;
return d1 -> {
BitVectorIntSet set = new BitVectorIntSet();
if(d1 == 0 || !(domain.getMappedObject(d1).codeElement instanceof LocalElement)) {
set.add(d1);
}
DomainElement de = domain.getMappedObject(d1);
if(de!=null && parameterMap.containsKey(de.codeElement))
set.add(domain.getMappedIndex(new DomainElement(parameterMap.get(de.codeElement),de.taintSource)));
return set;
};
}

View File

@ -94,7 +94,6 @@ import com.ibm.wala.types.TypeReference;
import com.ibm.wala.util.collections.HashSetFactory;
import com.ibm.wala.util.collections.Pair;
import com.ibm.wala.util.intset.IntSet;
import com.ibm.wala.util.intset.IntSetAction;
import com.ibm.wala.util.intset.MutableSparseIntSet;
import com.ibm.wala.util.intset.OrdinalSet;
import com.ibm.wala.util.intset.SparseIntSet;
@ -494,12 +493,7 @@ public class TaintTransferFunctions<E extends ISSABasicBlock> implements
private static IUnaryFlowFunction union(final IUnaryFlowFunction g,
final IUnaryFlowFunction h) {
return new IUnaryFlowFunction() {
@Override
public IntSet getTargets(int d1) {
return g.getTargets(d1).union(h.getTargets(d1));
}
};
return d1 -> g.getTargets(d1).union(h.getTargets(d1));
}
/**
@ -511,20 +505,10 @@ public class TaintTransferFunctions<E extends ISSABasicBlock> implements
*/
private static IUnaryFlowFunction compose(final IUnaryFlowFunction f,
final IUnaryFlowFunction g) {
return new IUnaryFlowFunction() {
@Override
public IntSet getTargets(int d1) {
final MutableSparseIntSet set = MutableSparseIntSet.makeEmpty();
g.getTargets(d1).foreach(new IntSetAction() {
@Override
public void act(int x) {
set.addAll(f.getTargets(x));
}
});
return set;
}
return d1 -> {
final MutableSparseIntSet set = MutableSparseIntSet.makeEmpty();
g.getTargets(d1).foreach(x -> set.addAll(f.getTargets(x)));
return set;
};
}

View File

@ -50,7 +50,6 @@ package org.scandroid.flow.functions;
import com.ibm.wala.dataflow.IFDS.IUnaryFlowFunction;
import com.ibm.wala.util.intset.IntSet;
import com.ibm.wala.util.intset.IntSetAction;
public class TracingFlowFunction implements IUnaryFlowFunction {
private final IUnaryFlowFunction function;
@ -63,12 +62,8 @@ public class TracingFlowFunction implements IUnaryFlowFunction {
public IntSet getTargets(int d1) {
IntSet result = function.getTargets(d1);
result.foreach(new IntSetAction() {
result.foreach(x -> {
@Override
public void act(int x) {
}
});
return result;
}

View File

@ -58,7 +58,6 @@ import java.util.Deque;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.function.Predicate;
import org.scandroid.domain.CodeElement;
import org.scandroid.domain.FieldElement;
@ -198,13 +197,7 @@ public class CGAnalysisContext<E extends ISSABasicBlock> {
Warnings.clear();
pa = cgb.getPointerAnalysis();
partialGraph = GraphSlicer.prune(cg, new Predicate<CGNode>() {
@Override
// CallGraph composed of APK nodes
public boolean test(CGNode node) {
return LoaderUtils.fromLoader(node, ClassLoaderReference.Application) || node.getMethod().isSynthetic();
}
});
partialGraph = GraphSlicer.prune(cg, node -> LoaderUtils.fromLoader(node, ClassLoaderReference.Application) || node.getMethod().isSynthetic());
if (options.includeLibrary()) {
graph = (ISupergraph) ICFGSupergraph.make(cg);
} else {
@ -217,65 +210,59 @@ public class CGAnalysisContext<E extends ISSABasicBlock> {
graph = (ISupergraph) ICFGSupergraph.make(pcg);
}
oneLevelGraph = GraphSlicer.prune(cg, new Predicate<CGNode>() {
@Override
public boolean test(CGNode node) {
// Node in APK
if (LoaderUtils.fromLoader(node, ClassLoaderReference.Application)) {
return true;
} else {
Iterator<CGNode> n = cg.getPredNodes(node);
while (n.hasNext()) {
// Primordial node has a successor in APK
if (LoaderUtils.fromLoader(n.next(), ClassLoaderReference.Application))
return true;
}
n = cg.getSuccNodes(node);
while (n.hasNext()) {
// Primordial node has a predecessor in APK
if (LoaderUtils.fromLoader(n.next(), ClassLoaderReference.Application))
return true;
}
// Primordial node with no direct successors or predecessors
// to APK code
return false;
oneLevelGraph = GraphSlicer.prune(cg, node -> {
// Node in APK
if (LoaderUtils.fromLoader(node, ClassLoaderReference.Application)) {
return true;
} else {
Iterator<CGNode> n = cg.getPredNodes(node);
while (n.hasNext()) {
// Primordial node has a successor in APK
if (LoaderUtils.fromLoader(n.next(), ClassLoaderReference.Application))
return true;
}
n = cg.getSuccNodes(node);
while (n.hasNext()) {
// Primordial node has a predecessor in APK
if (LoaderUtils.fromLoader(n.next(), ClassLoaderReference.Application))
return true;
}
// Primordial node with no direct successors or predecessors
// to APK code
return false;
}
});
systemToApkGraph = GraphSlicer.prune(cg, new Predicate<CGNode>() {
@Override
public boolean test(CGNode node) {
systemToApkGraph = GraphSlicer.prune(cg, node -> {
if (LoaderUtils.fromLoader(node, ClassLoaderReference.Primordial)) {
Iterator<CGNode> succs = cg.getSuccNodes(node);
while (succs.hasNext()) {
CGNode n = succs.next();
if (LoaderUtils.fromLoader(node, ClassLoaderReference.Primordial)) {
Iterator<CGNode> succs = cg.getSuccNodes(node);
while (succs.hasNext()) {
CGNode n1 = succs.next();
if (LoaderUtils.fromLoader(n, ClassLoaderReference.Application)) {
return true;
}
if (LoaderUtils.fromLoader(n1, ClassLoaderReference.Application)) {
return true;
}
// Primordial method, with no link to APK code:
return false;
} else if (LoaderUtils.fromLoader(node, ClassLoaderReference.Application)) {
// see if this is an APK method that was
// invoked by a Primordial method:
Iterator<CGNode> preds = cg.getPredNodes(node);
while (preds.hasNext()) {
CGNode n = preds.next();
if (LoaderUtils.fromLoader(n, ClassLoaderReference.Primordial)) {
return true;
}
}
// APK code, no link to Primordial:
return false;
}
// Primordial method, with no link to APK code:
return false;
} else if (LoaderUtils.fromLoader(node, ClassLoaderReference.Application)) {
// see if this is an APK method that was
// invoked by a Primordial method:
Iterator<CGNode> preds = cg.getPredNodes(node);
while (preds.hasNext()) {
CGNode n2 = preds.next();
// who knows, not interesting:
if (LoaderUtils.fromLoader(n2, ClassLoaderReference.Primordial)) {
return true;
}
}
// APK code, no link to Primordial:
return false;
}
// who knows, not interesting:
return false;
});
/*

View File

@ -95,12 +95,7 @@ public class CopyWriter {
final ArrayList<ZipEntry> entries = new ArrayList<>();
instrumenter = new OfflineInstrumenter();
instrumenter.setManifestBuilder(new OfflineInstrumenter.ManifestBuilder() {
@Override
public void addEntry(ZipEntry ze) {
entries.add(ze);
}
});
instrumenter.setManifestBuilder(ze -> entries.add(ze));
instrumenter.parseStandardArgs(args);
instrumenter.setJARComment(copyright);
instrumenter.beginTraversal();

View File

@ -19,7 +19,6 @@ import java.security.DigestOutputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import java.util.Comparator;
import com.ibm.wala.shrikeBT.Util;
import com.ibm.wala.shrikeCT.ClassConstants;
@ -119,13 +118,10 @@ public class AddSerialVersion {
fieldCount++;
}
}
Arrays.sort(fields, 0, fieldCount, new Comparator<Integer>() {
@Override
public int compare(Integer o1, Integer o2) {
String name1 = fieldNames[o1.intValue()];
String name2 = fieldNames[o2.intValue()];
return name1.compareTo(name2);
}
Arrays.sort(fields, 0, fieldCount, (o1, o2) -> {
String name1 = fieldNames[o1.intValue()];
String name2 = fieldNames[o2.intValue()];
return name1.compareTo(name2);
});
for (int i = 0; i < fieldCount; i++) {
int f = fields[i].intValue();
@ -155,18 +151,15 @@ public class AddSerialVersion {
methodCount++;
}
}
Arrays.sort(methods, 0, methodCount, new Comparator<Integer>() {
@Override
public int compare(Integer o1, Integer o2) {
int m1 = o1.intValue();
int m2 = o2.intValue();
if (methodKinds[m1] != methodKinds[m2]) {
return methodKinds[m1] - methodKinds[m2];
}
String name1 = methodSigs[m1];
String name2 = methodSigs[m2];
return name1.compareTo(name2);
Arrays.sort(methods, 0, methodCount, (o1, o2) -> {
int m1 = o1.intValue();
int m2 = o2.intValue();
if (methodKinds[m1] != methodKinds[m2]) {
return methodKinds[m1] - methodKinds[m2];
}
String name1 = methodSigs[m1];
String name2 = methodSigs[m2];
return name1.compareTo(name2);
});
for (int i = 0; i < methodCount; i++) {
int m = methods[i].intValue();

View File

@ -263,12 +263,7 @@ public abstract class OfflineInstrumenterBase {
if (d == null) {
throw new IllegalArgumentException("d is null");
}
File[] fs = d.listFiles(new FileFilter() {
@Override
public boolean accept(File f) {
return f.isDirectory() || f.getName().endsWith(".class");
}
});
File[] fs = d.listFiles((FileFilter) f -> f.isDirectory() || f.getName().endsWith(".class"));
if (fs == null) {
throw new IllegalArgumentException("bad directory " + d.getAbsolutePath());
}

View File

@ -754,40 +754,20 @@ public class TypeAnnotationsReader extends AnnotationsReader {
TypeAnnotationsReader apply() throws InvalidClassFileException;
}
public static TypeAnnotationsReader getReaderForAnnotationAtClassfile(final AnnotationType type, final ClassReader.AttrIterator iter, final SignatureReader signatureReader) {
return advanceIter(type, iter, new Action() {
@Override
public TypeAnnotationsReader apply() throws InvalidClassFileException {
return getTypeAnnotationReaderAtClassfile(iter, type.toString(), signatureReader);
}
});
return advanceIter(type, iter, () -> getTypeAnnotationReaderAtClassfile(iter, type.toString(), signatureReader));
}
public static TypeAnnotationsReader getReaderForAnnotationAtMethodInfo(final AnnotationType type, final ClassReader.AttrIterator iter, final ExceptionsReader exceptionReader, final SignatureReader signatureReader) {
return advanceIter(type, iter, new Action() {
@Override
public TypeAnnotationsReader apply() throws InvalidClassFileException {
return getTypeAnnotationReaderAtMethodInfo(iter, type.toString(), exceptionReader, signatureReader);
}
});
return advanceIter(type, iter, () -> getTypeAnnotationReaderAtMethodInfo(iter, type.toString(), exceptionReader, signatureReader));
}
public static TypeAnnotationsReader getReaderForAnnotationAtFieldInfo(final AnnotationType type, final ClassReader.AttrIterator iter) {
return advanceIter(type, iter, new Action() {
@Override
public TypeAnnotationsReader apply() throws InvalidClassFileException {
return getTypeAnnotationReaderAtFieldInfo(iter, type.toString());
}
});
return advanceIter(type, iter, () -> getTypeAnnotationReaderAtFieldInfo(iter, type.toString()));
}
public static TypeAnnotationsReader getReaderForAnnotationAtCode(final AnnotationType type, final ClassReader.AttrIterator iter, final CodeReader codereader) {
return advanceIter(type, iter, new Action() {
@Override
public TypeAnnotationsReader apply() throws InvalidClassFileException {
return getTypeAnnotationReaderAtCode(iter, type.toString(), codereader);
}
});
return advanceIter(type, iter, () -> getTypeAnnotationReaderAtCode(iter, type.toString(), codereader));
}

Some files were not shown because too many files have changed in this diff Show More