repo
stringlengths 1
191
⌀ | file
stringlengths 23
351
| code
stringlengths 0
5.32M
| file_length
int64 0
5.32M
| avg_line_length
float64 0
2.9k
| max_line_length
int64 0
288k
| extension_type
stringclasses 1
value |
|---|---|---|---|---|---|---|
WALA
|
WALA-master/core/src/test/java/com/ibm/wala/core/tests/demandpa/NoRefinePtrTest.java
|
/*
* This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html.
*
* This file is a derivative of code released by the University of
* California under the terms listed below.
*
* Refinement Analysis Tools is Copyright (c) 2007 The Regents of the
* University of California (Regents). Provided that this notice and
* the following two paragraphs are included in any distribution of
* Refinement Analysis Tools or its derivative work, Regents agrees
* not to assert any of Regents' copyright rights in Refinement
* Analysis Tools against recipient for recipient's reproduction,
* preparation of derivative works, public display, public
* performance, distribution or sublicensing of Refinement Analysis
* Tools and derivative works, in source code and object code form.
* This agreement not to assert does not confer, by implication,
* estoppel, or otherwise any license or rights in any intellectual
* property of Regents, including, but not limited to, any patents
* of Regents or Regents' employees.
*
* IN NO EVENT SHALL REGENTS BE LIABLE TO ANY PARTY FOR DIRECT,
* INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES,
* INCLUDING LOST PROFITS, ARISING OUT OF THE USE OF THIS SOFTWARE
* AND ITS DOCUMENTATION, EVEN IF REGENTS HAS BEEN ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* REGENTS SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE AND FURTHER DISCLAIMS ANY STATUTORY
* WARRANTY OF NON-INFRINGEMENT. THE SOFTWARE AND ACCOMPANYING
* DOCUMENTATION, IF ANY, PROVIDED HEREUNDER IS PROVIDED "AS
* IS". REGENTS HAS NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT,
* UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
*/
package com.ibm.wala.core.tests.demandpa;
import com.ibm.wala.ipa.cha.ClassHierarchyException;
import com.ibm.wala.util.CancelException;
import java.io.IOException;
import org.junit.Test;
/**
* Note that in this test we still do refinement of the array contents pseudo-field, to avoid
* excessive sensitivity to library versions.
*/
public class NoRefinePtrTest extends AbstractPtrTest {
public NoRefinePtrTest() {
super(TestInfo.SCOPE_FILE);
}
@Test
public void testOnTheFlySimple()
throws ClassHierarchyException, IllegalArgumentException, CancelException, IOException {
doPointsToSizeTest(TestInfo.TEST_ONTHEFLY_SIMPLE, 1);
}
@Test
public void testArraySet()
throws ClassHierarchyException, IllegalArgumentException, CancelException, IOException {
doPointsToSizeTest(TestInfo.TEST_ARRAY_SET, 2);
}
@Test
public void testArraySetIter()
throws ClassHierarchyException, IllegalArgumentException, CancelException, IOException {
doPointsToSizeTest(TestInfo.TEST_ARRAY_SET_ITER, 2);
}
@Test
public void testHashSet()
throws ClassHierarchyException, IllegalArgumentException, CancelException, IOException {
doPointsToSizeTest(TestInfo.TEST_HASH_SET, 2);
}
@Test
public void testMethodRecursion()
throws ClassHierarchyException, IllegalArgumentException, CancelException, IOException {
doPointsToSizeTest(TestInfo.TEST_METHOD_RECURSION, 2);
}
@Test
public void testFooId()
throws ClassHierarchyException, IllegalArgumentException, CancelException, IOException {
doPointsToSizeTest(TestInfo.TEST_ID, 2);
}
@Test
public void testLocals()
throws ClassHierarchyException, IllegalArgumentException, CancelException, IOException {
doPointsToSizeTest(TestInfo.TEST_LOCALS, 1);
}
@Test
public void testArrays()
throws ClassHierarchyException, IllegalArgumentException, CancelException, IOException {
doPointsToSizeTest(TestInfo.TEST_ARRAYS, 2);
}
@Test
public void testFields()
throws ClassHierarchyException, IllegalArgumentException, CancelException, IOException {
doPointsToSizeTest(TestInfo.TEST_FIELDS, 2);
}
@Test
public void testFieldsHarder()
throws ClassHierarchyException, IllegalArgumentException, CancelException, IOException {
doPointsToSizeTest(TestInfo.TEST_FIELDS_HARDER, 2);
}
@Test
public void testGetterSetter()
throws ClassHierarchyException, IllegalArgumentException, CancelException, IOException {
doPointsToSizeTest(TestInfo.TEST_GETTER_SETTER, 2);
}
@Test
public void testException()
throws ClassHierarchyException, IllegalArgumentException, CancelException, IOException {
doPointsToSizeTest(TestInfo.TEST_EXCEPTION, 4);
}
@Test
public void testMultiDim()
throws ClassHierarchyException, IllegalArgumentException, CancelException, IOException {
doPointsToSizeTest(TestInfo.TEST_MULTI_DIM, 2);
}
@Test
public void testGlobal()
throws ClassHierarchyException, IllegalArgumentException, CancelException, IOException {
doPointsToSizeTest(TestInfo.TEST_GLOBAL, 1);
}
@Test
public void testFlowsToLocals()
throws ClassHierarchyException, IllegalArgumentException, CancelException, IOException {
// local var, init of FlowsToType, init of Object, and param of TestUtil.makeVarUsed()
doFlowsToSizeTest(TestInfo.FLOWSTO_TEST_LOCALS, 4);
}
@Test
public void testFlowsToId()
throws ClassHierarchyException, IllegalArgumentException, CancelException, IOException {
doFlowsToSizeTest(TestInfo.FLOWSTO_TEST_ID, 8);
}
@Test
public void testFlowsToFields()
throws ClassHierarchyException, IllegalArgumentException, CancelException, IOException {
doFlowsToSizeTest(TestInfo.FLOWSTO_TEST_FIELDS, 6);
}
@Test
public void testFlowsToFieldsHarder()
throws ClassHierarchyException, IllegalArgumentException, CancelException, IOException {
doFlowsToSizeTest(TestInfo.FLOWSTO_TEST_FIELDS_HARDER, 6);
}
@Test
public void testFlowsToArraySetIter()
throws ClassHierarchyException, IllegalArgumentException, CancelException, IOException {
doFlowsToSizeTest(TestInfo.FLOWSTO_TEST_ARRAYSET_ITER, 8);
}
// don't test this until we have a way to handle different library versions
// @Test
// public void testFlowsToHashSet() throws ClassHierarchyException, IllegalArgumentException,
// CancelException, IOException {
// doFlowsToSizeTest(TestInfo.FLOWSTO_TEST_HASHSET, 8);
// }
}
| 6,437
| 35.372881
| 96
|
java
|
WALA
|
WALA-master/core/src/test/java/com/ibm/wala/core/tests/demandpa/OnTheFlyPtrTest.java
|
/*
* This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html.
*
* This file is a derivative of code released by the University of
* California under the terms listed below.
*
* Refinement Analysis Tools is Copyright (c) 2007 The Regents of the
* University of California (Regents). Provided that this notice and
* the following two paragraphs are included in any distribution of
* Refinement Analysis Tools or its derivative work, Regents agrees
* not to assert any of Regents' copyright rights in Refinement
* Analysis Tools against recipient for recipient's reproduction,
* preparation of derivative works, public display, public
* performance, distribution or sublicensing of Refinement Analysis
* Tools and derivative works, in source code and object code form.
* This agreement not to assert does not confer, by implication,
* estoppel, or otherwise any license or rights in any intellectual
* property of Regents, including, but not limited to, any patents
* of Regents or Regents' employees.
*
* IN NO EVENT SHALL REGENTS BE LIABLE TO ANY PARTY FOR DIRECT,
* INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES,
* INCLUDING LOST PROFITS, ARISING OUT OF THE USE OF THIS SOFTWARE
* AND ITS DOCUMENTATION, EVEN IF REGENTS HAS BEEN ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* REGENTS SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE AND FURTHER DISCLAIMS ANY STATUTORY
* WARRANTY OF NON-INFRINGEMENT. THE SOFTWARE AND ACCOMPANYING
* DOCUMENTATION, IF ANY, PROVIDED HEREUNDER IS PROVIDED "AS
* IS". REGENTS HAS NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT,
* UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
*/
package com.ibm.wala.core.tests.demandpa;
import com.ibm.wala.demandpa.alg.DemandRefinementPointsTo;
import com.ibm.wala.demandpa.alg.refinepolicy.AlwaysRefineCGPolicy;
import com.ibm.wala.demandpa.alg.refinepolicy.AlwaysRefineFieldsPolicy;
import com.ibm.wala.demandpa.alg.refinepolicy.SinglePassRefinementPolicy;
import com.ibm.wala.ipa.cha.ClassHierarchyException;
import com.ibm.wala.util.CancelException;
import java.io.IOException;
import org.junit.Test;
public class OnTheFlyPtrTest extends AbstractPtrTest {
public OnTheFlyPtrTest() {
super(TestInfo.SCOPE_FILE);
}
@Test
public void testOnTheFlySimple()
throws ClassHierarchyException, IllegalArgumentException, CancelException, IOException {
doPointsToSizeTest(TestInfo.TEST_ONTHEFLY_SIMPLE, 1);
}
@Override
protected DemandRefinementPointsTo makeDemandPointerAnalysis(String mainClass)
throws ClassHierarchyException, IllegalArgumentException, CancelException, IOException {
DemandRefinementPointsTo dmp = super.makeDemandPointerAnalysis(mainClass);
dmp.setRefinementPolicyFactory(
new SinglePassRefinementPolicy.Factory(
new AlwaysRefineFieldsPolicy(), new AlwaysRefineCGPolicy()));
return dmp;
}
}
| 3,151
| 43.394366
| 94
|
java
|
WALA
|
WALA-master/core/src/test/java/com/ibm/wala/core/tests/demandpa/RefineFieldsPtrTest.java
|
/*
* This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html.
*
* This file is a derivative of code released by the University of
* California under the terms listed below.
*
* Refinement Analysis Tools is Copyright (c) 2007 The Regents of the
* University of California (Regents). Provided that this notice and
* the following two paragraphs are included in any distribution of
* Refinement Analysis Tools or its derivative work, Regents agrees
* not to assert any of Regents' copyright rights in Refinement
* Analysis Tools against recipient for recipient's reproduction,
* preparation of derivative works, public display, public
* performance, distribution or sublicensing of Refinement Analysis
* Tools and derivative works, in source code and object code form.
* This agreement not to assert does not confer, by implication,
* estoppel, or otherwise any license or rights in any intellectual
* property of Regents, including, but not limited to, any patents
* of Regents or Regents' employees.
*
* IN NO EVENT SHALL REGENTS BE LIABLE TO ANY PARTY FOR DIRECT,
* INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES,
* INCLUDING LOST PROFITS, ARISING OUT OF THE USE OF THIS SOFTWARE
* AND ITS DOCUMENTATION, EVEN IF REGENTS HAS BEEN ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* REGENTS SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE AND FURTHER DISCLAIMS ANY STATUTORY
* WARRANTY OF NON-INFRINGEMENT. THE SOFTWARE AND ACCOMPANYING
* DOCUMENTATION, IF ANY, PROVIDED HEREUNDER IS PROVIDED "AS
* IS". REGENTS HAS NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT,
* UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
*/
package com.ibm.wala.core.tests.demandpa;
import com.ibm.wala.demandpa.alg.DemandRefinementPointsTo;
import com.ibm.wala.demandpa.alg.refinepolicy.AlwaysRefineFieldsPolicy;
import com.ibm.wala.demandpa.alg.refinepolicy.NeverRefineCGPolicy;
import com.ibm.wala.demandpa.alg.refinepolicy.SinglePassRefinementPolicy;
import com.ibm.wala.ipa.cha.ClassHierarchyException;
import com.ibm.wala.util.CancelException;
import java.io.IOException;
import org.junit.Test;
public class RefineFieldsPtrTest extends AbstractPtrTest {
public RefineFieldsPtrTest() {
super(TestInfo.SCOPE_FILE);
}
@Test
public void testNastyPtrs()
throws ClassHierarchyException, IllegalArgumentException, CancelException, IOException {
doPointsToSizeTest(TestInfo.TEST_NASTY_PTRS, 10);
}
@Test
public void testGlobal()
throws ClassHierarchyException, IllegalArgumentException, CancelException, IOException {
doPointsToSizeTest(TestInfo.TEST_GLOBAL, 1);
}
@Test
public void testFields()
throws ClassHierarchyException, IllegalArgumentException, CancelException, IOException {
doPointsToSizeTest(TestInfo.TEST_FIELDS, 1);
}
@Test
public void testFieldsHarder()
throws ClassHierarchyException, IllegalArgumentException, CancelException, IOException {
doPointsToSizeTest(TestInfo.TEST_FIELDS_HARDER, 1);
}
@Test
public void testArrays()
throws ClassHierarchyException, IllegalArgumentException, CancelException, IOException {
doPointsToSizeTest(TestInfo.TEST_ARRAYS, 2);
}
@Test
public void testGetterSetter()
throws ClassHierarchyException, IllegalArgumentException, CancelException, IOException {
doPointsToSizeTest(TestInfo.TEST_GETTER_SETTER, 1);
}
@Test
public void testArraySet()
throws ClassHierarchyException, IllegalArgumentException, CancelException, IOException {
doPointsToSizeTest(TestInfo.TEST_ARRAY_SET, 2);
}
@Test
public void testArraySetIter()
throws ClassHierarchyException, IllegalArgumentException, CancelException, IOException {
doPointsToSizeTest(TestInfo.TEST_ARRAY_SET_ITER, 2);
}
@Test
public void testMultiDim()
throws ClassHierarchyException, IllegalArgumentException, CancelException, IOException {
doPointsToSizeTest(TestInfo.TEST_MULTI_DIM, 2);
}
@Override
public DemandRefinementPointsTo makeDemandPointerAnalysis(String mainClass)
throws ClassHierarchyException, IllegalArgumentException, CancelException, IOException {
DemandRefinementPointsTo dmp = super.makeDemandPointerAnalysis(mainClass);
dmp.setRefinementPolicyFactory(
new SinglePassRefinementPolicy.Factory(
new AlwaysRefineFieldsPolicy(), new NeverRefineCGPolicy()));
return dmp;
}
@Test
public void testFlowsToFields()
throws ClassHierarchyException, IllegalArgumentException, CancelException, IOException {
doFlowsToSizeTest(TestInfo.FLOWSTO_TEST_FIELDS, 5);
}
@Test
public void testFlowsToFieldsHarder()
throws ClassHierarchyException, IllegalArgumentException, CancelException, IOException {
doFlowsToSizeTest(TestInfo.FLOWSTO_TEST_FIELDS_HARDER, 5);
}
}
| 5,076
| 37.755725
| 94
|
java
|
WALA
|
WALA-master/core/src/test/java/com/ibm/wala/core/tests/demandpa/TestInfo.java
|
/*
* This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html.
*
* This file is a derivative of code released by the University of
* California under the terms listed below.
*
* Refinement Analysis Tools is Copyright (c) 2007 The Regents of the
* University of California (Regents). Provided that this notice and
* the following two paragraphs are included in any distribution of
* Refinement Analysis Tools or its derivative work, Regents agrees
* not to assert any of Regents' copyright rights in Refinement
* Analysis Tools against recipient for recipient's reproduction,
* preparation of derivative works, public display, public
* performance, distribution or sublicensing of Refinement Analysis
* Tools and derivative works, in source code and object code form.
* This agreement not to assert does not confer, by implication,
* estoppel, or otherwise any license or rights in any intellectual
* property of Regents, including, but not limited to, any patents
* of Regents or Regents' employees.
*
* IN NO EVENT SHALL REGENTS BE LIABLE TO ANY PARTY FOR DIRECT,
* INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES,
* INCLUDING LOST PROFITS, ARISING OUT OF THE USE OF THIS SOFTWARE
* AND ITS DOCUMENTATION, EVEN IF REGENTS HAS BEEN ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* REGENTS SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE AND FURTHER DISCLAIMS ANY STATUTORY
* WARRANTY OF NON-INFRINGEMENT. THE SOFTWARE AND ACCOMPANYING
* DOCUMENTATION, IF ANY, PROVIDED HEREUNDER IS PROVIDED "AS
* IS". REGENTS HAS NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT,
* UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
*/
package com.ibm.wala.core.tests.demandpa;
public class TestInfo {
public static final String SCOPE_FILE = "wala.testdata.txt";
// public static final String TEST1 = "Ldemandpa/Test1";
public static final String TEST_FIELDS = "Ldemandpa/TestFields";
public static final String TEST_FIELDS_HARDER = "Ldemandpa/TestFieldsHarder";
public static final String TEST_GETTER_SETTER = "Ldemandpa/TestGetterSetter";
public static final String TEST_ARRAYS = "Ldemandpa/TestArrays";
public static final String TEST_EXCEPTION = "Ldemandpa/TestException";
public static final String TEST_FACTORY = "Ldemandpa/TestFactory";
public static final String TEST_ARRAY_SET = "Ldemandpa/TestArraySet";
public static final String TEST_ARRAY_SET_ITER = "Ldemandpa/TestArraySetIter";
public static final String TEST_MULTI_DIM = "Ldemandpa/TestMultiDim";
public static final String TEST_GLOBAL = "Ldemandpa/TestGlobal";
public static final String TEST_ID = "Ldemandpa/TestId";
public static final String TEST_LOCALS = "Ldemandpa/TestLocals";
public static final String TEST_ONTHEFLY_SIMPLE = "Ldemandpa/TestOnTheFlySimple";
public static final String TEST_ONTHEFLY_CS = "Ldemandpa/TestOnTheFlyCS";
public static final String TEST_COND = "Ldemandpa/TestCond";
public static final String TEST_METHOD_RECURSION = "Ldemandpa/TestMethodRecursion";
public static final String TEST_HASH_SET = "Ldemandpa/TestHashSet";
public static final String TEST_HASHMAP_GET = "Ldemandpa/TestHashMapGet";
public static final String TEST_LINKED_LIST = "Ldemandpa/TestLinkedList";
public static final String TEST_LINKEDLIST_ITER = "Ldemandpa/TestLinkedListIter";
public static final String TEST_ARRAY_LIST = "Ldemandpa/TestArrayList";
public static final String TEST_HASHTABLE_ENUM = "Ldemandpa/TestHashtableEnum";
public static final String TEST_NASTY_PTRS = "Ldemandpa/TestNastyPtrs";
public static final String TEST_WITHIN_METHOD_CALL = "Ldemandpa/TestWithinMethodCall";
public static final String TEST_CLONE = "Ldemandpa/TestClone";
public static final String FLOWSTO_TEST_LOCALS = "Ldemandpa/FlowsToTestLocals";
public static final String FLOWSTO_TEST_ID = "Ldemandpa/FlowsToTestId";
public static final String FLOWSTO_TEST_FIELDS = "Ldemandpa/FlowsToTestFields";
public static final String FLOWSTO_TEST_FIELDS_HARDER = "Ldemandpa/FlowsToTestFieldsHarder";
public static final String FLOWSTO_TEST_ARRAYSET_ITER = "Ldemandpa/FlowsToTestArraySetIter";
public static final String FLOWSTO_TEST_HASHSET = "Ldemandpa/FlowsToTestHashSet";
}
| 4,507
| 40.740741
| 94
|
java
|
WALA
|
WALA-master/core/src/test/java/com/ibm/wala/core/tests/demandpa/TunedRefinementTest.java
|
/*
* Copyright (c) 2008 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.core.tests.demandpa;
import com.ibm.wala.core.util.strings.Atom;
import com.ibm.wala.demandpa.alg.ContextSensitiveStateMachine;
import com.ibm.wala.demandpa.alg.DemandRefinementPointsTo;
import com.ibm.wala.demandpa.alg.IDemandPointerAnalysis;
import com.ibm.wala.demandpa.alg.refinepolicy.TunedRefinementPolicy;
import com.ibm.wala.demandpa.alg.statemachine.StateMachineFactory;
import com.ibm.wala.demandpa.flowgraph.IFlowLabel;
import com.ibm.wala.ipa.callgraph.CGNode;
import com.ibm.wala.ipa.callgraph.propagation.InstanceKey;
import com.ibm.wala.ipa.callgraph.propagation.PointerKey;
import com.ibm.wala.ipa.cha.ClassHierarchyException;
import com.ibm.wala.types.Descriptor;
import com.ibm.wala.util.CancelException;
import java.io.IOException;
import java.util.Collection;
import org.junit.Assert;
import org.junit.Ignore;
import org.junit.Test;
public class TunedRefinementTest extends AbstractPtrTest {
public TunedRefinementTest() {
super(TestInfo.SCOPE_FILE);
// TODO Auto-generated constructor stub
}
@Test
public void testArraySet()
throws ClassHierarchyException, IllegalArgumentException, CancelException, IOException {
doPointsToSizeTest(TestInfo.TEST_ARRAY_SET, 1);
}
@Test
public void testClone()
throws ClassHierarchyException, IllegalArgumentException, CancelException, IOException {
doPointsToSizeTest(TestInfo.TEST_CLONE, 1);
}
@Test
public void testFooId()
throws ClassHierarchyException, IllegalArgumentException, CancelException, IOException {
doPointsToSizeTest(TestInfo.TEST_ID, 1);
}
@Test
public void testHashtableEnum()
throws ClassHierarchyException, IllegalArgumentException, CancelException, IOException {
// 3 because
// can't tell between key and value enumerators in Hashtable
doPointsToSizeTest(TestInfo.TEST_HASHTABLE_ENUM, 2);
}
// we know this one fails...
// @Test public void testOnTheFlyCS() throws ClassHierarchyException {
// String mainClass = TestInfo.TEST_ONTHEFLY_CS;
// final IDemandPointerAnalysis<InstanceKey> dmp =
// makeDemandPointerAnalysis(TestInfo.SCOPE_FILE, mainClass);
// CGNode testMethod =
// AbstractPtrTest.findInstanceMethod(dmp.getBaseCallGraph(),
// dmp.getClassHierarchy().lookupClass(
// TypeReference.findOrCreate(ClassLoaderReference.Application,
// "Ltestdata/TestOnTheFlyCS$C2")), Atom
// .findOrCreateUnicodeAtom("doSomething"),
// Descriptor.findOrCreateUTF8("(Ljava/lang/Object;)V"));
// PointerKey keyToQuery = AbstractPtrTest.getParam(testMethod, "testThisVar",
// dmp.getHeapModel());
// Collection<InstanceKey> pointsTo = dmp.getPointsTo(keyToQuery);
// if (debug) {
// System.err.println("points-to for " + mainClass + ": " + pointsTo);
// }
// assertEquals(1, pointsTo.size());
// }
@Test
public void testWithinMethodCall()
throws ClassHierarchyException, IllegalArgumentException, CancelException, IOException {
String mainClass = TestInfo.TEST_WITHIN_METHOD_CALL;
final IDemandPointerAnalysis dmp = makeDemandPointerAnalysis(mainClass);
CGNode testMethod =
AbstractPtrTest.findStaticMethod(
dmp.getBaseCallGraph(),
Atom.findOrCreateUnicodeAtom("testMethod"),
Descriptor.findOrCreateUTF8("(Ljava/lang/Object;)V"));
PointerKey keyToQuery = AbstractPtrTest.getParam(testMethod, "testThisVar", dmp.getHeapModel());
Collection<InstanceKey> pointsTo = dmp.getPointsTo(keyToQuery);
if (debug) {
System.err.println("points-to for " + mainClass + ": " + pointsTo);
}
Assert.assertEquals(1, pointsTo.size());
}
@Test
public void testLinkedListIter()
throws ClassHierarchyException, IllegalArgumentException, CancelException, IOException {
doPointsToSizeTest(TestInfo.TEST_LINKEDLIST_ITER, 1);
}
@Test
public void testGlobal()
throws ClassHierarchyException, IllegalArgumentException, CancelException, IOException {
doPointsToSizeTest(TestInfo.TEST_GLOBAL, 1);
}
@Test
public void testHashSet()
throws ClassHierarchyException, IllegalArgumentException, CancelException, IOException {
doPointsToSizeTest(TestInfo.TEST_HASH_SET, 1);
}
@Test
public void testHashMapGet()
throws ClassHierarchyException, IllegalArgumentException, CancelException, IOException {
doPointsToSizeTest(TestInfo.TEST_HASHMAP_GET, 1);
}
@Test
public void testMethodRecursion()
throws ClassHierarchyException, IllegalArgumentException, CancelException, IOException {
doPointsToSizeTest(TestInfo.TEST_METHOD_RECURSION, 2);
}
@Test
public void testArraySetIter()
throws ClassHierarchyException, IllegalArgumentException, CancelException, IOException {
doPointsToSizeTest(TestInfo.TEST_ARRAY_SET_ITER, 1);
}
@Ignore
@Test
public void testArrayList()
throws ClassHierarchyException, IllegalArgumentException, CancelException, IOException {
doPointsToSizeTest(TestInfo.TEST_ARRAY_LIST, 1);
}
@Test
public void testLinkedList()
throws ClassHierarchyException, IllegalArgumentException, CancelException, IOException {
doPointsToSizeTest(TestInfo.TEST_LINKED_LIST, 1);
}
@Override
protected StateMachineFactory<IFlowLabel> getStateMachineFactory() {
return new ContextSensitiveStateMachine.Factory();
}
@Override
protected DemandRefinementPointsTo makeDemandPointerAnalysis(String mainClass)
throws ClassHierarchyException, IllegalArgumentException, CancelException, IOException {
DemandRefinementPointsTo dmp = super.makeDemandPointerAnalysis(mainClass);
dmp.setRefinementPolicyFactory(new TunedRefinementPolicy.Factory(dmp.getClassHierarchy()));
return dmp;
}
}
| 6,092
| 35.48503
| 100
|
java
|
WALA
|
WALA-master/core/src/test/java/com/ibm/wala/core/tests/exceptionpruning/ExceptionAnalysis2EdgeFilterTest.java
|
package com.ibm.wala.core.tests.exceptionpruning;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import com.ibm.wala.analysis.exceptionanalysis.ExceptionAnalysis;
import com.ibm.wala.analysis.exceptionanalysis.ExceptionAnalysis2EdgeFilter;
import com.ibm.wala.cfg.ControlFlowGraph;
import com.ibm.wala.classLoader.Language;
import com.ibm.wala.core.tests.util.TestConstants;
import com.ibm.wala.core.util.config.AnalysisScopeReader;
import com.ibm.wala.core.util.ref.ReferenceCleanser;
import com.ibm.wala.ipa.callgraph.AnalysisCacheImpl;
import com.ibm.wala.ipa.callgraph.AnalysisOptions;
import com.ibm.wala.ipa.callgraph.AnalysisScope;
import com.ibm.wala.ipa.callgraph.CGNode;
import com.ibm.wala.ipa.callgraph.CallGraph;
import com.ibm.wala.ipa.callgraph.CallGraphBuilder;
import com.ibm.wala.ipa.callgraph.CallGraphBuilderCancelException;
import com.ibm.wala.ipa.callgraph.Entrypoint;
import com.ibm.wala.ipa.callgraph.IAnalysisCacheView;
import com.ibm.wala.ipa.callgraph.impl.Util;
import com.ibm.wala.ipa.callgraph.propagation.InstanceKey;
import com.ibm.wala.ipa.callgraph.propagation.PointerAnalysis;
import com.ibm.wala.ipa.cfg.EdgeFilter;
import com.ibm.wala.ipa.cfg.PrunedCFG;
import com.ibm.wala.ipa.cfg.exceptionpruning.ExceptionFilter2EdgeFilter;
import com.ibm.wala.ipa.cfg.exceptionpruning.filter.IgnoreExceptionsFilter;
import com.ibm.wala.ipa.cfg.exceptionpruning.interprocedural.CombinedInterproceduralExceptionFilter;
import com.ibm.wala.ipa.cfg.exceptionpruning.interprocedural.IgnoreExceptionsInterFilter;
import com.ibm.wala.ipa.cha.ClassHierarchy;
import com.ibm.wala.ipa.cha.ClassHierarchyException;
import com.ibm.wala.ipa.cha.ClassHierarchyFactory;
import com.ibm.wala.ssa.AllIntegerDueToBranchePiPolicy;
import com.ibm.wala.ssa.ISSABasicBlock;
import com.ibm.wala.ssa.SSACFG;
import com.ibm.wala.ssa.SSAInstruction;
import com.ibm.wala.ssa.SSAInvokeInstruction;
import com.ibm.wala.ssa.SSAThrowInstruction;
import com.ibm.wala.types.TypeReference;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import org.junit.BeforeClass;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ErrorCollector;
/**
* This Test checks, if the number of deleted edges is correct for TestPruning, it is also doing a
* plausibility check for deleted edges (only edges after exceptional instructions should be
* deleted) and that no new edges are inserted.
*
* @author Stephan Gocht {@code <stephan@gobro.de>}
*/
public class ExceptionAnalysis2EdgeFilterTest {
private static final ClassLoader CLASS_LOADER =
ExceptionAnalysis2EdgeFilterTest.class.getClassLoader();
public static String REGRESSION_EXCLUSIONS = "Java60RegressionExclusions.txt";
private static ClassHierarchy cha;
private static CallGraph cg;
private static PointerAnalysis<InstanceKey> pointerAnalysis;
private static CombinedInterproceduralExceptionFilter<SSAInstruction> filter;
@Rule public ErrorCollector collector = new ErrorCollector();
@BeforeClass
public static void init()
throws IOException, ClassHierarchyException, IllegalArgumentException,
CallGraphBuilderCancelException {
AnalysisOptions options;
AnalysisScope scope;
scope =
AnalysisScopeReader.instance.readJavaScope(
TestConstants.WALA_TESTDATA, new File(REGRESSION_EXCLUSIONS), CLASS_LOADER);
cha = ClassHierarchyFactory.make(scope);
Iterable<Entrypoint> entrypoints =
Util.makeMainEntrypoints(cha, "Lexceptionpruning/TestPruning");
options = new AnalysisOptions(scope, entrypoints);
options.getSSAOptions().setPiNodePolicy(new AllIntegerDueToBranchePiPolicy());
ReferenceCleanser.registerClassHierarchy(cha);
IAnalysisCacheView cache = new AnalysisCacheImpl();
ReferenceCleanser.registerCache(cache);
CallGraphBuilder<InstanceKey> builder =
Util.makeZeroCFABuilder(Language.JAVA, options, cache, cha);
cg = builder.makeCallGraph(options, null);
pointerAnalysis = builder.getPointerAnalysis();
/*
* We will ignore some exceptions to focus on the exceptions we want to
* raise (OwnException, ArrayIndexOutOfBoundException)
*/
filter = new CombinedInterproceduralExceptionFilter<>();
filter.add(
new IgnoreExceptionsInterFilter<>(
new IgnoreExceptionsFilter(TypeReference.JavaLangOutOfMemoryError)));
filter.add(
new IgnoreExceptionsInterFilter<>(
new IgnoreExceptionsFilter(TypeReference.JavaLangNullPointerException)));
filter.add(
new IgnoreExceptionsInterFilter<>(
new IgnoreExceptionsFilter(TypeReference.JavaLangExceptionInInitializerError)));
filter.add(
new IgnoreExceptionsInterFilter<>(
new IgnoreExceptionsFilter(TypeReference.JavaLangNegativeArraySizeException)));
}
@Test
public void test() {
HashMap<String, Integer> deletedExceptional = new HashMap<>();
int deletedNormal = 0;
ExceptionAnalysis analysis = new ExceptionAnalysis(cg, pointerAnalysis, cha, filter);
analysis.solve();
for (CGNode node : cg) {
if (node.getIR() != null && !node.getIR().isEmptyIR()) {
EdgeFilter<ISSABasicBlock> exceptionAnalysedEdgeFilter =
new ExceptionAnalysis2EdgeFilter(analysis, node);
SSACFG cfg_orig = node.getIR().getControlFlowGraph();
ExceptionFilter2EdgeFilter<ISSABasicBlock> filterOnlyEdgeFilter =
new ExceptionFilter2EdgeFilter<>(filter.getFilter(node), cha, cfg_orig);
ControlFlowGraph<SSAInstruction, ISSABasicBlock> cfg =
PrunedCFG.make(cfg_orig, filterOnlyEdgeFilter);
ControlFlowGraph<SSAInstruction, ISSABasicBlock> exceptionPruned =
PrunedCFG.make(cfg_orig, exceptionAnalysedEdgeFilter);
for (ISSABasicBlock block : cfg) {
if (exceptionPruned.containsNode(block)) {
for (ISSABasicBlock normalSucc : cfg.getNormalSuccessors(block)) {
if (!exceptionPruned.getNormalSuccessors(block).contains(normalSucc)) {
checkRemovingNormalOk(node, cfg, block, normalSucc);
if (node.getMethod()
.getDeclaringClass()
.getName()
.getClassName()
.toString()
.equals("TestPruning")) {
deletedNormal += 1;
}
}
}
for (ISSABasicBlock exceptionalSucc : cfg.getExceptionalSuccessors(block)) {
if (!exceptionPruned.getExceptionalSuccessors(block).contains(exceptionalSucc)) {
if (node.getMethod()
.getDeclaringClass()
.getName()
.getClassName()
.toString()
.equals("TestPruning")) {
boolean count = true;
SSAInstruction instruction = block.getLastInstruction();
if (instruction instanceof SSAInvokeInstruction
&& ((SSAInvokeInstruction) instruction).isSpecial()) {
count = false;
}
if (count) {
Integer value = 0;
String key = node.getMethod().getName().toString();
if (deletedExceptional.containsKey(key)) {
value = deletedExceptional.get(key);
}
deletedExceptional.put(key, value + 1);
}
}
}
}
}
}
checkNoNewEdges(cfg, exceptionPruned);
}
}
assertEquals("Number of normal edges deleted wrong:", 0, deletedNormal);
for (Map.Entry<String, Integer> entry : deletedExceptional.entrySet()) {
final String key = entry.getKey();
final int value = entry.getValue();
String text = "Number of exceptional edges deleted wrong for " + key + ":";
switch (key) {
case "testTryCatchMultipleExceptions":
assertEquals(text, 12, value);
break;
case "testTryCatchOwnException":
case "testTryCatchImplicitException":
assertEquals(text, 5, value);
break;
case "testTryCatchSuper":
assertEquals(text, 3, value);
break;
case "main":
assertEquals(text, 4, value);
break;
default:
assertEquals(text, 0, value);
break;
}
}
}
private static void checkRemovingNormalOk(
CGNode node,
ControlFlowGraph<SSAInstruction, ISSABasicBlock> cfg,
ISSABasicBlock block,
ISSABasicBlock normalSucc) {
if (!block.getLastInstruction().isPEI()
|| !filter.getFilter(node).alwaysThrowsException(block.getLastInstruction())) {
specialCaseThrowFiltered(cfg, normalSucc);
} else {
assertTrue(block.getLastInstruction().isPEI());
assertTrue(filter.getFilter(node).alwaysThrowsException(block.getLastInstruction()));
}
}
/**
* If a filtered exception is thrown explicit with a throw command, all previous nodes, which only
* have normal edges to the throw statement will be deleted. They don't have a connection to the
* exit node anymore.
*
* <p>So, if there is a throw statement as normal successor, evrything is fine.
*/
private static void specialCaseThrowFiltered(
ControlFlowGraph<SSAInstruction, ISSABasicBlock> cfg, ISSABasicBlock normalSucc) {
ISSABasicBlock next = normalSucc;
while (!(next.getLastInstruction() instanceof SSAThrowInstruction)) {
assertTrue(cfg.getNormalSuccessors(next).iterator().hasNext());
next = cfg.getNormalSuccessors(next).iterator().next();
}
}
private static void checkNoNewEdges(
ControlFlowGraph<SSAInstruction, ISSABasicBlock> original,
ControlFlowGraph<SSAInstruction, ISSABasicBlock> filtered) {
for (ISSABasicBlock block : filtered) {
for (ISSABasicBlock normalSucc : filtered.getNormalSuccessors(block)) {
assertTrue(original.getNormalSuccessors(block).contains(normalSucc));
}
for (ISSABasicBlock exceptionalSucc : filtered.getExceptionalSuccessors(block)) {
assertTrue(original.getExceptionalSuccessors(block).contains(exceptionalSucc));
}
}
}
}
| 10,382
| 40.039526
| 100
|
java
|
WALA
|
WALA-master/core/src/test/java/com/ibm/wala/core/tests/exceptionpruning/ExceptionAnalysisTest.java
|
package com.ibm.wala.core.tests.exceptionpruning;
import static org.hamcrest.CoreMatchers.anyOf;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.not;
import com.ibm.wala.analysis.exceptionanalysis.ExceptionAnalysis;
import com.ibm.wala.analysis.exceptionanalysis.IntraproceduralExceptionAnalysis;
import com.ibm.wala.classLoader.CallSiteReference;
import com.ibm.wala.classLoader.Language;
import com.ibm.wala.core.tests.util.TestConstants;
import com.ibm.wala.core.util.config.AnalysisScopeReader;
import com.ibm.wala.core.util.ref.ReferenceCleanser;
import com.ibm.wala.ipa.callgraph.AnalysisCacheImpl;
import com.ibm.wala.ipa.callgraph.AnalysisOptions;
import com.ibm.wala.ipa.callgraph.AnalysisScope;
import com.ibm.wala.ipa.callgraph.CGNode;
import com.ibm.wala.ipa.callgraph.CallGraph;
import com.ibm.wala.ipa.callgraph.CallGraphBuilder;
import com.ibm.wala.ipa.callgraph.CallGraphBuilderCancelException;
import com.ibm.wala.ipa.callgraph.Entrypoint;
import com.ibm.wala.ipa.callgraph.IAnalysisCacheView;
import com.ibm.wala.ipa.callgraph.impl.Util;
import com.ibm.wala.ipa.callgraph.propagation.InstanceKey;
import com.ibm.wala.ipa.callgraph.propagation.PointerAnalysis;
import com.ibm.wala.ipa.cfg.exceptionpruning.filter.IgnoreExceptionsFilter;
import com.ibm.wala.ipa.cfg.exceptionpruning.interprocedural.CombinedInterproceduralExceptionFilter;
import com.ibm.wala.ipa.cfg.exceptionpruning.interprocedural.IgnoreExceptionsInterFilter;
import com.ibm.wala.ipa.cha.ClassHierarchy;
import com.ibm.wala.ipa.cha.ClassHierarchyException;
import com.ibm.wala.ipa.cha.ClassHierarchyFactory;
import com.ibm.wala.ssa.AllIntegerDueToBranchePiPolicy;
import com.ibm.wala.ssa.SSAInstruction;
import com.ibm.wala.types.TypeReference;
import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import java.util.Set;
import org.junit.BeforeClass;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ErrorCollector;
/**
* This class checks, if the number of exceptions which might occur intra and interprocedural is
* right. As well as the number of caught exceptions for each call site.
*
* @author Stephan Gocht {@code <stephan@gobro.de>}
*/
public class ExceptionAnalysisTest {
private static final ClassLoader CLASS_LOADER = ExceptionAnalysisTest.class.getClassLoader();
public static String REGRESSION_EXCLUSIONS = "Java60RegressionExclusions.txt";
private static ClassHierarchy cha;
private static CallGraph cg;
private static PointerAnalysis<InstanceKey> pointerAnalysis;
private static CombinedInterproceduralExceptionFilter<SSAInstruction> filter;
@Rule public ErrorCollector collector = new ErrorCollector();
@BeforeClass
public static void init()
throws IOException, ClassHierarchyException, IllegalArgumentException,
CallGraphBuilderCancelException {
AnalysisOptions options;
AnalysisScope scope;
scope =
AnalysisScopeReader.instance.readJavaScope(
TestConstants.WALA_TESTDATA, new File(REGRESSION_EXCLUSIONS), CLASS_LOADER);
cha = ClassHierarchyFactory.make(scope);
Iterable<Entrypoint> entrypoints =
Util.makeMainEntrypoints(cha, "Lexceptionpruning/TestPruning");
options = new AnalysisOptions(scope, entrypoints);
options.getSSAOptions().setPiNodePolicy(new AllIntegerDueToBranchePiPolicy());
ReferenceCleanser.registerClassHierarchy(cha);
IAnalysisCacheView cache = new AnalysisCacheImpl();
ReferenceCleanser.registerCache(cache);
CallGraphBuilder<InstanceKey> builder =
Util.makeZeroCFABuilder(Language.JAVA, options, cache, cha);
cg = builder.makeCallGraph(options, null);
pointerAnalysis = builder.getPointerAnalysis();
/*
* We will ignore some exceptions to focus on the exceptions we want to
* raise (OwnException, ArrayIndexOutOfBoundException)
*/
filter = new CombinedInterproceduralExceptionFilter<>();
filter.add(
new IgnoreExceptionsInterFilter<>(
new IgnoreExceptionsFilter(TypeReference.JavaLangOutOfMemoryError)));
filter.add(
new IgnoreExceptionsInterFilter<>(
new IgnoreExceptionsFilter(TypeReference.JavaLangNullPointerException)));
filter.add(
new IgnoreExceptionsInterFilter<>(
new IgnoreExceptionsFilter(TypeReference.JavaLangExceptionInInitializerError)));
filter.add(
new IgnoreExceptionsInterFilter<>(
new IgnoreExceptionsFilter(TypeReference.JavaLangExceptionInInitializerError)));
filter.add(
new IgnoreExceptionsInterFilter<>(
new IgnoreExceptionsFilter(TypeReference.JavaLangNegativeArraySizeException)));
}
@Test
public void testIntra() {
for (CGNode node : cg) {
IntraproceduralExceptionAnalysis analysis =
new IntraproceduralExceptionAnalysis(node, filter.getFilter(node), cha, pointerAnalysis);
if (node.getMethod()
.getDeclaringClass()
.getName()
.getClassName()
.toString()
.equals("TestPruning")) {
checkThrownExceptions(node, analysis);
checkCaughtExceptions(node, analysis);
}
}
}
private void checkCaughtExceptions(CGNode node, IntraproceduralExceptionAnalysis analysis) {
String text =
"Number of caught exceptions did not match in "
+ node.getMethod().getName().toString()
+ ". The follwoing exceptions were caught: ";
Iterator<CallSiteReference> it = node.iterateCallSites();
while (it.hasNext()) {
Set<TypeReference> caught = analysis.getCaughtExceptions(it.next());
if (node.getMethod().getName().toString().matches("testTryCatch.*")) {
if (node.getMethod().getName().toString().equals("testTryCatchMultipleExceptions")) {
collector.checkThat(text + caught.toString(), caught.size(), equalTo(2));
} else if (node.getMethod().getName().toString().equals("testTryCatchSuper")) {
collector.checkThat(
text + caught.toString(),
caught.size(),
not(anyOf(equalTo(0), equalTo(1), equalTo(2), equalTo(3))));
} else {
collector.checkThat(text + caught.toString(), caught.size(), equalTo(1));
}
} else {
collector.checkThat(text + caught.toString(), caught.size(), equalTo(0));
}
}
}
private void checkThrownExceptions(CGNode node, IntraproceduralExceptionAnalysis analysis) {
Set<TypeReference> exceptions = analysis.getExceptions();
String text =
"Number of thrown exceptions did not match in "
+ node.getMethod().getName().toString()
+ ". The follwoing exceptions were thrown: "
+ exceptions.toString();
if (node.getMethod().getName().toString().matches("invokeSingle.*")
&& !node.getMethod().getName().toString().equals("invokeSingleRecursive2Helper")
&& !node.getMethod().getName().toString().equals("invokeSinglePassThrough")) {
collector.checkThat(text, exceptions.size(), equalTo(1));
} else {
collector.checkThat(text, exceptions.size(), equalTo(0));
}
}
@Test
public void testInterprocedural() {
ExceptionAnalysis analysis = new ExceptionAnalysis(cg, pointerAnalysis, cha, filter);
analysis.solve();
for (CGNode node : cg) {
if (node.getMethod()
.getDeclaringClass()
.getName()
.getClassName()
.toString()
.equals("TestPruning")) {
Set<TypeReference> exceptions = analysis.getCGNodeExceptions(node);
String text =
"Number of thrown exceptions did not match in "
+ node.getMethod().getName().toString()
+ ". The follwoing exceptions were thrown: "
+ exceptions.toString();
if (node.getMethod().getName().toString().matches("invokeSingle.*")) {
collector.checkThat(text, exceptions.size(), equalTo(1));
} else if (node.getMethod().getName().toString().matches("testTryCatch.*")) {
collector.checkThat(text, exceptions.size(), equalTo(0));
} else if (node.getMethod().getName().toString().matches("invokeAll.*")) {
collector.checkThat(text, exceptions.size(), equalTo(2));
} else if (node.getMethod().getName().toString().equals("main")) {
collector.checkThat(text, exceptions.size(), equalTo(0));
} else {
String text2 =
"Found method, i didn't know the expected number of exceptions for: "
+ node.getMethod().getName().toString();
collector.checkThat(
text2,
node.getMethod().getName().toString(),
anyOf(equalTo("main"), equalTo("<init>")));
}
analysis.getCGNodeExceptions(node);
}
}
}
}
| 8,844
| 41.320574
| 100
|
java
|
WALA
|
WALA-master/core/src/test/java/com/ibm/wala/core/tests/ir/CFGSanitizerTest.java
|
/*
* Copyright (c) 2002 - 2006 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.core.tests.ir;
import com.ibm.wala.cfg.CFGSanitizer;
import com.ibm.wala.classLoader.IMethod;
import com.ibm.wala.core.tests.callGraph.CallGraphTestUtil;
import com.ibm.wala.core.tests.util.WalaTestCase;
import com.ibm.wala.core.util.config.AnalysisScopeReader;
import com.ibm.wala.core.util.io.FileProvider;
import com.ibm.wala.ipa.callgraph.AnalysisOptions;
import com.ibm.wala.ipa.callgraph.AnalysisScope;
import com.ibm.wala.ipa.callgraph.impl.Everywhere;
import com.ibm.wala.ipa.cha.ClassHierarchy;
import com.ibm.wala.ipa.cha.ClassHierarchyFactory;
import com.ibm.wala.ipa.summaries.MethodSummary;
import com.ibm.wala.ipa.summaries.SummarizedMethod;
import com.ibm.wala.ipa.summaries.XMLMethodSummaryReader;
import com.ibm.wala.ssa.IR;
import com.ibm.wala.ssa.ISSABasicBlock;
import com.ibm.wala.ssa.SSACFG.BasicBlock;
import com.ibm.wala.types.MethodReference;
import com.ibm.wala.util.WalaException;
import com.ibm.wala.util.graph.Graph;
import java.io.IOException;
import java.io.InputStream;
import java.util.Map;
import org.junit.Assert;
import org.junit.Test;
/** Test integrity of CFGs */
public class CFGSanitizerTest extends WalaTestCase {
/**
* check that for all synthetic methods coming from the native specifications, the exit block is
* not disconnected from the rest of the sanitized graph
*/
@Test
public void testSyntheticEdgeToExit()
throws IOException, IllegalArgumentException, WalaException {
AnalysisScope scope =
AnalysisScopeReader.instance.makePrimordialScope(
new FileProvider().getFile(CallGraphTestUtil.REGRESSION_EXCLUSIONS));
ClassHierarchy cha = ClassHierarchyFactory.make(scope);
ClassLoader cl = CFGSanitizerTest.class.getClassLoader();
XMLMethodSummaryReader summary;
try (final InputStream s = cl.getResourceAsStream("natives.xml")) {
summary = new XMLMethodSummaryReader(s, scope);
}
AnalysisOptions options = new AnalysisOptions(scope, null);
Map<MethodReference, MethodSummary> summaries = summary.getSummaries();
for (Map.Entry<MethodReference, MethodSummary> entry : summaries.entrySet()) {
final MethodReference mr = entry.getKey();
IMethod m = cha.resolveMethod(mr);
if (m == null) {
continue;
}
System.out.println(m.getSignature());
MethodSummary methodSummary = entry.getValue();
SummarizedMethod summMethod = new SummarizedMethod(mr, methodSummary, m.getDeclaringClass());
IR ir = summMethod.makeIR(Everywhere.EVERYWHERE, options.getSSAOptions());
System.out.println(ir);
Graph<ISSABasicBlock> graph = CFGSanitizer.sanitize(ir, cha);
System.out.println(graph);
BasicBlock exit = ir.getControlFlowGraph().exit();
if (!exit.equals(ir.getControlFlowGraph().entry())) {
Assert.assertTrue(graph.getPredNodeCount(exit) > 0);
}
}
}
}
| 3,267
| 39.345679
| 99
|
java
|
WALA
|
WALA-master/core/src/test/java/com/ibm/wala/core/tests/ir/CFGTest.java
|
/*
* Copyright (c) 2002 - 2006 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.core.tests.ir;
import com.ibm.wala.cfg.ControlFlowGraph;
import com.ibm.wala.classLoader.IMethod;
import com.ibm.wala.classLoader.Language;
import com.ibm.wala.core.tests.util.WalaTestCase;
import com.ibm.wala.core.util.strings.StringStuff;
import com.ibm.wala.ipa.callgraph.AnalysisOptions;
import com.ibm.wala.ipa.callgraph.IAnalysisCacheView;
import com.ibm.wala.ipa.callgraph.impl.Everywhere;
import com.ibm.wala.ipa.cha.ClassHierarchyException;
import com.ibm.wala.ipa.cha.IClassHierarchy;
import com.ibm.wala.ssa.IR;
import com.ibm.wala.ssa.ISSABasicBlock;
import com.ibm.wala.ssa.SSACFG;
import com.ibm.wala.ssa.SSAInstruction;
import com.ibm.wala.ssa.SSAOptions;
import com.ibm.wala.types.MethodReference;
import com.ibm.wala.util.debug.Assertions;
import com.ibm.wala.util.graph.GraphIntegrity;
import com.ibm.wala.util.graph.GraphIntegrity.UnsoundGraphException;
import com.ibm.wala.util.intset.IntSet;
import java.io.IOException;
import org.junit.Assert;
import org.junit.Test;
/** Test integrity of CFGs */
public abstract class CFGTest extends WalaTestCase {
private final IClassHierarchy cha;
protected CFGTest(IClassHierarchy cha) {
this.cha = cha;
}
public CFGTest() throws ClassHierarchyException, IOException {
this(AnnotationTest.makeCHA());
}
public static void main(String[] args) {
justThisTest(CFGTest.class);
}
/** Build an IR, then check integrity on two flavors of CFG */
private void doMethod(String methodSig) {
try {
MethodReference mr = StringStuff.makeMethodReference(Language.JAVA, methodSig);
IMethod m = cha.resolveMethod(mr);
if (m == null) {
Assertions.UNREACHABLE("could not resolve " + mr);
}
AnalysisOptions options = new AnalysisOptions();
options.getSSAOptions().setPiNodePolicy(SSAOptions.getAllBuiltInPiNodes());
IAnalysisCacheView cache = makeAnalysisCache(options.getSSAOptions());
IR ir = cache.getIR(m, Everywhere.EVERYWHERE);
ControlFlowGraph<SSAInstruction, ISSABasicBlock> cfg = ir.getControlFlowGraph();
try {
GraphIntegrity.check(cfg);
} catch (UnsoundGraphException e) {
e.printStackTrace();
System.err.println(ir);
Assert.fail(" failed cfg integrity check for " + methodSig);
}
try {
GraphIntegrity.check(cfg);
} catch (UnsoundGraphException e) {
e.printStackTrace();
System.err.println(ir);
System.err.println(cfg);
Assert.fail(" failed 2-exit cfg integrity check for " + methodSig);
}
} catch (Exception e) {
e.printStackTrace();
Assertions.UNREACHABLE();
}
}
/**
* this method does not exist in 1.5 libraries @Test public void testFDBigInt() {
* doMethod("java.lang.FDBigInt.class$(Ljava/lang/String;)Ljava/lang/Class;"); }
*/
@Test
public void testResolveProxyClass() {
doMethod("java.io.ObjectInputStream.resolveProxyClass([Ljava/lang/String;)Ljava/lang/Class;");
}
@Test
public void testIRCacheIdempotence() {
MethodReference mr = StringStuff.makeMethodReference("hello.Hello.main([Ljava/lang/String;)V");
IMethod m = cha.resolveMethod(mr);
IAnalysisCacheView cache = makeAnalysisCache();
IR irBefore = cache.getIR(m);
cache.clear();
IR irAfter = cache.getIR(m);
for (int i = 0; i < irBefore.getInstructions().length; i++) {
System.out.println(irBefore.getInstructions()[i]);
System.out.println(irAfter.getInstructions()[i]);
Assert.assertEquals(irAfter.getInstructions()[i], irBefore.getInstructions()[i]);
}
}
@Test
public void testSync1() {
MethodReference mr = StringStuff.makeMethodReference("cfg.MonitorTest.sync1()V");
IMethod m = cha.resolveMethod(mr);
IAnalysisCacheView cache = makeAnalysisCache();
IR ir = cache.getIR(m);
System.out.println(ir);
SSACFG controlFlowGraph = ir.getControlFlowGraph();
Assert.assertEquals(
1, controlFlowGraph.getSuccNodeCount(controlFlowGraph.getBlockForInstruction(21)));
}
@Test
public void testSync2() {
MethodReference mr = StringStuff.makeMethodReference("cfg.MonitorTest.sync2()V");
IMethod m = cha.resolveMethod(mr);
IAnalysisCacheView cache = makeAnalysisCache();
IR ir = cache.getIR(m);
System.out.println(ir);
SSACFG controlFlowGraph = ir.getControlFlowGraph();
IntSet succs = controlFlowGraph.getSuccNodeNumbers(controlFlowGraph.getBlockForInstruction(13));
Assert.assertEquals(2, succs.size());
Assert.assertTrue(succs.contains(6));
Assert.assertTrue(succs.contains(7));
}
@Test
public void testSync3() {
MethodReference mr = StringStuff.makeMethodReference("cfg.MonitorTest.sync3()V");
IMethod m = cha.resolveMethod(mr);
IAnalysisCacheView cache = makeAnalysisCache();
IR ir = cache.getIR(m);
SSACFG controlFlowGraph = ir.getControlFlowGraph();
Assert.assertEquals(
1, controlFlowGraph.getSuccNodeCount(controlFlowGraph.getBlockForInstruction(33)));
}
public static void testCFG(SSACFG cfg, int[][] assertions) {
for (int i = 0; i < assertions.length; i++) {
SSACFG.BasicBlock bb = cfg.getNode(i);
Assert.assertEquals("basic block " + i, assertions[i].length, cfg.getSuccNodeCount(bb));
for (int j = 0; j < assertions[i].length; j++) {
Assert.assertTrue(cfg.hasEdge(bb, cfg.getNode(assertions[i][j])));
}
}
}
}
| 5,814
| 34.03012
| 100
|
java
|
WALA
|
WALA-master/core/src/test/java/com/ibm/wala/core/tests/ir/CornerCasesTest.java
|
/*
* Copyright (c) 2002 - 2006 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.core.tests.ir;
import com.ibm.wala.analysis.typeInference.TypeInference;
import com.ibm.wala.classLoader.IClass;
import com.ibm.wala.classLoader.IMethod;
import com.ibm.wala.classLoader.ShrikeCTMethod;
import com.ibm.wala.core.tests.callGraph.CallGraphTestUtil;
import com.ibm.wala.core.tests.util.TestConstants;
import com.ibm.wala.core.tests.util.WalaTestCase;
import com.ibm.wala.core.util.config.AnalysisScopeReader;
import com.ibm.wala.core.util.io.FileProvider;
import com.ibm.wala.core.util.strings.Atom;
import com.ibm.wala.ipa.callgraph.AnalysisCacheImpl;
import com.ibm.wala.ipa.callgraph.AnalysisOptions;
import com.ibm.wala.ipa.callgraph.AnalysisScope;
import com.ibm.wala.ipa.callgraph.impl.Everywhere;
import com.ibm.wala.ipa.cha.ClassHierarchy;
import com.ibm.wala.ipa.cha.ClassHierarchyException;
import com.ibm.wala.ipa.cha.ClassHierarchyFactory;
import com.ibm.wala.ssa.IR;
import com.ibm.wala.types.Descriptor;
import com.ibm.wala.types.Selector;
import com.ibm.wala.types.TypeReference;
import java.io.IOException;
import org.junit.Assert;
import org.junit.Test;
/**
* tests for weird corner cases, such as when the input program doesn't verify
*
* @author sfink
*/
public class CornerCasesTest extends WalaTestCase {
private static final ClassLoader MY_CLASSLOADER = CornerCasesTest.class.getClassLoader();
/** test that getMethod() works even if a declared ancestor interface doesn't exist */
@Test
public void testBug38484() throws ClassHierarchyException, IOException {
AnalysisScope scope =
AnalysisScopeReader.instance.readJavaScope(
TestConstants.WALA_TESTDATA,
new FileProvider().getFile(CallGraphTestUtil.REGRESSION_EXCLUSIONS),
MY_CLASSLOADER);
ClassHierarchy cha = ClassHierarchyFactory.make(scope);
TypeReference t =
TypeReference.findOrCreateClass(
scope.getApplicationLoader(), "cornerCases", "YuckyInterface");
IClass klass = cha.lookupClass(t);
Assert.assertNotNull(klass);
IMethod m =
klass.getMethod(
new Selector(Atom.findOrCreateAsciiAtom("x"), Descriptor.findOrCreateUTF8("()V")));
Assert.assertNull(m);
}
/**
* test that type inference works in the presence of a getfield where the field's declared type
* cannot be loaded
*/
@Test
public void testBug38540() throws ClassHierarchyException, IOException {
AnalysisScope scope =
AnalysisScopeReader.instance.readJavaScope(
TestConstants.WALA_TESTDATA,
new FileProvider().getFile(CallGraphTestUtil.REGRESSION_EXCLUSIONS),
MY_CLASSLOADER);
AnalysisOptions options = new AnalysisOptions();
ClassHierarchy cha = ClassHierarchyFactory.make(scope);
TypeReference t =
TypeReference.findOrCreateClass(scope.getApplicationLoader(), "cornerCases", "Main");
IClass klass = cha.lookupClass(t);
Assert.assertNotNull(klass);
ShrikeCTMethod m =
(ShrikeCTMethod)
klass.getMethod(
new Selector(
Atom.findOrCreateAsciiAtom("foo"),
Descriptor.findOrCreateUTF8("()Ljava/lang/Object;")));
Assert.assertNotNull(m);
IR ir =
new AnalysisCacheImpl()
.getSSACache()
.findOrCreateIR(m, Everywhere.EVERYWHERE, options.getSSAOptions());
TypeInference.make(ir, false);
}
}
| 3,779
| 36.8
| 97
|
java
|
WALA
|
WALA-master/core/src/test/java/com/ibm/wala/core/tests/ir/DeterministicIRTest.java
|
/*
* Copyright (c) 2002 - 2006 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.core.tests.ir;
import com.ibm.wala.classLoader.IMethod;
import com.ibm.wala.core.tests.util.WalaTestCase;
import com.ibm.wala.core.util.strings.Atom;
import com.ibm.wala.core.util.strings.ImmutableByteArray;
import com.ibm.wala.core.util.strings.UTF8Convert;
import com.ibm.wala.ipa.callgraph.AnalysisOptions;
import com.ibm.wala.ipa.callgraph.AnalysisScope;
import com.ibm.wala.ipa.callgraph.IAnalysisCacheView;
import com.ibm.wala.ipa.callgraph.impl.Everywhere;
import com.ibm.wala.ipa.cha.ClassHierarchyException;
import com.ibm.wala.ipa.cha.IClassHierarchy;
import com.ibm.wala.ssa.IR;
import com.ibm.wala.ssa.SSAInstruction;
import com.ibm.wala.types.MethodReference;
import com.ibm.wala.util.graph.GraphIntegrity;
import com.ibm.wala.util.graph.GraphIntegrity.UnsoundGraphException;
import java.io.IOException;
import java.util.Iterator;
import org.junit.Assert;
import org.junit.Test;
/**
* Test that the SSA-numbering of variables in the IR is deterministic.
*
* <p>Introduced 05-AUG-03; the default implementation of hashCode was being invoked.
* Object.hashCode is a source of random numbers and has no place in a deterministic program.
*/
public abstract class DeterministicIRTest extends WalaTestCase {
private final IClassHierarchy cha;
private final AnalysisOptions options = new AnalysisOptions();
protected DeterministicIRTest(IClassHierarchy cha) {
this.cha = cha;
}
public DeterministicIRTest() throws ClassHierarchyException, IOException {
this(AnnotationTest.makeCHA());
}
public static void main(String[] args) {
justThisTest(DeterministicIRTest.class);
}
private IR doMethod(MethodReference method) {
IAnalysisCacheView cache = makeAnalysisCache();
Assert.assertNotNull("method not found", method);
IMethod imethod = cha.resolveMethod(method);
Assert.assertNotNull("imethod not found", imethod);
IR ir1 = cache.getIRFactory().makeIR(imethod, Everywhere.EVERYWHERE, options.getSSAOptions());
cache.clear();
checkNotAllNull(ir1.getInstructions());
checkNoneNull(ir1.iterateAllInstructions());
try {
GraphIntegrity.check(ir1.getControlFlowGraph());
} catch (UnsoundGraphException e) {
System.err.println(ir1);
e.printStackTrace();
Assert.fail("unsound CFG for ir1");
}
IR ir2 = cache.getIRFactory().makeIR(imethod, Everywhere.EVERYWHERE, options.getSSAOptions());
cache.clear();
try {
GraphIntegrity.check(ir2.getControlFlowGraph());
} catch (UnsoundGraphException e1) {
System.err.println(ir2);
e1.printStackTrace();
Assert.fail("unsound CFG for ir2");
}
Assert.assertEquals(ir1.toString(), ir2.toString());
return ir1;
}
// The Tests ///////////////////////////////////////////////////////
private static void checkNoneNull(Iterator<?> iterator) {
while (iterator.hasNext()) {
Assert.assertNotNull(iterator.next());
}
}
private static void checkNotAllNull(SSAInstruction[] instructions) {
for (SSAInstruction instruction : instructions) {
if (instruction != null) {
return;
}
}
Assert.fail("no instructions generated");
}
@Test
public void testIR1() {
// 'remove' is a nice short method
doMethod(
cha.getScope()
.findMethod(
AnalysisScope.APPLICATION,
"Ljava/util/HashMap",
Atom.findOrCreateUnicodeAtom("remove"),
new ImmutableByteArray(
UTF8Convert.toUTF8("(Ljava/lang/Object;)Ljava/lang/Object;"))));
}
@Test
public void testIR2() {
// 'equals' is a nice medium-sized method
doMethod(
cha.getScope()
.findMethod(
AnalysisScope.APPLICATION,
"Ljava/lang/String",
Atom.findOrCreateUnicodeAtom("equals"),
new ImmutableByteArray(UTF8Convert.toUTF8("(Ljava/lang/Object;)Z"))));
}
@Test
public void testIR3() {
// 'resolveProxyClass' is a nice long method (at least in Sun libs)
doMethod(
cha.getScope()
.findMethod(
AnalysisScope.APPLICATION,
"Ljava/io/ObjectInputStream",
Atom.findOrCreateUnicodeAtom("resolveProxyClass"),
new ImmutableByteArray(
UTF8Convert.toUTF8("([Ljava/lang/String;)Ljava/lang/Class;"))));
}
@Test
public void testIR4() {
// test some corner cases with try-finally
doMethod(
cha.getScope()
.findMethod(
AnalysisScope.APPLICATION,
"LcornerCases/TryFinally",
Atom.findOrCreateUnicodeAtom("test1"),
new ImmutableByteArray(
UTF8Convert.toUTF8("(Ljava/io/InputStream;Ljava/io/InputStream;)V"))));
}
}
| 5,216
| 31.811321
| 98
|
java
|
WALA
|
WALA-master/core/src/test/java/com/ibm/wala/core/tests/ir/JVMLAnnotationTest.java
|
package com.ibm.wala.core.tests.ir;
import com.ibm.wala.ipa.cha.ClassHierarchyException;
import java.io.IOException;
public class JVMLAnnotationTest extends AnnotationTest {
public JVMLAnnotationTest() throws ClassHierarchyException, IOException {
super();
}
}
| 272
| 21.75
| 75
|
java
|
WALA
|
WALA-master/core/src/test/java/com/ibm/wala/core/tests/ir/LocalNamesTest.java
|
/*
* Copyright (c) 2002 - 2006 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.core.tests.ir;
import com.ibm.wala.classLoader.ClassLoaderFactory;
import com.ibm.wala.classLoader.ClassLoaderFactoryImpl;
import com.ibm.wala.classLoader.IClass;
import com.ibm.wala.classLoader.IMethod;
import com.ibm.wala.core.tests.util.TestConstants;
import com.ibm.wala.core.tests.util.WalaTestCase;
import com.ibm.wala.core.util.config.AnalysisScopeReader;
import com.ibm.wala.core.util.io.FileProvider;
import com.ibm.wala.core.util.strings.Atom;
import com.ibm.wala.core.util.strings.ImmutableByteArray;
import com.ibm.wala.core.util.strings.UTF8Convert;
import com.ibm.wala.ipa.callgraph.AnalysisCacheImpl;
import com.ibm.wala.ipa.callgraph.AnalysisOptions;
import com.ibm.wala.ipa.callgraph.AnalysisScope;
import com.ibm.wala.ipa.callgraph.IAnalysisCacheView;
import com.ibm.wala.ipa.callgraph.impl.Everywhere;
import com.ibm.wala.ipa.cha.ClassHierarchy;
import com.ibm.wala.ipa.cha.ClassHierarchyException;
import com.ibm.wala.ipa.cha.ClassHierarchyFactory;
import com.ibm.wala.ssa.IR;
import com.ibm.wala.ssa.SSAInstruction;
import com.ibm.wala.ssa.SSAOptions;
import com.ibm.wala.ssa.SSAPiNodePolicy;
import com.ibm.wala.types.Descriptor;
import com.ibm.wala.types.MethodReference;
import com.ibm.wala.types.Selector;
import com.ibm.wala.types.TypeReference;
import com.ibm.wala.util.debug.Assertions;
import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;
/** Test IR's getLocalNames. */
public class LocalNamesTest extends WalaTestCase {
private static final ClassLoader MY_CLASSLOADER = LocalNamesTest.class.getClassLoader();
private static AnalysisScope scope;
private static ClassHierarchy cha;
private static AnalysisOptions options;
public static void main(String[] args) {
justThisTest(LocalNamesTest.class);
}
@BeforeClass
public static void beforeClass() throws Exception {
scope =
AnalysisScopeReader.instance.readJavaScope(
TestConstants.WALA_TESTDATA,
new FileProvider().getFile("J2SEClassHierarchyExclusions.txt"),
MY_CLASSLOADER);
options = new AnalysisOptions(scope, null);
ClassLoaderFactory factory = new ClassLoaderFactoryImpl(scope.getExclusions());
try {
cha = ClassHierarchyFactory.make(scope, factory);
} catch (ClassHierarchyException e) {
throw new Exception(e);
}
}
/*
* (non-Javadoc)
*
* @see junit.framework.TestCase#tearDown()
*/
@AfterClass
public static void afterClass() throws Exception {
scope = null;
cha = null;
options = null;
}
/** Build an IR, then check getLocalNames */
@Test
public void testAliasNames() {
try {
AnalysisScope scope =
AnalysisScopeReader.instance.readJavaScope(
TestConstants.WALA_TESTDATA,
new FileProvider().getFile("J2SEClassHierarchyExclusions.txt"),
MY_CLASSLOADER);
ClassHierarchy cha = ClassHierarchyFactory.make(scope);
TypeReference t =
TypeReference.findOrCreateClass(
scope.getApplicationLoader(), "cornerCases", "AliasNames");
IClass klass = cha.lookupClass(t);
Assert.assertNotNull(klass);
IMethod m =
klass.getMethod(
new Selector(
Atom.findOrCreateAsciiAtom("foo"),
Descriptor.findOrCreateUTF8("([Ljava/lang/String;)V")));
AnalysisOptions options = new AnalysisOptions();
options.getSSAOptions().setPiNodePolicy(SSAOptions.getAllBuiltInPiNodes());
IAnalysisCacheView cache = new AnalysisCacheImpl(options.getSSAOptions());
IR ir = cache.getIR(m, Everywhere.EVERYWHERE);
for (int offsetIndex = 0; offsetIndex < ir.getInstructions().length; offsetIndex++) {
SSAInstruction instr = ir.getInstructions()[offsetIndex];
if (instr != null) {
String[] localNames = ir.getLocalNames(offsetIndex, instr.getDef());
if (localNames != null && localNames.length > 0 && localNames[0] == null) {
System.err.println(ir);
Assert.fail(
" getLocalNames() returned [null,...] for the def of instruction at offset "
+ offsetIndex
+ "\n\tinstr");
}
}
}
} catch (Exception e) {
e.printStackTrace();
Assertions.UNREACHABLE();
}
}
@Test
public void testLocalNamesWithoutPiNodes() {
SSAPiNodePolicy save = options.getSSAOptions().getPiNodePolicy();
options.getSSAOptions().setPiNodePolicy(null);
MethodReference mref =
scope.findMethod(
AnalysisScope.APPLICATION,
"LcornerCases/Locals",
Atom.findOrCreateUnicodeAtom("foo"),
new ImmutableByteArray(UTF8Convert.toUTF8("([Ljava/lang/String;)V")));
Assert.assertNotNull("method not found", mref);
IMethod imethod = cha.resolveMethod(mref);
Assert.assertNotNull("imethod not found", imethod);
IAnalysisCacheView cache = new AnalysisCacheImpl(options.getSSAOptions());
IR ir = cache.getIRFactory().makeIR(imethod, Everywhere.EVERYWHERE, options.getSSAOptions());
options.getSSAOptions().setPiNodePolicy(save);
// v1 should be the parameter "a" at pc 0
String[] names = ir.getLocalNames(0, 1);
Assert.assertNotNull("failed local name resolution for v1@0", names);
Assert.assertEquals(
"incorrect number of local names for v1@0: " + names.length, 1, names.length);
Assert.assertEquals("incorrect local name resolution for v1@0: " + names[0], "a", names[0]);
// v2 is a compiler-induced temporary
Assert.assertNull("didn't expect name for v2 at pc 2", ir.getLocalNames(2, 2));
// at pc 5, v1 should represent the locals "a" and "b"
names = ir.getLocalNames(5, 1);
Assert.assertNotNull("failed local name resolution for v1@5", names);
Assert.assertEquals(
"incorrect number of local names for v1@5: " + names.length, 2, names.length);
Assert.assertEquals("incorrect local name resolution #0 for v1@5: " + names[0], "a", names[0]);
Assert.assertEquals("incorrect local name resolution #1 for v1@5: " + names[1], "b", names[1]);
}
@Test
public void testLocalNamesWithPiNodes() {
SSAPiNodePolicy save = options.getSSAOptions().getPiNodePolicy();
options.getSSAOptions().setPiNodePolicy(SSAOptions.getAllBuiltInPiNodes());
MethodReference mref =
scope.findMethod(
AnalysisScope.APPLICATION,
"LcornerCases/Locals",
Atom.findOrCreateUnicodeAtom("foo"),
new ImmutableByteArray(UTF8Convert.toUTF8("([Ljava/lang/String;)V")));
Assert.assertNotNull("method not found", mref);
IMethod imethod = cha.resolveMethod(mref);
Assert.assertNotNull("imethod not found", imethod);
IAnalysisCacheView cache = new AnalysisCacheImpl(options.getSSAOptions());
IR ir = cache.getIRFactory().makeIR(imethod, Everywhere.EVERYWHERE, options.getSSAOptions());
options.getSSAOptions().setPiNodePolicy(save);
// v1 should be the parameter "a" at pc 0
String[] names = ir.getLocalNames(0, 1);
Assert.assertNotNull("failed local name resolution for v1@0", names);
Assert.assertEquals(
"incorrect number of local names for v1@0: " + names.length, 1, names.length);
Assert.assertEquals("incorrect local name resolution for v1@0: " + names[0], "a", names[0]);
// v2 is a compiler-induced temporary
Assert.assertNull("didn't expect name for v2 at pc 2", ir.getLocalNames(2, 2));
// at pc 5, v1 should represent the locals "a" and "b"
names = ir.getLocalNames(5, 1);
Assert.assertNotNull("failed local name resolution for v1@5", names);
Assert.assertEquals(
"incorrect number of local names for v1@5: " + names.length, 2, names.length);
Assert.assertEquals("incorrect local name resolution #0 for v1@5: " + names[0], "a", names[0]);
Assert.assertEquals("incorrect local name resolution #1 for v1@5: " + names[1], "b", names[1]);
}
}
| 8,406
| 38.843602
| 99
|
java
|
WALA
|
WALA-master/core/src/test/java/com/ibm/wala/core/tests/ir/MultiNewArrayTest.java
|
/*
* Copyright (c) 2008 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.core.tests.ir;
import com.ibm.wala.classLoader.IClass;
import com.ibm.wala.classLoader.IMethod;
import com.ibm.wala.classLoader.Language;
import com.ibm.wala.core.tests.util.TestConstants;
import com.ibm.wala.core.tests.util.WalaTestCase;
import com.ibm.wala.core.util.config.AnalysisScopeReader;
import com.ibm.wala.core.util.io.FileProvider;
import com.ibm.wala.ipa.callgraph.AnalysisCacheImpl;
import com.ibm.wala.ipa.callgraph.AnalysisScope;
import com.ibm.wala.ipa.callgraph.IAnalysisCacheView;
import com.ibm.wala.ipa.callgraph.impl.Everywhere;
import com.ibm.wala.ipa.cha.ClassHierarchy;
import com.ibm.wala.ipa.cha.ClassHierarchyException;
import com.ibm.wala.ipa.cha.ClassHierarchyFactory;
import com.ibm.wala.ssa.IR;
import com.ibm.wala.ssa.SSAInstruction;
import com.ibm.wala.ssa.SSANewInstruction;
import com.ibm.wala.ssa.SSAOptions;
import com.ibm.wala.types.ClassLoaderReference;
import com.ibm.wala.types.Selector;
import com.ibm.wala.types.TypeReference;
import java.io.IOException;
import org.junit.Assert;
import org.junit.Test;
public class MultiNewArrayTest extends WalaTestCase {
private static final ClassLoader MY_CLASSLOADER = MultiNewArrayTest.class.getClassLoader();
@Test
public void testMultiNewArray1() throws IOException, ClassHierarchyException {
AnalysisScope scope =
AnalysisScopeReader.instance.readJavaScope(
TestConstants.WALA_TESTDATA,
new FileProvider().getFile("J2SEClassHierarchyExclusions.txt"),
MY_CLASSLOADER);
ClassHierarchy cha = ClassHierarchyFactory.make(scope);
IClass klass =
cha.lookupClass(
TypeReference.findOrCreate(
ClassLoaderReference.Application, TestConstants.MULTI_DIM_MAIN));
Assert.assertNotNull(klass);
IMethod m = klass.getMethod(Selector.make(Language.JAVA, "testNewMultiArray()V"));
Assert.assertNotNull(m);
IAnalysisCacheView cache = new AnalysisCacheImpl();
IR ir = cache.getIRFactory().makeIR(m, Everywhere.EVERYWHERE, new SSAOptions());
Assert.assertNotNull(ir);
SSAInstruction[] instructions = ir.getInstructions();
for (SSAInstruction instr : instructions) {
if (instr instanceof SSANewInstruction) {
System.err.println(instr.toString(ir.getSymbolTable()));
Assert.assertEquals(2, instr.getNumberOfUses());
Assert.assertEquals(3, ir.getSymbolTable().getIntValue(instr.getUse(0)));
Assert.assertEquals(4, ir.getSymbolTable().getIntValue(instr.getUse(1)));
}
}
}
}
| 2,908
| 39.402778
| 93
|
java
|
WALA
|
WALA-master/core/src/test/java/com/ibm/wala/core/tests/ir/TypeAnnotationTest.java
|
/*
* Copyright (c) 2013,2016 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
* Martin Hecker, KIT - adaptation to type annotations
*/
package com.ibm.wala.core.tests.ir;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.containsInAnyOrder;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import com.ibm.wala.classLoader.FieldImpl;
import com.ibm.wala.classLoader.IClass;
import com.ibm.wala.classLoader.IMethod;
import com.ibm.wala.classLoader.ShrikeCTMethod;
import com.ibm.wala.classLoader.ShrikeClass;
import com.ibm.wala.core.tests.util.WalaTestCase;
import com.ibm.wala.core.util.strings.Atom;
import com.ibm.wala.ipa.cha.ClassHierarchyException;
import com.ibm.wala.ipa.cha.IClassHierarchy;
import com.ibm.wala.shrike.shrikeCT.AnnotationsReader.ConstantElementValue;
import com.ibm.wala.shrike.shrikeCT.AnnotationsReader.ElementValue;
import com.ibm.wala.shrike.shrikeCT.InvalidClassFileException;
import com.ibm.wala.shrike.shrikeCT.TypeAnnotationsReader;
import com.ibm.wala.shrike.shrikeCT.TypeAnnotationsReader.TargetType;
import com.ibm.wala.shrike.shrikeCT.TypeAnnotationsReader.TypePathKind;
import com.ibm.wala.types.ClassLoaderReference;
import com.ibm.wala.types.MethodReference;
import com.ibm.wala.types.Selector;
import com.ibm.wala.types.TypeReference;
import com.ibm.wala.types.annotations.Annotation;
import com.ibm.wala.types.annotations.TypeAnnotation;
import com.ibm.wala.util.PlatformUtil;
import com.ibm.wala.util.collections.HashMapFactory;
import com.ibm.wala.util.collections.HashSetFactory;
import com.ibm.wala.util.collections.Pair;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import org.junit.Test;
@SuppressWarnings("UnconstructableJUnitTestCase")
public class TypeAnnotationTest extends WalaTestCase {
private final IClassHierarchy cha;
protected TypeAnnotationTest(IClassHierarchy cha) {
this.cha = cha;
}
public TypeAnnotationTest() throws ClassHierarchyException, IOException {
this(AnnotationTest.makeCHA());
}
private final String typeAnnotatedClass1 = "Lannotations/TypeAnnotatedClass1";
private final String typeAnnotatedClass2 = "Lannotations/TypeAnnotatedClass2";
@Test
public void testClassAnnotations5() throws Exception {
TypeReference typeUnderTest =
TypeReference.findOrCreate(ClassLoaderReference.Application, typeAnnotatedClass1);
Collection<TypeAnnotation> expectedRuntimeInvisibleAnnotations = HashSetFactory.make();
expectedRuntimeInvisibleAnnotations.add(
TypeAnnotation.make(
Annotation.make(
TypeReference.findOrCreate(
ClassLoaderReference.Application, "Lannotations/TypeAnnotationTypeUse")),
// TODO: currently, annotations will reference class loaders from which they were
// loaded, even if the type
// comes from, e.g., primordial (e.g.: Application instead of Primordial).
// See {@link TypeAnnotation#fromString(ClassLoaderReference, String)}
new TypeAnnotation.SuperTypeTarget(
TypeReference.findOrCreate(ClassLoaderReference.Application, "Ljava/lang/Object")),
TargetType.CLASS_EXTENDS));
Collection<TypeAnnotation> expectedRuntimeVisibleAnnotations = HashSetFactory.make();
testClassAnnotations(
typeUnderTest, expectedRuntimeInvisibleAnnotations, expectedRuntimeVisibleAnnotations);
}
@Test
public void testClassAnnotations5Foo() throws Exception {
// TODO: the catchIIndex is obviously somewhat unstable wrt change in generated bytecode (and
// changes in Decoder).
// Just change it whenever a test starts to fail
final int catchIIndex = 16;
// TODO: the instanceOfIIndex is obviously somewhat unstable wrt change in generated bytecode
// (and changes in Decoder).
// This is even more so true since apparently, some compilers generate (for an instanceof test)
// the bytecode index
// not of the instanceof instruction (as required per spec:
// "The value of the offset item specifies the code array offset of either the instanceof
// bytecode instruction
// corresponding to the instanceof expression, ..."
// ), but instead of the preceding aload instruction.
//
// Just change it whenever a test starts to fail
final int instanceOfIIndex = PlatformUtil.getJavaRuntimeVersion() > 8 ? 7 : 6;
TypeReference typeUnderTest =
TypeReference.findOrCreate(ClassLoaderReference.Application, typeAnnotatedClass1);
MethodReference methodRefUnderTest =
MethodReference.findOrCreate(
typeUnderTest, Selector.make("foo(ILjava/lang/Object;)Ljava/lang/Integer;"));
Collection<TypeAnnotation> expectedRuntimeInvisibleAnnotations = HashSetFactory.make();
expectedRuntimeInvisibleAnnotations.add(
TypeAnnotation.make(
Annotation.make(
TypeReference.findOrCreate(
ClassLoaderReference.Application, "Lannotations/TypeAnnotationTypeUse")),
new TypeAnnotation.LocalVarTarget(3, "x"),
TargetType.LOCAL_VARIABLE));
expectedRuntimeInvisibleAnnotations.add(
TypeAnnotation.make(
Annotation.make(
TypeReference.findOrCreate(
ClassLoaderReference.Application, "Lannotations/TypeAnnotationTypeUse")),
new TypeAnnotation.LocalVarTarget(4, "y"),
TargetType.LOCAL_VARIABLE));
// TODO: comment wrt. ClassLoaderReference in testClassAnnotations5() also applies here
final TypeReference runtimeExceptionRef =
TypeReference.findOrCreate(ClassLoaderReference.Application, "Ljava/lang/RuntimeException");
expectedRuntimeInvisibleAnnotations.add(
TypeAnnotation.make(
Annotation.make(
TypeReference.findOrCreate(
ClassLoaderReference.Application, "Lannotations/TypeAnnotationTypeUse")),
new TypeAnnotation.CatchTarget(catchIIndex, runtimeExceptionRef),
TargetType.EXCEPTION_PARAMETER));
final Map<String, ElementValue> values = HashMapFactory.make();
values.put("someKey", new ConstantElementValue("lul"));
// TODO: comment wrt. ClassLoaderReference in testClassAnnotations5() also applies here
expectedRuntimeInvisibleAnnotations.add(
TypeAnnotation.make(
Annotation.makeWithNamed(
TypeReference.findOrCreate(
ClassLoaderReference.Application, "Lannotations/TypeAnnotationTypeUse"),
values),
new TypeAnnotation.OffsetTarget(instanceOfIIndex),
TargetType.INSTANCEOF));
expectedRuntimeInvisibleAnnotations.add(
TypeAnnotation.make(
Annotation.make(
TypeReference.findOrCreate(
ClassLoaderReference.Application, "Lannotations/TypeAnnotationTypeUse")),
new TypeAnnotation.EmptyTarget(),
TargetType.METHOD_RETURN));
expectedRuntimeInvisibleAnnotations.add(
TypeAnnotation.make(
Annotation.make(
TypeReference.findOrCreate(
ClassLoaderReference.Application, "Lannotations/TypeAnnotationTypeUse")),
new TypeAnnotation.FormalParameterTarget(0),
TargetType.METHOD_FORMAL_PARAMETER));
expectedRuntimeInvisibleAnnotations.add(
TypeAnnotation.make(
Annotation.make(
TypeReference.findOrCreate(
ClassLoaderReference.Application, "Lannotations/TypeAnnotationTypeUse")),
new TypeAnnotation.FormalParameterTarget(1),
TargetType.METHOD_FORMAL_PARAMETER));
Collection<TypeAnnotation> expectedRuntimeVisibleAnnotations = HashSetFactory.make();
testMethodAnnotations(
methodRefUnderTest, expectedRuntimeInvisibleAnnotations, expectedRuntimeVisibleAnnotations);
}
@Test
public void testClassAnnotations5field() throws Exception {
TypeReference typeUnderTest =
TypeReference.findOrCreate(ClassLoaderReference.Application, typeAnnotatedClass1);
Collection<TypeAnnotation> expectedAnnotations = HashSetFactory.make();
expectedAnnotations.add(
TypeAnnotation.make(
Annotation.make(
TypeReference.findOrCreate(
ClassLoaderReference.Application, "Lannotations/TypeAnnotationTypeUse")),
TypeAnnotationsReader.TYPEPATH_EMPTY,
new TypeAnnotation.EmptyTarget(),
TargetType.FIELD));
final List<Pair<TypePathKind, Integer>> path = new ArrayList<>();
path.add(Pair.make(TypeAnnotationsReader.TypePathKind.TYPE_ARGUMENT, 0));
path.add(Pair.make(TypeAnnotationsReader.TypePathKind.TYPE_ARGUMENT, 0));
expectedAnnotations.add(
TypeAnnotation.make(
Annotation.make(
TypeReference.findOrCreate(
ClassLoaderReference.Application, "Lannotations/TypeAnnotationTypeUse")),
path,
new TypeAnnotation.EmptyTarget(),
TargetType.FIELD));
testFieldAnnotations("field", typeUnderTest, expectedAnnotations);
}
private TypeAnnotation makeForAnnotations6(
String annotation, List<Pair<TypePathKind, Integer>> path) {
return TypeAnnotation.make(
Annotation.make(
TypeReference.findOrCreate(
ClassLoaderReference.Application, typeAnnotatedClass2 + "$" + annotation)),
path,
new TypeAnnotation.EmptyTarget(),
TargetType.FIELD);
}
@Test
public void testClassAnnotations6field1() throws Exception {
TypeReference typeUnderTest =
TypeReference.findOrCreate(ClassLoaderReference.Application, typeAnnotatedClass2);
Collection<TypeAnnotation> expectedAnnotations = HashSetFactory.make();
{
final List<Pair<TypePathKind, Integer>> pathA = new ArrayList<>();
expectedAnnotations.add(makeForAnnotations6("A", pathA));
}
{
final List<Pair<TypePathKind, Integer>> pathB = new ArrayList<>();
pathB.add(Pair.make(TypeAnnotationsReader.TypePathKind.TYPE_ARGUMENT, 0));
expectedAnnotations.add(makeForAnnotations6("B", pathB));
}
{
final List<Pair<TypePathKind, Integer>> pathC = new ArrayList<>();
pathC.add(Pair.make(TypeAnnotationsReader.TypePathKind.TYPE_ARGUMENT, 0));
pathC.add(Pair.make(TypeAnnotationsReader.TypePathKind.WILDCARD_BOUND, 0));
expectedAnnotations.add(makeForAnnotations6("C", pathC));
}
{
final List<Pair<TypePathKind, Integer>> pathD = new ArrayList<>();
pathD.add(Pair.make(TypeAnnotationsReader.TypePathKind.TYPE_ARGUMENT, 1));
expectedAnnotations.add(makeForAnnotations6("D", pathD));
}
{
final List<Pair<TypePathKind, Integer>> pathE = new ArrayList<>();
pathE.add(Pair.make(TypeAnnotationsReader.TypePathKind.TYPE_ARGUMENT, 1));
pathE.add(Pair.make(TypeAnnotationsReader.TypePathKind.TYPE_ARGUMENT, 0));
expectedAnnotations.add(makeForAnnotations6("E", pathE));
}
testFieldAnnotations("field1", typeUnderTest, expectedAnnotations);
}
private void testClassAnnotations(
TypeReference typeUnderTest,
Collection<TypeAnnotation> expectedRuntimeInvisibleAnnotations,
Collection<TypeAnnotation> expectedRuntimeVisibleAnnotations)
throws InvalidClassFileException {
IClass classUnderTest = cha.lookupClass(typeUnderTest);
assertNotNull(typeUnderTest.toString() + " not found", classUnderTest);
assertTrue(classUnderTest + " must be BytecodeClass", classUnderTest instanceof ShrikeClass);
ShrikeClass bcClassUnderTest = (ShrikeClass) classUnderTest;
Collection<TypeAnnotation> runtimeInvisibleAnnotations =
bcClassUnderTest.getTypeAnnotations(true);
AnnotationTest.assertEqualCollections(
expectedRuntimeInvisibleAnnotations, runtimeInvisibleAnnotations);
Collection<TypeAnnotation> runtimeVisibleAnnotations =
bcClassUnderTest.getTypeAnnotations(false);
AnnotationTest.assertEqualCollections(
expectedRuntimeVisibleAnnotations, runtimeVisibleAnnotations);
}
private void testMethodAnnotations(
MethodReference methodRefUnderTest,
Collection<TypeAnnotation> expectedRuntimeInvisibleAnnotations,
Collection<TypeAnnotation> expectedRuntimeVisibleAnnotations)
throws InvalidClassFileException {
IMethod methodUnderTest = cha.resolveMethod(methodRefUnderTest);
assertNotNull(methodRefUnderTest.toString() + " not found", methodUnderTest);
assertTrue(
methodUnderTest + " must be ShrikeCTMethod", methodUnderTest instanceof ShrikeCTMethod);
ShrikeCTMethod bcMethodUnderTest = (ShrikeCTMethod) methodUnderTest;
Collection<TypeAnnotation> runtimeInvisibleAnnotations = HashSetFactory.make();
runtimeInvisibleAnnotations.addAll(bcMethodUnderTest.getTypeAnnotationsAtCode(true));
runtimeInvisibleAnnotations.addAll(bcMethodUnderTest.getTypeAnnotationsAtMethodInfo(true));
assertThat(
runtimeInvisibleAnnotations,
containsInAnyOrder(expectedRuntimeInvisibleAnnotations.toArray(new TypeAnnotation[0])));
Collection<TypeAnnotation> runtimeVisibleAnnotations = HashSetFactory.make();
runtimeVisibleAnnotations.addAll(bcMethodUnderTest.getTypeAnnotationsAtCode(false));
runtimeVisibleAnnotations.addAll(bcMethodUnderTest.getTypeAnnotationsAtMethodInfo(false));
assertThat(
runtimeVisibleAnnotations,
containsInAnyOrder(expectedRuntimeVisibleAnnotations.toArray(new TypeAnnotation[0])));
}
private void testFieldAnnotations(
String fieldNameStr,
TypeReference typeUnderTest,
Collection<TypeAnnotation> expectedAnnotations) {
IClass classUnderTest = cha.lookupClass(typeUnderTest);
assertNotNull(typeUnderTest.toString() + " not found", classUnderTest);
assertTrue(classUnderTest + " must be BytecodeClass", classUnderTest instanceof ShrikeClass);
ShrikeClass bcClassUnderTest = (ShrikeClass) classUnderTest;
final Atom fieldName = Atom.findOrCreateUnicodeAtom(fieldNameStr);
FieldImpl field = (FieldImpl) bcClassUnderTest.getField(fieldName);
Collection<TypeAnnotation> annotations = field.getTypeAnnotations();
AnnotationTest.assertEqualCollections(expectedAnnotations, annotations);
}
}
| 14,762
| 43.87234
| 100
|
java
|
WALA
|
WALA-master/core/src/test/java/com/ibm/wala/core/tests/jdk11/nestmates/NestmatesTest.java
|
/*
* Copyright (c) 2006 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.core.tests.jdk11.nestmates;
import com.ibm.wala.core.tests.callGraph.CallGraphTestUtil;
import com.ibm.wala.core.tests.util.WalaTestCase;
import com.ibm.wala.ipa.callgraph.*;
import com.ibm.wala.ipa.cha.ClassHierarchy;
import com.ibm.wala.ipa.cha.ClassHierarchyException;
import com.ibm.wala.ipa.cha.ClassHierarchyFactory;
import com.ibm.wala.types.ClassLoaderReference;
import com.ibm.wala.types.MethodReference;
import com.ibm.wala.types.TypeReference;
import com.ibm.wala.util.CancelException;
import java.io.IOException;
import org.junit.Assert;
import org.junit.Test;
public class NestmatesTest extends WalaTestCase {
@Test
public void testPrivateInterfaceMethods()
throws ClassHierarchyException, IllegalArgumentException, CancelException, IOException {
AnalysisScope scope =
CallGraphTestUtil.makeJ2SEAnalysisScope(
"wala.testdata.txt", CallGraphTestUtil.REGRESSION_EXCLUSIONS);
ClassHierarchy cha = ClassHierarchyFactory.make(scope);
Iterable<Entrypoint> entrypoints =
com.ibm.wala.ipa.callgraph.impl.Util.makeMainEntrypoints(cha, "Lnestmates/TestNestmates");
AnalysisOptions options = CallGraphTestUtil.makeAnalysisOptions(scope, entrypoints);
CallGraph cg = CallGraphTestUtil.buildZeroCFA(options, new AnalysisCacheImpl(), cha, false);
// Find node corresponding to main
TypeReference tm =
TypeReference.findOrCreate(ClassLoaderReference.Application, "Lnestmates/TestNestmates");
MethodReference mm = MethodReference.findOrCreate(tm, "main", "([Ljava/lang/String;)V");
Assert.assertTrue("expect main node", cg.getNodes(mm).iterator().hasNext());
CGNode mnode = cg.getNodes(mm).iterator().next();
// should be from main to Triple()
TypeReference t1s =
TypeReference.findOrCreate(ClassLoaderReference.Application, "Lnestmates/Outer$Inner");
MethodReference t1m = MethodReference.findOrCreate(t1s, "triple", "()I");
Assert.assertTrue("expect Outer.Inner.triple node", cg.getNodes(t1m).iterator().hasNext());
CGNode t1node = cg.getNodes(t1m).iterator().next();
// Check call from main to Triple()
Assert.assertTrue(
"should have call site from main to TestNestmates.triple()",
cg.getPossibleSites(mnode, t1node).hasNext());
// check that triple() does not call an accessor method
Assert.assertFalse(
"there should not be a call from triple() to an accessor method",
cg.getSuccNodes(t1node).hasNext());
}
}
| 2,873
| 41.895522
| 98
|
java
|
WALA
|
WALA-master/core/src/test/java/com/ibm/wala/core/tests/jdk11/privateInterfaceMethods/PrivateInterfaceMethodsTest.java
|
/*
* Copyright (c) 2006 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.core.tests.jdk11.privateInterfaceMethods;
import com.ibm.wala.classLoader.IClass;
import com.ibm.wala.classLoader.IMethod;
import com.ibm.wala.core.tests.callGraph.CallGraphTestUtil;
import com.ibm.wala.core.tests.util.WalaTestCase;
import com.ibm.wala.ipa.callgraph.AnalysisCacheImpl;
import com.ibm.wala.ipa.callgraph.AnalysisOptions;
import com.ibm.wala.ipa.callgraph.AnalysisScope;
import com.ibm.wala.ipa.callgraph.CGNode;
import com.ibm.wala.ipa.callgraph.CallGraph;
import com.ibm.wala.ipa.callgraph.Entrypoint;
import com.ibm.wala.ipa.cha.ClassHierarchy;
import com.ibm.wala.ipa.cha.ClassHierarchyException;
import com.ibm.wala.ipa.cha.ClassHierarchyFactory;
import com.ibm.wala.types.ClassLoaderReference;
import com.ibm.wala.types.MethodReference;
import com.ibm.wala.types.TypeReference;
import com.ibm.wala.util.CancelException;
import java.io.IOException;
import java.util.Collection;
import org.junit.Assert;
import org.junit.Test;
public class PrivateInterfaceMethodsTest extends WalaTestCase {
@Test
public void testPrivateInterfaceMethods()
throws ClassHierarchyException, IllegalArgumentException, CancelException, IOException {
AnalysisScope scope =
CallGraphTestUtil.makeJ2SEAnalysisScope(
"wala.testdata.txt", CallGraphTestUtil.REGRESSION_EXCLUSIONS);
ClassHierarchy cha = ClassHierarchyFactory.make(scope);
Iterable<Entrypoint> entrypoints =
com.ibm.wala.ipa.callgraph.impl.Util.makeMainEntrypoints(
cha, "LprivateInterfaceMethods/testArrayReturn/TestArrayReturn");
AnalysisOptions options = CallGraphTestUtil.makeAnalysisOptions(scope, entrypoints);
CallGraph cg = CallGraphTestUtil.buildZeroCFA(options, new AnalysisCacheImpl(), cha, false);
// Find node corresponding to main
TypeReference tm =
TypeReference.findOrCreate(
ClassLoaderReference.Application,
"LprivateInterfaceMethods/testArrayReturn/TestArrayReturn");
MethodReference mm = MethodReference.findOrCreate(tm, "main", "([Ljava/lang/String;)V");
Assert.assertTrue("expect main node", cg.getNodes(mm).iterator().hasNext());
CGNode mnode = cg.getNodes(mm).iterator().next();
// should be from main to RetT
TypeReference t2s =
TypeReference.findOrCreate(
ClassLoaderReference.Application,
"LprivateInterfaceMethods/testArrayReturn/ReturnArray");
MethodReference t2m = MethodReference.findOrCreate(t2s, "RetT", "(Ljava/lang/Object;)V");
Assert.assertTrue("expect RetT node", cg.getNodes(t2m).iterator().hasNext());
CGNode t2node = cg.getNodes(t2m).iterator().next();
// Check call from main to RetT(string)
Assert.assertTrue(
"should have call site from main to TestArrayRetur.retT",
cg.getPossibleSites(mnode, t2node).hasNext());
// Find node corresponding to getT() called by retT() from main
TypeReference t3s =
TypeReference.findOrCreate(
ClassLoaderReference.Application,
"LprivateInterfaceMethods/testArrayReturn/ReturnArray");
MethodReference t3m =
MethodReference.findOrCreate(t3s, "GetT", "(Ljava/lang/Object;)Ljava/lang/Object;");
Assert.assertTrue("expect ReturnArray.GetT() node", cg.getNodes(t3m).iterator().hasNext());
CGNode t3node = cg.getNodes(t3m).iterator().next();
// Check call from RetT to GetT
Assert.assertTrue(
"should have call site from RetT to ReturnArray.GetT()",
cg.getPossibleSites(t2node, t3node).hasNext());
// check that Iclass.getAllMethods() returns both the default RetT and private GetT
TypeReference test1Type =
TypeReference.findOrCreate(
ClassLoaderReference.Application,
"LprivateInterfaceMethods/testArrayReturn/ReturnArray");
IClass test1Class = cha.lookupClass(test1Type);
Collection<? extends IMethod> allMethods = test1Class.getAllMethods();
IMethod defaultMethod = test1Class.getMethod(t2m.getSelector());
IMethod privateMethod = test1Class.getMethod(t3m.getSelector());
Assert.assertTrue(
"Expecting default methods to show up in IClass.allMethods()",
allMethods.contains(defaultMethod));
Assert.assertTrue(
"Expecting private methods to show up in IClass.allMethods()",
allMethods.contains(privateMethod));
}
}
| 4,725
| 42.357798
| 96
|
java
|
WALA
|
WALA-master/core/src/test/java/com/ibm/wala/core/tests/jdk11/stringConcat/JDK11StringConcatTest.java
|
package com.ibm.wala.core.tests.jdk11.stringConcat;
import com.ibm.wala.core.tests.callGraph.CallGraphTestUtil;
import com.ibm.wala.core.tests.util.WalaTestCase;
import com.ibm.wala.ipa.callgraph.*;
import com.ibm.wala.ipa.cha.ClassHierarchy;
import com.ibm.wala.ipa.cha.ClassHierarchyException;
import com.ibm.wala.ipa.cha.ClassHierarchyFactory;
import com.ibm.wala.types.ClassLoaderReference;
import com.ibm.wala.types.MethodReference;
import com.ibm.wala.types.TypeReference;
import com.ibm.wala.util.CancelException;
import java.io.IOException;
import org.junit.Assert;
import org.junit.Test;
/** Tests string concatenation on JDK 11+, which uses invokedynamic at the bytecode level */
public class JDK11StringConcatTest extends WalaTestCase {
@Test
public void testStringConcat()
throws ClassHierarchyException, IllegalArgumentException, CancelException, IOException {
AnalysisScope scope =
CallGraphTestUtil.makeJ2SEAnalysisScope(
"wala.testdata.txt", CallGraphTestUtil.REGRESSION_EXCLUSIONS);
ClassHierarchy cha = ClassHierarchyFactory.make(scope);
Iterable<Entrypoint> entrypoints =
com.ibm.wala.ipa.callgraph.impl.Util.makeMainEntrypoints(cha, "LstringConcat/StringConcat");
AnalysisOptions options = CallGraphTestUtil.makeAnalysisOptions(scope, entrypoints);
CallGraph cg = CallGraphTestUtil.buildZeroCFA(options, new AnalysisCacheImpl(), cha, false);
// Find node corresponding to main
TypeReference tm =
TypeReference.findOrCreate(ClassLoaderReference.Application, "LstringConcat/StringConcat");
MethodReference mm = MethodReference.findOrCreate(tm, "main", "([Ljava/lang/String;)V");
Assert.assertTrue("expect main node", cg.getNodes(mm).iterator().hasNext());
CGNode mnode = cg.getNodes(mm).iterator().next();
// should be from main to testConcat()
TypeReference t1s =
TypeReference.findOrCreate(ClassLoaderReference.Application, "LstringConcat/StringConcat");
MethodReference t1m = MethodReference.findOrCreate(t1s, "testConcat", "()Ljava/lang/String;");
Assert.assertTrue("expect testConcat node", cg.getNodes(t1m).iterator().hasNext());
CGNode t1node = cg.getNodes(t1m).iterator().next();
// Check call from main to testConcat()
Assert.assertTrue(
"should have call site from main to StringConcat.testConcat()",
cg.getPossibleSites(mnode, t1node).hasNext());
// For now, we will see no call edges from the testConcat method, as we have not added
// support for invokedynamic-based string concatenation yet
// TODO add support and change this assertion
Assert.assertFalse(
"did not expect call nodes from testConcat", cg.getSuccNodes(t1node).hasNext());
}
}
| 2,746
| 45.559322
| 100
|
java
|
WALA
|
WALA-master/core/src/test/java/com/ibm/wala/core/tests/ptrs/MultiDimArrayTest.java
|
/*
* Copyright (c) 2006 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.core.tests.ptrs;
import com.ibm.wala.classLoader.Language;
import com.ibm.wala.core.tests.callGraph.CallGraphTestUtil;
import com.ibm.wala.core.tests.util.TestConstants;
import com.ibm.wala.core.tests.util.WalaTestCase;
import com.ibm.wala.ipa.callgraph.AnalysisCacheImpl;
import com.ibm.wala.ipa.callgraph.AnalysisOptions;
import com.ibm.wala.ipa.callgraph.AnalysisScope;
import com.ibm.wala.ipa.callgraph.CGNode;
import com.ibm.wala.ipa.callgraph.CallGraph;
import com.ibm.wala.ipa.callgraph.CallGraphBuilder;
import com.ibm.wala.ipa.callgraph.Entrypoint;
import com.ibm.wala.ipa.callgraph.impl.Util;
import com.ibm.wala.ipa.callgraph.propagation.InstanceKey;
import com.ibm.wala.ipa.callgraph.propagation.PointerAnalysis;
import com.ibm.wala.ipa.callgraph.propagation.PointerKey;
import com.ibm.wala.ipa.cha.ClassHierarchy;
import com.ibm.wala.ipa.cha.ClassHierarchyException;
import com.ibm.wala.ipa.cha.ClassHierarchyFactory;
import com.ibm.wala.util.CancelException;
import com.ibm.wala.util.debug.Assertions;
import com.ibm.wala.util.intset.OrdinalSet;
import java.io.IOException;
import org.junit.Assert;
import org.junit.Test;
/**
* Test for pointer analysis of multidimensional arrays
*
* @author sfink
*/
public class MultiDimArrayTest extends WalaTestCase {
public static void main(String[] args) {
justThisTest(MultiDimArrayTest.class);
}
public MultiDimArrayTest() {}
@Test
public void testMultiDim()
throws ClassHierarchyException, IllegalArgumentException, CancelException, IOException {
AnalysisScope scope =
CallGraphTestUtil.makeJ2SEAnalysisScope(
TestConstants.WALA_TESTDATA, CallGraphTestUtil.REGRESSION_EXCLUSIONS);
ClassHierarchy cha = ClassHierarchyFactory.make(scope);
Iterable<Entrypoint> entrypoints =
com.ibm.wala.ipa.callgraph.impl.Util.makeMainEntrypoints(cha, TestConstants.MULTI_DIM_MAIN);
AnalysisOptions options = CallGraphTestUtil.makeAnalysisOptions(scope, entrypoints);
CallGraphBuilder<InstanceKey> builder =
Util.makeVanillaZeroOneCFABuilder(Language.JAVA, options, new AnalysisCacheImpl(), cha);
CallGraph cg = builder.makeCallGraph(options, null);
PointerAnalysis<InstanceKey> pa = builder.getPointerAnalysis();
CGNode node = findDoNothingNode(cg);
PointerKey pk = pa.getHeapModel().getPointerKeyForLocal(node, 1);
OrdinalSet<InstanceKey> ptsTo = pa.getPointsToSet(pk);
Assert.assertEquals(1, ptsTo.size());
}
private static final CGNode findDoNothingNode(CallGraph cg) {
for (CGNode n : cg) {
if (n.getMethod().getName().toString().equals("doNothing")) {
return n;
}
}
Assertions.UNREACHABLE("Unexpected: failed to find doNothing node");
return null;
}
}
| 3,140
| 36.843373
| 100
|
java
|
WALA
|
WALA-master/core/src/test/java/com/ibm/wala/core/tests/ptrs/ObjectSensitiveTest.java
|
/*
* Copyright (c) 2002 - 2020 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.core.tests.ptrs;
import com.ibm.wala.core.tests.callGraph.CallGraphTestUtil;
import com.ibm.wala.core.tests.util.TestConstants;
import com.ibm.wala.ipa.callgraph.AnalysisCacheImpl;
import com.ibm.wala.ipa.callgraph.AnalysisOptions;
import com.ibm.wala.ipa.callgraph.AnalysisScope;
import com.ibm.wala.ipa.callgraph.CGNode;
import com.ibm.wala.ipa.callgraph.CallGraph;
import com.ibm.wala.ipa.callgraph.CallGraphBuilder;
import com.ibm.wala.ipa.callgraph.CallGraphBuilderCancelException;
import com.ibm.wala.ipa.callgraph.Entrypoint;
import com.ibm.wala.ipa.callgraph.impl.Util;
import com.ibm.wala.ipa.callgraph.propagation.InstanceKey;
import com.ibm.wala.ipa.callgraph.propagation.LocalPointerKey;
import com.ibm.wala.ipa.callgraph.propagation.PointerAnalysis;
import com.ibm.wala.ipa.cha.ClassHierarchy;
import com.ibm.wala.ipa.cha.ClassHierarchyException;
import com.ibm.wala.ipa.cha.ClassHierarchyFactory;
import com.ibm.wala.types.ClassLoaderReference;
import com.ibm.wala.types.MethodReference;
import com.ibm.wala.types.TypeReference;
import com.ibm.wala.util.collections.Pair;
import com.ibm.wala.util.intset.OrdinalSet;
import java.io.IOException;
import java.util.Optional;
import java.util.Set;
import org.junit.Assert;
import org.junit.Test;
/** test case for nObjBuilder */
public class ObjectSensitiveTest {
@Test
public void testObjSensitive1()
throws IOException, ClassHierarchyException, CallGraphBuilderCancelException {
doPointsToSizeTest(1, TestConstants.OBJECT_SENSITIVE_TEST1, 1);
}
@Test
public void testObjSensitive2()
throws IOException, ClassHierarchyException, CallGraphBuilderCancelException {
// If n is set to 2, the pts of the parameter will be inaccurate
doPointsToSizeTest(2, TestConstants.OBJECT_SENSITIVE_TEST2, 2);
doPointsToSizeTest(3, TestConstants.OBJECT_SENSITIVE_TEST2, 1);
}
public static void doPointsToSizeTest(int n, String mainClass, int expectedSize)
throws IOException, ClassHierarchyException, CallGraphBuilderCancelException {
Pair<CallGraph, PointerAnalysis<InstanceKey>> pair = initCallGraph(n, mainClass);
CallGraph cg = pair.fst;
PointerAnalysis<InstanceKey> pa = pair.snd;
// find the doNothing call, and check the parameter's points-to set
CGNode doNothing = findDoNothingCall(cg, mainClass);
LocalPointerKey localPointerKey =
new LocalPointerKey(doNothing, doNothing.getIR().getParameter(0));
OrdinalSet<InstanceKey> pts = pa.getPointsToSet(localPointerKey);
Assert.assertEquals(pts.size(), expectedSize);
}
private static Pair<CallGraph, PointerAnalysis<InstanceKey>> initCallGraph(
int n, String mainClass)
throws IOException, ClassHierarchyException, CallGraphBuilderCancelException {
AnalysisScope scope =
CallGraphTestUtil.makeJ2SEAnalysisScope(
TestConstants.WALA_TESTDATA, CallGraphTestUtil.REGRESSION_EXCLUSIONS);
ClassHierarchy cha = ClassHierarchyFactory.make(scope);
Iterable<Entrypoint> entrypoints =
com.ibm.wala.ipa.callgraph.impl.Util.makeMainEntrypoints(cha, mainClass);
AnalysisOptions options = CallGraphTestUtil.makeAnalysisOptions(scope, entrypoints);
CallGraphBuilder<InstanceKey> builder =
Util.makeVanillaNObjBuilder(n, options, new AnalysisCacheImpl(), cha);
CallGraph cg = builder.makeCallGraph(options, null);
PointerAnalysis<InstanceKey> pa = builder.getPointerAnalysis();
return Pair.make(cg, pa);
}
private static CGNode findDoNothingCall(CallGraph cg, String mainClass) {
TypeReference mainClassTr =
TypeReference.findOrCreate(ClassLoaderReference.Application, mainClass);
MethodReference mr =
MethodReference.findOrCreate(mainClassTr, "doNothing", "(Ljava/lang/Object;)V");
Set<CGNode> nodes = cg.getNodes(mr);
Assert.assertEquals(1, nodes.size());
Optional<CGNode> firstMatched = nodes.stream().findFirst();
Assert.assertTrue(firstMatched.isPresent());
return firstMatched.get();
}
}
| 4,406
| 40.186916
| 88
|
java
|
WALA
|
WALA-master/core/src/test/java/com/ibm/wala/core/tests/ptrs/TypeBasedArrayAliasTest.java
|
/*
* Copyright (c) 2008 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.core.tests.ptrs;
import com.ibm.wala.core.tests.callGraph.CallGraphTestUtil;
import com.ibm.wala.core.tests.util.TestConstants;
import com.ibm.wala.core.tests.util.WalaTestCase;
import com.ibm.wala.ipa.callgraph.AnalysisCacheImpl;
import com.ibm.wala.ipa.callgraph.AnalysisOptions;
import com.ibm.wala.ipa.callgraph.AnalysisScope;
import com.ibm.wala.ipa.callgraph.CGNode;
import com.ibm.wala.ipa.callgraph.CallGraph;
import com.ibm.wala.ipa.callgraph.CallGraphBuilder;
import com.ibm.wala.ipa.callgraph.Entrypoint;
import com.ibm.wala.ipa.callgraph.impl.Util;
import com.ibm.wala.ipa.callgraph.propagation.InstanceKey;
import com.ibm.wala.ipa.callgraph.propagation.PointerAnalysis;
import com.ibm.wala.ipa.callgraph.propagation.PointerKey;
import com.ibm.wala.ipa.cha.ClassHierarchy;
import com.ibm.wala.ipa.cha.ClassHierarchyException;
import com.ibm.wala.ipa.cha.ClassHierarchyFactory;
import com.ibm.wala.util.CancelException;
import com.ibm.wala.util.debug.Assertions;
import com.ibm.wala.util.intset.OrdinalSet;
import java.io.IOException;
import org.junit.Assert;
import org.junit.Test;
public class TypeBasedArrayAliasTest extends WalaTestCase {
@Test
public void testTypeBasedArrayAlias()
throws ClassHierarchyException, IllegalArgumentException, CancelException, IOException {
AnalysisScope scope =
CallGraphTestUtil.makeJ2SEAnalysisScope(
TestConstants.WALA_TESTDATA, CallGraphTestUtil.REGRESSION_EXCLUSIONS);
ClassHierarchy cha = ClassHierarchyFactory.make(scope);
Iterable<Entrypoint> entrypoints =
com.ibm.wala.ipa.callgraph.impl.Util.makeMainEntrypoints(
cha, TestConstants.ARRAY_ALIAS_MAIN);
AnalysisOptions options = CallGraphTestUtil.makeAnalysisOptions(scope, entrypoints);
// RTA yields a TypeBasedPointerAnalysis
CallGraphBuilder<InstanceKey> builder =
Util.makeRTABuilder(options, new AnalysisCacheImpl(), cha);
CallGraph cg = builder.makeCallGraph(options, null);
PointerAnalysis<InstanceKey> pa = builder.getPointerAnalysis();
CGNode node = findNode(cg, "testMayAlias1");
PointerKey pk1 = pa.getHeapModel().getPointerKeyForLocal(node, 1);
PointerKey pk2 = pa.getHeapModel().getPointerKeyForLocal(node, 2);
Assert.assertTrue(mayAliased(pk1, pk2, pa));
node = findNode(cg, "testMayAlias2");
pk1 = pa.getHeapModel().getPointerKeyForLocal(node, 1);
pk2 = pa.getHeapModel().getPointerKeyForLocal(node, 2);
Assert.assertTrue(mayAliased(pk1, pk2, pa));
node = findNode(cg, "testMayAlias3");
pk1 = pa.getHeapModel().getPointerKeyForLocal(node, 1);
pk2 = pa.getHeapModel().getPointerKeyForLocal(node, 2);
Assert.assertTrue(mayAliased(pk1, pk2, pa));
}
private static final CGNode findNode(CallGraph cg, String methodName) {
for (CGNode n : cg) {
if (n.getMethod().getName().toString().equals(methodName)) {
return n;
}
}
Assertions.UNREACHABLE("Unexpected: failed to find " + methodName + " node");
return null;
}
private static boolean mayAliased(
PointerKey pk1, PointerKey pk2, PointerAnalysis<InstanceKey> pa) {
OrdinalSet<InstanceKey> ptsTo1 = pa.getPointsToSet(pk1);
OrdinalSet<InstanceKey> ptsTo2 = pa.getPointsToSet(pk2);
boolean foundIntersection = false;
outer:
for (InstanceKey i : ptsTo1) {
for (InstanceKey j : ptsTo2) {
if (i.equals(j)) {
foundIntersection = true;
break outer;
}
}
}
return foundIntersection;
}
}
| 3,907
| 38.08
| 94
|
java
|
WALA
|
WALA-master/core/src/test/java/com/ibm/wala/core/tests/ptrs/ZeroLengthArrayTest.java
|
/*
* Copyright (c) 2008 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.core.tests.ptrs;
import com.ibm.wala.classLoader.Language;
import com.ibm.wala.core.tests.callGraph.CallGraphTestUtil;
import com.ibm.wala.core.tests.util.TestConstants;
import com.ibm.wala.ipa.callgraph.AnalysisCacheImpl;
import com.ibm.wala.ipa.callgraph.AnalysisOptions;
import com.ibm.wala.ipa.callgraph.AnalysisScope;
import com.ibm.wala.ipa.callgraph.CGNode;
import com.ibm.wala.ipa.callgraph.CallGraph;
import com.ibm.wala.ipa.callgraph.CallGraphBuilder;
import com.ibm.wala.ipa.callgraph.Entrypoint;
import com.ibm.wala.ipa.callgraph.impl.Everywhere;
import com.ibm.wala.ipa.callgraph.impl.Util;
import com.ibm.wala.ipa.callgraph.propagation.HeapModel;
import com.ibm.wala.ipa.callgraph.propagation.InstanceKey;
import com.ibm.wala.ipa.callgraph.propagation.PointerAnalysis;
import com.ibm.wala.ipa.cha.ClassHierarchy;
import com.ibm.wala.ipa.cha.ClassHierarchyException;
import com.ibm.wala.ipa.cha.ClassHierarchyFactory;
import com.ibm.wala.types.ClassLoaderReference;
import com.ibm.wala.types.MethodReference;
import com.ibm.wala.types.Selector;
import com.ibm.wala.types.TypeReference;
import com.ibm.wala.util.CancelException;
import com.ibm.wala.util.intset.OrdinalSet;
import java.io.IOException;
import org.junit.Assert;
import org.junit.Test;
public class ZeroLengthArrayTest {
@Test
public void testZeroLengthArray()
throws ClassHierarchyException, IllegalArgumentException, CancelException, IOException {
AnalysisScope scope =
CallGraphTestUtil.makeJ2SEAnalysisScope(
TestConstants.WALA_TESTDATA, CallGraphTestUtil.REGRESSION_EXCLUSIONS);
ClassHierarchy cha = ClassHierarchyFactory.make(scope);
Iterable<Entrypoint> entrypoints =
com.ibm.wala.ipa.callgraph.impl.Util.makeMainEntrypoints(
cha, TestConstants.ZERO_LENGTH_ARRAY_MAIN);
AnalysisOptions options = CallGraphTestUtil.makeAnalysisOptions(scope, entrypoints);
CallGraphBuilder<InstanceKey> builder =
Util.makeVanillaZeroOneCFABuilder(Language.JAVA, options, new AnalysisCacheImpl(), cha);
CallGraph cg = builder.makeCallGraph(options, null);
PointerAnalysis<InstanceKey> pa = builder.getPointerAnalysis();
// System.err.println(pa);
HeapModel heapModel = pa.getHeapModel();
CGNode mainNode =
cg.getNode(
cha.resolveMethod(
MethodReference.findOrCreate(
TypeReference.findOrCreate(
ClassLoaderReference.Application, TestConstants.ZERO_LENGTH_ARRAY_MAIN),
Selector.make("main([Ljava/lang/String;)V"))),
Everywhere.EVERYWHERE);
OrdinalSet<InstanceKey> pointsToSet =
pa.getPointsToSet(heapModel.getPointerKeyForLocal(mainNode, 4));
Assert.assertEquals(1, pointsToSet.size());
InstanceKey arrayKey = pointsToSet.iterator().next();
OrdinalSet<InstanceKey> arrayContents =
pa.getPointsToSet(heapModel.getPointerKeyForArrayContents(arrayKey));
System.err.println(arrayContents);
Assert.assertEquals(0, arrayContents.size());
}
}
| 3,447
| 42.1
| 96
|
java
|
WALA
|
WALA-master/core/src/test/java/com/ibm/wala/core/tests/shrike/DynamicCallGraphTest.java
|
/*
* Copyright (c) 2002 - 2014 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.core.tests.shrike;
import com.ibm.wala.core.tests.callGraph.CallGraphTestUtil;
import com.ibm.wala.core.tests.util.TestConstants;
import com.ibm.wala.ipa.callgraph.AnalysisCacheImpl;
import com.ibm.wala.ipa.callgraph.AnalysisOptions;
import com.ibm.wala.ipa.callgraph.AnalysisScope;
import com.ibm.wala.ipa.callgraph.CallGraph;
import com.ibm.wala.ipa.callgraph.Entrypoint;
import com.ibm.wala.ipa.cha.ClassHierarchy;
import com.ibm.wala.ipa.cha.ClassHierarchyException;
import com.ibm.wala.ipa.cha.ClassHierarchyFactory;
import com.ibm.wala.shrike.shrikeBT.analysis.Analyzer.FailureException;
import com.ibm.wala.shrike.shrikeCT.InvalidClassFileException;
import com.ibm.wala.util.CancelException;
import java.io.IOException;
import org.junit.Test;
public abstract class DynamicCallGraphTest extends DynamicCallGraphTestBase {
protected final String testJarLocation;
protected DynamicCallGraphTest(String testJarLocation) {
this.testJarLocation = testJarLocation;
}
public DynamicCallGraphTest() {
this(getClasspathEntry("core"));
}
private static CallGraph staticCG(String mainClass, String exclusionsFile)
throws IOException, ClassHierarchyException, IllegalArgumentException, CancelException {
AnalysisScope scope =
CallGraphTestUtil.makeJ2SEAnalysisScope(
TestConstants.WALA_TESTDATA,
exclusionsFile != null ? exclusionsFile : CallGraphTestUtil.REGRESSION_EXCLUSIONS);
ClassHierarchy cha = ClassHierarchyFactory.make(scope);
Iterable<Entrypoint> entrypoints =
com.ibm.wala.ipa.callgraph.impl.Util.makeMainEntrypoints(cha, mainClass);
AnalysisOptions options = CallGraphTestUtil.makeAnalysisOptions(scope, entrypoints);
return CallGraphTestUtil.buildZeroOneCFA(options, new AnalysisCacheImpl(), cha, false);
}
@Test
public void testGraph()
throws IOException, ClassNotFoundException, InvalidClassFileException, FailureException,
SecurityException, IllegalArgumentException, ClassHierarchyException, CancelException,
InterruptedException {
instrument(testJarLocation);
run("dynamicCG.MainClass", null);
CallGraph staticCG = staticCG("LdynamicCG/MainClass", null);
checkEdges(staticCG);
}
@Test
public void testCallbacks()
throws IOException, ClassNotFoundException, InvalidClassFileException, FailureException,
SecurityException, IllegalArgumentException, ClassHierarchyException, CancelException,
InterruptedException {
instrument(testJarLocation);
run("dynamicCG.CallbacksMainClass", null);
CallGraph staticCG = staticCG("LdynamicCG/CallbacksMainClass", null);
checkEdges(staticCG);
}
@Test
public void testExclusions()
throws IOException, ClassNotFoundException, InvalidClassFileException, FailureException,
SecurityException, IllegalArgumentException, ClassHierarchyException, CancelException,
InterruptedException {
instrument(testJarLocation);
run("dynamicCG.MainClass", "ShrikeTestExclusions.txt");
CallGraph staticCG = staticCG("LdynamicCG/MainClass", "ShrikeTestExclusions.txt");
checkEdges(staticCG);
}
@Test
public void testLambdas()
throws IOException, ClassNotFoundException, InvalidClassFileException, FailureException,
SecurityException, IllegalArgumentException, ClassHierarchyException, CancelException,
InterruptedException {
instrument(testJarLocation);
run("lambda.SortingExample", null);
CallGraph staticCG = staticCG("Llambda/SortingExample", null);
checkEdges(staticCG);
}
}
| 3,988
| 39.292929
| 96
|
java
|
WALA
|
WALA-master/core/src/test/java/com/ibm/wala/core/tests/shrike/FloatingPointsTest.java
|
package com.ibm.wala.core.tests.shrike;
import com.ibm.wala.core.tests.util.WalaTestCase;
import com.ibm.wala.shrike.shrikeBT.ConstantInstruction;
import com.ibm.wala.shrike.shrikeBT.Constants;
import com.ibm.wala.shrike.shrikeBT.IInstruction;
import com.ibm.wala.shrike.shrikeBT.MethodData;
import com.ibm.wala.shrike.shrikeBT.MethodEditor;
import com.ibm.wala.shrike.shrikeBT.MethodEditor.Output;
import com.ibm.wala.shrike.shrikeBT.shrikeCT.ClassInstrumenter;
import com.ibm.wala.shrike.shrikeBT.shrikeCT.OfflineInstrumenter;
import com.ibm.wala.shrike.shrikeCT.ClassReader;
import com.ibm.wala.shrike.shrikeCT.ClassWriter;
import com.ibm.wala.shrike.shrikeCT.InvalidClassFileException;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
@SuppressWarnings("UnconstructableJUnitTestCase")
public class FloatingPointsTest extends WalaTestCase {
private final String klass = "shrike/FloatingPoints";
private final String testJarLocation;
private OfflineInstrumenter instrumenter;
private Path instrumentedJarLocation;
private List<ClassInstrumenter> classInstrumenters;
protected FloatingPointsTest(String testJarLocation) {
this.testJarLocation = testJarLocation;
}
public FloatingPointsTest() {
this(getClasspathEntry(String.join(File.separator, "classes", "java", "testSubjects")));
}
@Before
public void setOfflineInstrumenter() throws IOException {
// Create a temporary file for the shrike instrumented output
instrumentedJarLocation = Files.createTempFile("wala-test", ".jar");
instrumentedJarLocation.toFile().deleteOnExit();
// Initialize the OfflineInstrumenter loading the class file specified in
// 'klass' above
instrumenter = new OfflineInstrumenter();
instrumenter.addInputClass(
new File(testJarLocation), new File(testJarLocation + "/" + klass + ".class"));
instrumenter.setPassUnmodifiedClasses(false);
instrumenter.setOutputJar(instrumentedJarLocation.toFile());
instrumenter.beginTraversal();
// To be able to reuse all classes from shrike save them in a list
classInstrumenters = new ArrayList<>();
ClassInstrumenter ci = null;
while ((ci = instrumenter.nextClass()) != null) {
classInstrumenters.add(ci);
}
}
@Test
public void testDouble() throws IOException, InvalidClassFileException {
double amountToAdd = 2.5d;
// Find the method data in which patches should be applied
String signature = "L" + klass + ";.doubble()V";
MethodData methodData = getMethodData(signature);
// Find the first ConstantInstruction of type double (D)
IInstruction[] instructions = methodData.getInstructions();
Integer index = getFirstConstantInstructionIndex(instructions, Constants.TYPE_double);
// Since such an instruction was found, read the original value and add some
// specified amount
ConstantInstruction constantDoubleInstruction = (ConstantInstruction) instructions[index];
double value = (double) constantDoubleInstruction.getValue();
double newValue = value + amountToAdd;
// Replace the original constant instruction with another which pushes the
// new value (from above)
MethodEditor me = new MethodEditor(methodData);
me.beginPass();
me.replaceWith(
index,
new MethodEditor.Patch() {
@Override
public void emitTo(Output w) {
w.emit(ConstantInstruction.make(newValue));
}
});
me.applyPatches();
me.endPass();
// Write the altered bytecode to jar file
write();
// Read the saved application from shrike again and verify that the
// altered constant instruction has the new value
double readValue =
(double) getConstantInstructionValue(signature, index, Constants.TYPE_double);
// And finally (and most important) compare the value
Assert.assertEquals(newValue, readValue, 0d);
}
@Test
public void testFloat() throws IOException, InvalidClassFileException {
float amountToAdd = 2.5f;
// Find the method data in which patches should be applied
String signature = "L" + klass + ";.floatt()V";
MethodData methodData = getMethodData(signature);
// Find the first ConstantInstruction of type float (F)
IInstruction[] instructions = methodData.getInstructions();
Integer index = getFirstConstantInstructionIndex(instructions, Constants.TYPE_float);
// Since such an instruction was found, read the original value and add some
// specified amount
ConstantInstruction constantDoubleInstruction = (ConstantInstruction) instructions[index];
float value = (float) constantDoubleInstruction.getValue();
float newValue = value + amountToAdd;
// Replace the original constant instruction with another which pushes the
// new value (from above)
MethodEditor me = new MethodEditor(methodData);
me.beginPass();
me.replaceWith(
index,
new MethodEditor.Patch() {
@Override
public void emitTo(Output w) {
w.emit(ConstantInstruction.make(newValue));
}
});
me.applyPatches();
me.endPass();
// Write the altered bytecode to jar file
write();
// Read the saved application from shrike again and verify that the
// altered constant instruction has the new value
float readValue = (float) getConstantInstructionValue(signature, index, Constants.TYPE_float);
// And finally (and most important) compare the value
Assert.assertEquals(newValue, readValue, 0d);
}
private void write() throws IllegalStateException, IOException, InvalidClassFileException {
// Write all modified classes
for (ClassInstrumenter ci2 : classInstrumenters) {
if (ci2.isChanged()) {
ClassWriter cw = ci2.emitClass();
instrumenter.outputModifiedClass(ci2, cw);
}
}
// Finally write the instrumented jar
instrumenter.close();
}
private void setValidationInstrumenter() throws IOException {
// Reuse the instrumenter variable to just read the previously instrumented
// file.
instrumenter = new OfflineInstrumenter();
instrumenter.addInputJar(instrumentedJarLocation.toFile());
instrumenter.beginTraversal();
// To be able to reuse all classes from shrike save them in a new list
classInstrumenters = new ArrayList<>();
ClassInstrumenter ci = null;
while ((ci = instrumenter.nextClass()) != null) {
classInstrumenters.add(ci);
}
}
private Object getConstantInstructionValue(String signature, int index, String type)
throws IllegalStateException, IOException, InvalidClassFileException {
setValidationInstrumenter();
// Find the method data which contains the altered method body
MethodData methodData = getMethodData(signature);
// Find the ConstantInstruction given by index. This one should be validated
// to hold the new value
IInstruction[] instructions = methodData.getInstructions();
IInstruction instruction = instructions[index];
// Check that the instruction type has not been changed
Assert.assertTrue(instruction instanceof ConstantInstruction);
// The type type should be the same as well
ConstantInstruction instruction2 = (ConstantInstruction) instruction;
Assert.assertTrue(type.contentEquals(instruction2.getType()));
return instruction2.getValue();
}
private Integer getFirstConstantInstructionIndex(IInstruction[] instructions, String type) {
// Iterate all instructions to find the first which is a ConstantInstruction
// and has the correct type
for (int index = 0; index < instructions.length; index++) {
IInstruction instruction = instructions[index];
System.out.println(instruction);
if (instruction instanceof ConstantInstruction) {
ConstantInstruction constantInstruction = (ConstantInstruction) instruction;
if (constantInstruction.getType().contentEquals(type)) {
return index;
}
}
}
Assert.fail("No ConstantInstruction with type '" + type + "' found");
return null;
}
private MethodData getMethodData(String signature) throws InvalidClassFileException {
// Look up loaded methods and compare them by signature
for (ClassInstrumenter ci : classInstrumenters) {
ClassReader cr = ci.getReader();
for (int m = 0; m < cr.getMethodCount(); m++) {
MethodData md = ci.visitMethod(m);
// TODO .toString() on MethodData might not be safe in the future to
// generate a valid jvm signature. Build up the signature from fields
// in MethodData and compare it afterwards.
if (signature.contentEquals(md.toString())) {
return md;
}
}
}
Assert.fail("Method data not found. Check the signature");
return null;
}
}
| 9,017
| 36.575
| 98
|
java
|
WALA
|
WALA-master/core/src/test/java/com/ibm/wala/core/tests/slicer/SlicerTest.java
|
/*
* Copyright (c) 2006 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.core.tests.slicer;
import com.ibm.wala.classLoader.Language;
import com.ibm.wala.core.tests.callGraph.CallGraphTestUtil;
import com.ibm.wala.core.tests.util.TestConstants;
import com.ibm.wala.core.util.config.AnalysisScopeReader;
import com.ibm.wala.core.util.io.FileProvider;
import com.ibm.wala.core.util.strings.Atom;
import com.ibm.wala.examples.drivers.PDFSlice;
import com.ibm.wala.ipa.callgraph.AnalysisCacheImpl;
import com.ibm.wala.ipa.callgraph.AnalysisOptions;
import com.ibm.wala.ipa.callgraph.AnalysisScope;
import com.ibm.wala.ipa.callgraph.CGNode;
import com.ibm.wala.ipa.callgraph.CallGraph;
import com.ibm.wala.ipa.callgraph.CallGraphBuilder;
import com.ibm.wala.ipa.callgraph.ContextSelector;
import com.ibm.wala.ipa.callgraph.Entrypoint;
import com.ibm.wala.ipa.callgraph.IAnalysisCacheView;
import com.ibm.wala.ipa.callgraph.impl.PartialCallGraph;
import com.ibm.wala.ipa.callgraph.impl.Util;
import com.ibm.wala.ipa.callgraph.propagation.InstanceFieldKey;
import com.ibm.wala.ipa.callgraph.propagation.InstanceKey;
import com.ibm.wala.ipa.callgraph.propagation.PointerAnalysis;
import com.ibm.wala.ipa.callgraph.propagation.PointerKey;
import com.ibm.wala.ipa.callgraph.propagation.SSAContextInterpreter;
import com.ibm.wala.ipa.callgraph.propagation.SSAPropagationCallGraphBuilder;
import com.ibm.wala.ipa.callgraph.propagation.cfa.ZeroXInstanceKeys;
import com.ibm.wala.ipa.callgraph.propagation.cfa.nCFABuilder;
import com.ibm.wala.ipa.callgraph.util.CallGraphSearchUtil;
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.ipa.slicer.HeapStatement.HeapReturnCaller;
import com.ibm.wala.ipa.slicer.MethodEntryStatement;
import com.ibm.wala.ipa.slicer.NormalReturnCaller;
import com.ibm.wala.ipa.slicer.NormalStatement;
import com.ibm.wala.ipa.slicer.SDG;
import com.ibm.wala.ipa.slicer.Slicer;
import com.ibm.wala.ipa.slicer.Slicer.ControlDependenceOptions;
import com.ibm.wala.ipa.slicer.Slicer.DataDependenceOptions;
import com.ibm.wala.ipa.slicer.SlicerUtil;
import com.ibm.wala.ipa.slicer.Statement;
import com.ibm.wala.ipa.slicer.thin.ThinSlicer;
import com.ibm.wala.types.ClassLoaderReference;
import com.ibm.wala.types.Descriptor;
import com.ibm.wala.util.CancelException;
import com.ibm.wala.util.config.FileOfClasses;
import com.ibm.wala.util.graph.GraphIntegrity;
import com.ibm.wala.util.graph.GraphIntegrity.UnsoundGraphException;
import com.ibm.wala.util.io.FileUtil;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.Test;
public class SlicerTest {
private static AnalysisScope cachedScope;
private static String makeSlicerExclusions() {
try {
try (InputStream is =
new FileProvider()
.getInputStreamFromClassLoader(
CallGraphTestUtil.REGRESSION_EXCLUSIONS, SlicerTest.class.getClassLoader())) {
String exclusions = new String(FileUtil.readBytes(is), "UTF-8");
// we also need to exclude java.security to avoid blowup during slicing
return exclusions + "java\\/security\\/.*\n";
}
} catch (IOException e) {
throw new RuntimeException(e);
}
}
private static AnalysisScope findOrCreateAnalysisScope() throws IOException {
if (cachedScope == null) {
cachedScope =
AnalysisScopeReader.instance.readJavaScope(
TestConstants.WALA_TESTDATA, null, SlicerTest.class.getClassLoader());
cachedScope.setExclusions(
new FileOfClasses(new ByteArrayInputStream(makeSlicerExclusions().getBytes("UTF-8"))));
}
return cachedScope;
}
private static IClassHierarchy cachedCHA;
private static IClassHierarchy findOrCreateCHA(AnalysisScope scope)
throws ClassHierarchyException {
if (cachedCHA == null) {
cachedCHA = ClassHierarchyFactory.make(scope);
}
return cachedCHA;
}
@AfterClass
public static void afterClass() {
cachedCHA = null;
cachedScope = null;
}
public static Statement findCallToDoNothing(CGNode n) {
return SlicerUtil.findCallTo(n, "doNothing");
}
@Test
public void testSlice1()
throws ClassHierarchyException, IllegalArgumentException, CancelException, IOException {
AnalysisScope scope = findOrCreateAnalysisScope();
IClassHierarchy cha = findOrCreateCHA(scope);
Iterable<Entrypoint> entrypoints =
com.ibm.wala.ipa.callgraph.impl.Util.makeMainEntrypoints(cha, TestConstants.SLICE1_MAIN);
AnalysisOptions options = CallGraphTestUtil.makeAnalysisOptions(scope, entrypoints);
CallGraphBuilder<InstanceKey> builder =
Util.makeZeroOneCFABuilder(Language.JAVA, options, new AnalysisCacheImpl(), cha);
CallGraph cg = builder.makeCallGraph(options, null);
CGNode main = CallGraphSearchUtil.findMainMethod(cg);
Statement s = SlicerUtil.findCallTo(main, "println");
System.err.println("Statement: " + s);
// compute a data slice
final PointerAnalysis<InstanceKey> pointerAnalysis = builder.getPointerAnalysis();
Collection<Statement> computeBackwardSlice =
Slicer.computeBackwardSlice(
s, cg, pointerAnalysis, DataDependenceOptions.FULL, ControlDependenceOptions.NONE);
Collection<Statement> slice = computeBackwardSlice;
SlicerUtil.dumpSlice(slice);
int i = 0;
for (Statement st : slice) {
if (st.getNode()
.getMethod()
.getDeclaringClass()
.getClassLoader()
.getReference()
.equals(ClassLoaderReference.Application)) {
i++;
}
}
Assert.assertEquals(16, i);
}
@Test
public void testSlice2()
throws ClassHierarchyException, IllegalArgumentException, CancelException, IOException {
AnalysisScope scope = findOrCreateAnalysisScope();
IClassHierarchy cha = findOrCreateCHA(scope);
Iterable<Entrypoint> entrypoints =
com.ibm.wala.ipa.callgraph.impl.Util.makeMainEntrypoints(cha, TestConstants.SLICE2_MAIN);
AnalysisOptions options = CallGraphTestUtil.makeAnalysisOptions(scope, entrypoints);
CallGraphBuilder<InstanceKey> builder =
Util.makeZeroOneCFABuilder(Language.JAVA, options, new AnalysisCacheImpl(), cha);
CallGraph cg = builder.makeCallGraph(options, null);
CGNode main = CallGraphSearchUtil.findMethod(cg, "baz");
Statement s = SlicerUtil.findCallTo(main, "println");
System.err.println("Statement: " + s);
// compute a data slice
final PointerAnalysis<InstanceKey> pointerAnalysis = builder.getPointerAnalysis();
Collection<Statement> computeBackwardSlice =
Slicer.computeBackwardSlice(
s, cg, pointerAnalysis, DataDependenceOptions.FULL, ControlDependenceOptions.NONE);
Collection<Statement> slice = computeBackwardSlice;
SlicerUtil.dumpSlice(slice);
Assert.assertEquals(slice.toString(), 9, SlicerUtil.countNormals(slice));
}
@Test
public void testSlice3()
throws ClassHierarchyException, IllegalArgumentException, CancelException, IOException {
AnalysisScope scope = findOrCreateAnalysisScope();
IClassHierarchy cha = findOrCreateCHA(scope);
Iterable<Entrypoint> entrypoints =
com.ibm.wala.ipa.callgraph.impl.Util.makeMainEntrypoints(cha, TestConstants.SLICE3_MAIN);
AnalysisOptions options = CallGraphTestUtil.makeAnalysisOptions(scope, entrypoints);
CallGraphBuilder<InstanceKey> builder =
Util.makeZeroOneCFABuilder(Language.JAVA, options, new AnalysisCacheImpl(), cha);
CallGraph cg = builder.makeCallGraph(options, null);
CGNode main = CallGraphSearchUtil.findMethod(cg, "main");
Statement s = SlicerUtil.findCallTo(main, "doNothing");
System.err.println("Statement: " + s);
// compute a data slice
final PointerAnalysis<InstanceKey> pointerAnalysis = builder.getPointerAnalysis();
Collection<Statement> slice =
Slicer.computeBackwardSlice(
s, cg, pointerAnalysis, DataDependenceOptions.FULL, ControlDependenceOptions.NONE);
SlicerUtil.dumpSlice(slice);
Assert.assertEquals(slice.toString(), 1, SlicerUtil.countAllocations(slice, false));
}
@Test
public void testSlice4()
throws ClassHierarchyException, IllegalArgumentException, CancelException, IOException {
AnalysisScope scope = findOrCreateAnalysisScope();
IClassHierarchy cha = findOrCreateCHA(scope);
Iterable<Entrypoint> entrypoints =
com.ibm.wala.ipa.callgraph.impl.Util.makeMainEntrypoints(cha, TestConstants.SLICE4_MAIN);
AnalysisOptions options = CallGraphTestUtil.makeAnalysisOptions(scope, entrypoints);
CallGraphBuilder<InstanceKey> builder =
Util.makeZeroOneCFABuilder(Language.JAVA, options, new AnalysisCacheImpl(), cha);
CallGraph cg = builder.makeCallGraph(options, null);
CGNode main = CallGraphSearchUtil.findMainMethod(cg);
Statement s = SlicerUtil.findCallTo(main, "foo");
s = PDFSlice.getReturnStatementForCall(s);
System.err.println("Statement: " + s);
// compute a data slice
final PointerAnalysis<InstanceKey> pointerAnalysis = builder.getPointerAnalysis();
Collection<Statement> slice =
Slicer.computeForwardSlice(
s, cg, pointerAnalysis, DataDependenceOptions.FULL, ControlDependenceOptions.NONE);
SlicerUtil.dumpSlice(slice);
Assert.assertEquals(slice.toString(), 4, slice.size());
}
@Test
public void testSlice5()
throws ClassHierarchyException, IllegalArgumentException, CancelException, IOException {
AnalysisScope scope = findOrCreateAnalysisScope();
IClassHierarchy cha = findOrCreateCHA(scope);
Iterable<Entrypoint> entrypoints =
com.ibm.wala.ipa.callgraph.impl.Util.makeMainEntrypoints(cha, TestConstants.SLICE5_MAIN);
AnalysisOptions options = CallGraphTestUtil.makeAnalysisOptions(scope, entrypoints);
CallGraphBuilder<InstanceKey> builder =
Util.makeZeroOneCFABuilder(Language.JAVA, options, new AnalysisCacheImpl(), cha);
CallGraph cg = builder.makeCallGraph(options, null);
CGNode n = CallGraphSearchUtil.findMethod(cg, "baz");
Statement s = SlicerUtil.findCallTo(n, "foo");
s = PDFSlice.getReturnStatementForCall(s);
System.err.println("Statement: " + s);
// compute a data slice
final PointerAnalysis<InstanceKey> pointerAnalysis = builder.getPointerAnalysis();
Collection<Statement> slice =
Slicer.computeForwardSlice(
s, cg, pointerAnalysis, DataDependenceOptions.FULL, ControlDependenceOptions.NONE);
SlicerUtil.dumpSlice(slice);
Assert.assertEquals(slice.toString(), 7, slice.size());
}
/** test unreproduced bug reported on mailing list by Sameer Madan, 7/3/2007 */
@Test
public void testSlice7()
throws ClassHierarchyException, IllegalArgumentException, CancelException, IOException {
AnalysisScope scope = findOrCreateAnalysisScope();
IClassHierarchy cha = findOrCreateCHA(scope);
Iterable<Entrypoint> entrypoints =
com.ibm.wala.ipa.callgraph.impl.Util.makeMainEntrypoints(cha, TestConstants.SLICE7_MAIN);
AnalysisOptions options = CallGraphTestUtil.makeAnalysisOptions(scope, entrypoints);
CallGraphBuilder<InstanceKey> builder =
Util.makeZeroOneContainerCFABuilder(options, new AnalysisCacheImpl(), cha);
CallGraph cg = builder.makeCallGraph(options, null);
CGNode main = CallGraphSearchUtil.findMainMethod(cg);
Statement s = SlicerUtil.findFirstAllocation(main);
System.err.println("Statement: " + s);
// compute a data slice
final PointerAnalysis<InstanceKey> pointerAnalysis = builder.getPointerAnalysis();
Collection<Statement> slice =
Slicer.computeForwardSlice(
s, cg, pointerAnalysis, DataDependenceOptions.FULL, ControlDependenceOptions.NONE);
SlicerUtil.dumpSlice(slice);
}
/** test bug reported on mailing list by Ravi Chandhran, 4/16/2010 */
@Test
public void testSlice8()
throws ClassHierarchyException, IllegalArgumentException, CancelException, IOException {
AnalysisScope scope = findOrCreateAnalysisScope();
IClassHierarchy cha = findOrCreateCHA(scope);
Iterable<Entrypoint> entrypoints =
com.ibm.wala.ipa.callgraph.impl.Util.makeMainEntrypoints(cha, TestConstants.SLICE8_MAIN);
AnalysisOptions options = CallGraphTestUtil.makeAnalysisOptions(scope, entrypoints);
CallGraphBuilder<InstanceKey> builder =
Util.makeZeroOneCFABuilder(Language.JAVA, options, new AnalysisCacheImpl(), cha);
CallGraph cg = builder.makeCallGraph(options, null);
CGNode process =
CallGraphSearchUtil.findMethod(
cg, Descriptor.findOrCreateUTF8("()V"), Atom.findOrCreateUnicodeAtom("process"));
Statement s = findCallToDoNothing(process);
System.err.println("Statement: " + s);
// compute a backward slice, with data dependence and no exceptional control dependence
final PointerAnalysis<InstanceKey> pointerAnalysis = builder.getPointerAnalysis();
Collection<Statement> slice =
Slicer.computeBackwardSlice(
s,
cg,
pointerAnalysis,
DataDependenceOptions.FULL,
ControlDependenceOptions.NO_EXCEPTIONAL_EDGES);
SlicerUtil.dumpSlice(slice);
Assert.assertEquals(4, SlicerUtil.countInvokes(slice));
// should only get 4 statements total when ignoring control dependences completely
slice =
Slicer.computeBackwardSlice(
s, cg, pointerAnalysis, DataDependenceOptions.FULL, ControlDependenceOptions.NONE);
Assert.assertEquals(slice.toString(), 4, slice.size());
}
@Test
public void testSlice9()
throws ClassHierarchyException, IllegalArgumentException, CancelException, IOException {
AnalysisScope scope = findOrCreateAnalysisScope();
IClassHierarchy cha = findOrCreateCHA(scope);
Iterable<Entrypoint> entrypoints =
com.ibm.wala.ipa.callgraph.impl.Util.makeMainEntrypoints(cha, TestConstants.SLICE9_MAIN);
AnalysisOptions options = CallGraphTestUtil.makeAnalysisOptions(scope, entrypoints);
CallGraphBuilder<InstanceKey> builder =
Util.makeZeroOneCFABuilder(Language.JAVA, options, new AnalysisCacheImpl(), cha);
CallGraph cg = builder.makeCallGraph(options, null);
CGNode main = CallGraphSearchUtil.findMainMethod(cg);
Statement s = findCallToDoNothing(main);
System.err.println("Statement: " + s);
// compute a backward slice, with data dependence and no exceptional control dependence
final PointerAnalysis<InstanceKey> pointerAnalysis = builder.getPointerAnalysis();
Collection<Statement> slice =
Slicer.computeBackwardSlice(
s,
cg,
pointerAnalysis,
DataDependenceOptions.FULL,
ControlDependenceOptions.NO_EXCEPTIONAL_EDGES);
// dumpSlice(slice);
Assert.assertEquals(/*slice.toString(), */ 5, SlicerUtil.countApplicationNormals(slice));
}
@Test
public void testTestCD1()
throws ClassHierarchyException, IllegalArgumentException, CancelException, IOException {
AnalysisScope scope = findOrCreateAnalysisScope();
IClassHierarchy cha = findOrCreateCHA(scope);
Iterable<Entrypoint> entrypoints =
com.ibm.wala.ipa.callgraph.impl.Util.makeMainEntrypoints(cha, TestConstants.SLICE_TESTCD1);
AnalysisOptions options = CallGraphTestUtil.makeAnalysisOptions(scope, entrypoints);
CallGraphBuilder<InstanceKey> builder =
Util.makeZeroOneCFABuilder(Language.JAVA, options, new AnalysisCacheImpl(), cha);
CallGraph cg = builder.makeCallGraph(options, null);
CGNode main = CallGraphSearchUtil.findMainMethod(cg);
Statement s = findCallToDoNothing(main);
System.err.println("Statement: " + s);
// compute a data slice
final PointerAnalysis<InstanceKey> pointerAnalysis = builder.getPointerAnalysis();
Collection<Statement> slice =
Slicer.computeBackwardSlice(
s, cg, pointerAnalysis, DataDependenceOptions.NONE, ControlDependenceOptions.FULL);
SlicerUtil.dumpSlice(slice);
Assert.assertEquals(slice.toString(), 2, SlicerUtil.countConditionals(slice));
}
@Test
public void testTestCD2()
throws ClassHierarchyException, IllegalArgumentException, CancelException, IOException {
AnalysisScope scope = findOrCreateAnalysisScope();
IClassHierarchy cha = findOrCreateCHA(scope);
Iterable<Entrypoint> entrypoints =
com.ibm.wala.ipa.callgraph.impl.Util.makeMainEntrypoints(cha, TestConstants.SLICE_TESTCD2);
AnalysisOptions options = CallGraphTestUtil.makeAnalysisOptions(scope, entrypoints);
CallGraphBuilder<InstanceKey> builder =
Util.makeZeroOneCFABuilder(Language.JAVA, options, new AnalysisCacheImpl(), cha);
CallGraph cg = builder.makeCallGraph(options, null);
CGNode main = CallGraphSearchUtil.findMainMethod(cg);
Statement s = findCallToDoNothing(main);
System.err.println("Statement: " + s);
// compute a data slice
final PointerAnalysis<InstanceKey> pointerAnalysis = builder.getPointerAnalysis();
Collection<Statement> slice =
Slicer.computeBackwardSlice(
s, cg, pointerAnalysis, DataDependenceOptions.NONE, ControlDependenceOptions.FULL);
SlicerUtil.dumpSlice(slice);
Assert.assertEquals(slice.toString(), 1, SlicerUtil.countConditionals(slice));
}
@Test
public void testTestCD3()
throws ClassHierarchyException, IllegalArgumentException, CancelException, IOException {
AnalysisScope scope = findOrCreateAnalysisScope();
IClassHierarchy cha = findOrCreateCHA(scope);
Iterable<Entrypoint> entrypoints =
com.ibm.wala.ipa.callgraph.impl.Util.makeMainEntrypoints(cha, TestConstants.SLICE_TESTCD3);
AnalysisOptions options = CallGraphTestUtil.makeAnalysisOptions(scope, entrypoints);
CallGraphBuilder<InstanceKey> builder =
Util.makeZeroOneCFABuilder(Language.JAVA, options, new AnalysisCacheImpl(), cha);
CallGraph cg = builder.makeCallGraph(options, null);
CGNode main = CallGraphSearchUtil.findMainMethod(cg);
Statement s = findCallToDoNothing(main);
System.err.println("Statement: " + s);
// compute a data slice
final PointerAnalysis<InstanceKey> pointerAnalysis = builder.getPointerAnalysis();
Collection<Statement> slice =
Slicer.computeBackwardSlice(
s, cg, pointerAnalysis, DataDependenceOptions.NONE, ControlDependenceOptions.FULL);
SlicerUtil.dumpSlice(slice);
Assert.assertEquals(slice.toString(), 0, SlicerUtil.countConditionals(slice));
}
@Test
public void testTestCD4()
throws ClassHierarchyException, IllegalArgumentException, CancelException, IOException {
AnalysisScope scope = findOrCreateAnalysisScope();
IClassHierarchy cha = findOrCreateCHA(scope);
Iterable<Entrypoint> entrypoints =
com.ibm.wala.ipa.callgraph.impl.Util.makeMainEntrypoints(cha, TestConstants.SLICE_TESTCD4);
AnalysisOptions options = CallGraphTestUtil.makeAnalysisOptions(scope, entrypoints);
CallGraphBuilder<InstanceKey> builder =
Util.makeZeroOneCFABuilder(Language.JAVA, options, new AnalysisCacheImpl(), cha);
CallGraph cg = builder.makeCallGraph(options, null);
CGNode main = CallGraphSearchUtil.findMainMethod(cg);
Statement s = findCallToDoNothing(main);
System.err.println("Statement: " + s);
// compute a no-data slice
final PointerAnalysis<InstanceKey> pointerAnalysis = builder.getPointerAnalysis();
Collection<Statement> slice =
Slicer.computeBackwardSlice(
s, cg, pointerAnalysis, DataDependenceOptions.NONE, ControlDependenceOptions.FULL);
SlicerUtil.dumpSlice(slice);
Assert.assertEquals(0, SlicerUtil.countConditionals(slice));
// compute a full slice
slice =
Slicer.computeBackwardSlice(
s, cg, pointerAnalysis, DataDependenceOptions.FULL, ControlDependenceOptions.FULL);
SlicerUtil.dumpSlice(slice);
Assert.assertEquals(slice.toString(), 1, SlicerUtil.countConditionals(slice));
}
@Test
public void testTestCD5()
throws ClassHierarchyException, IllegalArgumentException, CancelException, IOException {
AnalysisScope scope = findOrCreateAnalysisScope();
IClassHierarchy cha = findOrCreateCHA(scope);
Iterable<Entrypoint> entrypoints =
com.ibm.wala.ipa.callgraph.impl.Util.makeMainEntrypoints(cha, TestConstants.SLICE_TESTCD5);
AnalysisOptions options = CallGraphTestUtil.makeAnalysisOptions(scope, entrypoints);
CallGraphBuilder<InstanceKey> builder =
Util.makeZeroOneCFABuilder(Language.JAVA, options, new AnalysisCacheImpl(), cha);
CallGraph cg = builder.makeCallGraph(options, null);
CGNode main = CallGraphSearchUtil.findMainMethod(cg);
Statement s = new MethodEntryStatement(main);
System.err.println("Statement: " + s);
// compute a no-data slice
final PointerAnalysis<InstanceKey> pointerAnalysis = builder.getPointerAnalysis();
Collection<Statement> slice =
Slicer.computeForwardSlice(
s,
cg,
pointerAnalysis,
DataDependenceOptions.NONE,
ControlDependenceOptions.NO_EXCEPTIONAL_EDGES);
SlicerUtil.dumpSlice(slice);
Assert.assertEquals(10, slice.size());
Assert.assertEquals(3, SlicerUtil.countReturns(slice));
}
@Test
public void testTestCD5NoInterproc()
throws ClassHierarchyException, IllegalArgumentException, CancelException, IOException {
AnalysisScope scope = findOrCreateAnalysisScope();
IClassHierarchy cha = findOrCreateCHA(scope);
Iterable<Entrypoint> entrypoints =
com.ibm.wala.ipa.callgraph.impl.Util.makeMainEntrypoints(cha, TestConstants.SLICE_TESTCD5);
AnalysisOptions options = CallGraphTestUtil.makeAnalysisOptions(scope, entrypoints);
CallGraphBuilder<InstanceKey> builder =
Util.makeZeroOneCFABuilder(Language.JAVA, options, new AnalysisCacheImpl(), cha);
CallGraph cg = builder.makeCallGraph(options, null);
CGNode main = CallGraphSearchUtil.findMainMethod(cg);
Statement s = new MethodEntryStatement(main);
System.err.println("Statement: " + s);
// compute a no-data slice
final PointerAnalysis<InstanceKey> pointerAnalysis = builder.getPointerAnalysis();
Collection<Statement> slice =
Slicer.computeForwardSlice(
s,
cg,
pointerAnalysis,
DataDependenceOptions.NONE,
ControlDependenceOptions.NO_INTERPROC_NO_EXCEPTION);
SlicerUtil.dumpSlice(slice);
Assert.assertEquals(8, slice.size());
Assert.assertEquals(2, SlicerUtil.countReturns(slice));
}
@Test
public void testTestCD6()
throws ClassHierarchyException, IllegalArgumentException, CancelException, IOException {
AnalysisScope scope = findOrCreateAnalysisScope();
IClassHierarchy cha = findOrCreateCHA(scope);
Iterable<Entrypoint> entrypoints =
com.ibm.wala.ipa.callgraph.impl.Util.makeMainEntrypoints(cha, TestConstants.SLICE_TESTCD6);
AnalysisOptions options = CallGraphTestUtil.makeAnalysisOptions(scope, entrypoints);
CallGraphBuilder<InstanceKey> builder =
Util.makeZeroOneCFABuilder(Language.JAVA, options, new AnalysisCacheImpl(), cha);
CallGraph cg = builder.makeCallGraph(options, null);
CGNode main = CallGraphSearchUtil.findMainMethod(cg);
Statement s = new MethodEntryStatement(main);
System.err.println("Statement: " + s);
// compute a no-data slice
final PointerAnalysis<InstanceKey> pointerAnalysis = builder.getPointerAnalysis();
Collection<Statement> slice =
Slicer.computeForwardSlice(
s,
cg,
pointerAnalysis,
DataDependenceOptions.NONE,
ControlDependenceOptions.NO_EXCEPTIONAL_EDGES);
SlicerUtil.dumpSlice(slice);
Assert.assertEquals(slice.toString(), 2, SlicerUtil.countInvokes(slice));
}
@Test
public void testTestId()
throws ClassHierarchyException, IllegalArgumentException, CancelException, IOException {
AnalysisScope scope = findOrCreateAnalysisScope();
IClassHierarchy cha = findOrCreateCHA(scope);
Iterable<Entrypoint> entrypoints =
com.ibm.wala.ipa.callgraph.impl.Util.makeMainEntrypoints(cha, TestConstants.SLICE_TESTID);
AnalysisOptions options = CallGraphTestUtil.makeAnalysisOptions(scope, entrypoints);
CallGraphBuilder<InstanceKey> builder =
Util.makeZeroOneCFABuilder(Language.JAVA, options, new AnalysisCacheImpl(), cha);
CallGraph cg = builder.makeCallGraph(options, null);
CGNode main = CallGraphSearchUtil.findMainMethod(cg);
Statement s = findCallToDoNothing(main);
System.err.println("Statement: " + s);
// compute a data slice
final PointerAnalysis<InstanceKey> pointerAnalysis = builder.getPointerAnalysis();
Collection<Statement> slice =
Slicer.computeBackwardSlice(
s, cg, pointerAnalysis, DataDependenceOptions.FULL, ControlDependenceOptions.NONE);
SlicerUtil.dumpSlice(slice);
Assert.assertEquals(slice.toString(), 1, SlicerUtil.countAllocations(slice, false));
}
@Test
public void testTestArrays()
throws ClassHierarchyException, IllegalArgumentException, CancelException, IOException {
AnalysisScope scope = findOrCreateAnalysisScope();
IClassHierarchy cha = findOrCreateCHA(scope);
Iterable<Entrypoint> entrypoints =
com.ibm.wala.ipa.callgraph.impl.Util.makeMainEntrypoints(
cha, TestConstants.SLICE_TESTARRAYS);
AnalysisOptions options = CallGraphTestUtil.makeAnalysisOptions(scope, entrypoints);
CallGraphBuilder<InstanceKey> builder =
Util.makeZeroOneCFABuilder(Language.JAVA, options, new AnalysisCacheImpl(), cha);
CallGraph cg = builder.makeCallGraph(options, null);
CGNode main = CallGraphSearchUtil.findMainMethod(cg);
Statement s = findCallToDoNothing(main);
System.err.println("Statement: " + s);
// compute a data slice
final PointerAnalysis<InstanceKey> pointerAnalysis = builder.getPointerAnalysis();
Collection<Statement> slice =
Slicer.computeBackwardSlice(
s, cg, pointerAnalysis, DataDependenceOptions.FULL, ControlDependenceOptions.NONE);
SlicerUtil.dumpSlice(slice);
Assert.assertEquals(slice.toString(), 2, SlicerUtil.countAllocations(slice, false));
Assert.assertEquals(slice.toString(), 1, SlicerUtil.countAloads(slice));
}
@Test
public void testTestFields()
throws ClassHierarchyException, IllegalArgumentException, CancelException, IOException {
AnalysisScope scope = findOrCreateAnalysisScope();
IClassHierarchy cha = findOrCreateCHA(scope);
Iterable<Entrypoint> entrypoints =
com.ibm.wala.ipa.callgraph.impl.Util.makeMainEntrypoints(
cha, TestConstants.SLICE_TESTFIELDS);
AnalysisOptions options = CallGraphTestUtil.makeAnalysisOptions(scope, entrypoints);
CallGraphBuilder<InstanceKey> builder =
Util.makeZeroOneCFABuilder(Language.JAVA, options, new AnalysisCacheImpl(), cha);
CallGraph cg = builder.makeCallGraph(options, null);
CGNode main = CallGraphSearchUtil.findMainMethod(cg);
Statement s = findCallToDoNothing(main);
System.err.println("Statement: " + s);
// compute a data slice
final PointerAnalysis<InstanceKey> pointerAnalysis = builder.getPointerAnalysis();
Collection<Statement> slice =
Slicer.computeBackwardSlice(
s, cg, pointerAnalysis, DataDependenceOptions.FULL, ControlDependenceOptions.NONE);
SlicerUtil.dumpSlice(slice);
Assert.assertEquals(slice.toString(), 2, SlicerUtil.countAllocations(slice, false));
Assert.assertEquals(slice.toString(), 1, SlicerUtil.countPutfields(slice));
}
@Test
public void testThin1()
throws ClassHierarchyException, IllegalArgumentException, CancelException, IOException {
AnalysisScope scope = findOrCreateAnalysisScope();
IClassHierarchy cha = findOrCreateCHA(scope);
Iterable<Entrypoint> entrypoints =
com.ibm.wala.ipa.callgraph.impl.Util.makeMainEntrypoints(
cha, TestConstants.SLICE_TESTTHIN1);
AnalysisOptions options = CallGraphTestUtil.makeAnalysisOptions(scope, entrypoints);
CallGraphBuilder<InstanceKey> builder =
Util.makeZeroOneCFABuilder(Language.JAVA, options, new AnalysisCacheImpl(), cha);
CallGraph cg = builder.makeCallGraph(options, null);
CGNode main = CallGraphSearchUtil.findMainMethod(cg);
Statement s = findCallToDoNothing(main);
System.err.println("Statement: " + s);
// compute normal data slice
// compute a data slice
final PointerAnalysis<InstanceKey> pointerAnalysis = builder.getPointerAnalysis();
Collection<Statement> slice =
Slicer.computeBackwardSlice(
s, cg, pointerAnalysis, DataDependenceOptions.FULL, ControlDependenceOptions.NONE);
SlicerUtil.dumpSlice(slice);
Assert.assertEquals(3, SlicerUtil.countAllocations(slice, false));
Assert.assertEquals(2, SlicerUtil.countPutfields(slice));
// compute thin slice .. ignore base pointers
Collection<Statement> computeBackwardSlice =
Slicer.computeBackwardSlice(
s,
cg,
pointerAnalysis,
DataDependenceOptions.NO_BASE_PTRS,
ControlDependenceOptions.NONE);
slice = computeBackwardSlice;
SlicerUtil.dumpSlice(slice);
Assert.assertEquals(slice.toString(), 2, SlicerUtil.countAllocations(slice, false));
Assert.assertEquals(slice.toString(), 1, SlicerUtil.countPutfields(slice));
}
@Test
public void testTestGlobal()
throws ClassHierarchyException, IllegalArgumentException, CancelException, IOException {
AnalysisScope scope = findOrCreateAnalysisScope();
IClassHierarchy cha = findOrCreateCHA(scope);
Iterable<Entrypoint> entrypoints =
com.ibm.wala.ipa.callgraph.impl.Util.makeMainEntrypoints(
cha, TestConstants.SLICE_TESTGLOBAL);
AnalysisOptions options = CallGraphTestUtil.makeAnalysisOptions(scope, entrypoints);
CallGraphBuilder<InstanceKey> builder =
Util.makeZeroOneCFABuilder(Language.JAVA, options, new AnalysisCacheImpl(), cha);
CallGraph cg = builder.makeCallGraph(options, null);
CGNode main = CallGraphSearchUtil.findMainMethod(cg);
Statement s = findCallToDoNothing(main);
System.err.println("Statement: " + s);
// compute a data slice
final PointerAnalysis<InstanceKey> pointerAnalysis = builder.getPointerAnalysis();
Collection<Statement> slice =
Slicer.computeBackwardSlice(
s, cg, pointerAnalysis, DataDependenceOptions.FULL, ControlDependenceOptions.NONE);
SlicerUtil.dumpSlice(slice);
Assert.assertEquals(slice.toString(), 1, SlicerUtil.countAllocations(slice, false));
Assert.assertEquals(slice.toString(), 2, SlicerUtil.countPutstatics(slice));
Assert.assertEquals(slice.toString(), 2, SlicerUtil.countGetstatics(slice));
}
@Test
public void testTestMultiTarget()
throws ClassHierarchyException, IllegalArgumentException, CancelException, IOException {
AnalysisScope scope = findOrCreateAnalysisScope();
IClassHierarchy cha = findOrCreateCHA(scope);
Iterable<Entrypoint> entrypoints =
com.ibm.wala.ipa.callgraph.impl.Util.makeMainEntrypoints(
cha, TestConstants.SLICE_TESTMULTITARGET);
AnalysisOptions options = CallGraphTestUtil.makeAnalysisOptions(scope, entrypoints);
CallGraphBuilder<InstanceKey> builder =
Util.makeZeroOneCFABuilder(Language.JAVA, options, new AnalysisCacheImpl(), cha);
CallGraph cg = builder.makeCallGraph(options, null);
CGNode main = CallGraphSearchUtil.findMainMethod(cg);
Statement s = findCallToDoNothing(main);
System.err.println("Statement: " + s);
// compute a data slice
final PointerAnalysis<InstanceKey> pointerAnalysis = builder.getPointerAnalysis();
Collection<Statement> slice =
Slicer.computeBackwardSlice(
s, cg, pointerAnalysis, DataDependenceOptions.FULL, ControlDependenceOptions.NONE);
SlicerUtil.dumpSlice(slice);
Assert.assertEquals(slice.toString(), 2, SlicerUtil.countAllocations(slice, false));
}
@Test
public void testTestRecursion()
throws ClassHierarchyException, IllegalArgumentException, CancelException, IOException {
AnalysisScope scope = findOrCreateAnalysisScope();
IClassHierarchy cha = findOrCreateCHA(scope);
Iterable<Entrypoint> entrypoints =
com.ibm.wala.ipa.callgraph.impl.Util.makeMainEntrypoints(
cha, TestConstants.SLICE_TESTRECURSION);
AnalysisOptions options = CallGraphTestUtil.makeAnalysisOptions(scope, entrypoints);
CallGraphBuilder<InstanceKey> builder =
Util.makeZeroOneCFABuilder(Language.JAVA, options, new AnalysisCacheImpl(), cha);
CallGraph cg = builder.makeCallGraph(options, null);
CGNode main = CallGraphSearchUtil.findMainMethod(cg);
Statement s = findCallToDoNothing(main);
System.err.println("Statement: " + s);
// compute a data slice
final PointerAnalysis<InstanceKey> pointerAnalysis = builder.getPointerAnalysis();
Collection<Statement> slice =
Slicer.computeBackwardSlice(
s, cg, pointerAnalysis, DataDependenceOptions.FULL, ControlDependenceOptions.NONE);
SlicerUtil.dumpSlice(slice);
Assert.assertEquals(slice.toString(), 3, SlicerUtil.countAllocations(slice, false));
Assert.assertEquals(slice.toString(), 2, SlicerUtil.countPutfields(slice));
}
@Test
public void testPrimGetterSetter()
throws ClassHierarchyException, IllegalArgumentException, CancelException, IOException {
AnalysisScope scope = findOrCreateAnalysisScope();
IClassHierarchy cha = findOrCreateCHA(scope);
Iterable<Entrypoint> entrypoints =
com.ibm.wala.ipa.callgraph.impl.Util.makeMainEntrypoints(
cha, TestConstants.SLICE_TEST_PRIM_GETTER_SETTER);
AnalysisOptions options = CallGraphTestUtil.makeAnalysisOptions(scope, entrypoints);
CallGraphBuilder<InstanceKey> builder =
Util.makeZeroOneCFABuilder(Language.JAVA, options, new AnalysisCacheImpl(), cha);
CallGraph cg = builder.makeCallGraph(options, null);
CGNode test = CallGraphSearchUtil.findMethod(cg, "test");
PartialCallGraph pcg = PartialCallGraph.make(cg, Collections.singleton(test));
Statement s = findCallToDoNothing(test);
System.err.println("Statement: " + s);
// compute full slice
final PointerAnalysis<InstanceKey> pointerAnalysis = builder.getPointerAnalysis();
Collection<Statement> slice =
Slicer.computeBackwardSlice(
s, pcg, pointerAnalysis, DataDependenceOptions.FULL, ControlDependenceOptions.FULL);
SlicerUtil.dumpSlice(slice);
Assert.assertEquals(slice.toString(), 0, SlicerUtil.countAllocations(slice, false));
Assert.assertEquals(slice.toString(), 1, SlicerUtil.countPutfields(slice));
}
/**
* Test of using N-CFA builder to distinguish receiver objects for two calls to a getter method.
* Also tests disabling SMUSH_PRIMITIVE_HOLDERS to ensure we get distinct abstract objects for two
* different primitive holders.
*/
@Test
public void testPrimGetterSetter2()
throws ClassHierarchyException, IllegalArgumentException, CancelException, IOException {
AnalysisScope scope = findOrCreateAnalysisScope();
IClassHierarchy cha = findOrCreateCHA(scope);
Iterable<Entrypoint> entrypoints =
com.ibm.wala.ipa.callgraph.impl.Util.makeMainEntrypoints(
cha, TestConstants.SLICE_TEST_PRIM_GETTER_SETTER2);
AnalysisOptions options = CallGraphTestUtil.makeAnalysisOptions(scope, entrypoints);
Util.addDefaultSelectors(options, cha);
Util.addDefaultBypassLogic(options, Util.class.getClassLoader(), cha);
ContextSelector appSelector = null;
SSAContextInterpreter appInterpreter = null;
IAnalysisCacheView cache = new AnalysisCacheImpl();
SSAPropagationCallGraphBuilder builder =
new nCFABuilder(
1,
Language.JAVA.getFakeRootMethod(cha, options, cache),
options,
cache,
appSelector,
appInterpreter);
// nCFABuilder uses type-based heap abstraction by default, but we want allocation sites
// NOTE: we disable ZeroXInstanceKeys.SMUSH_PRIMITIVE_HOLDERS for this test, since IntWrapper
// is a primitive holder
builder.setInstanceKeys(
new ZeroXInstanceKeys(
options,
cha,
builder.getContextInterpreter(),
ZeroXInstanceKeys.ALLOCATIONS
| ZeroXInstanceKeys.SMUSH_MANY /* | ZeroXInstanceKeys.SMUSH_PRIMITIVE_HOLDERS */
| ZeroXInstanceKeys.SMUSH_STRINGS
| ZeroXInstanceKeys.SMUSH_THROWABLES));
CallGraph cg = builder.makeCallGraph(options, null);
CGNode test = CallGraphSearchUtil.findMainMethod(cg);
PartialCallGraph pcg = PartialCallGraph.make(cg, Collections.singleton(test));
Statement s = findCallToDoNothing(test);
System.err.println("Statement: " + s);
final PointerAnalysis<InstanceKey> pointerAnalysis = builder.getPointerAnalysis();
Collection<Statement> slice =
Slicer.computeBackwardSlice(
s, pcg, pointerAnalysis, DataDependenceOptions.FULL, ControlDependenceOptions.NONE);
SlicerUtil.dumpSlice(slice);
Assert.assertEquals(slice.toString(), 1, SlicerUtil.countAllocations(slice, false));
Assert.assertEquals(slice.toString(), 1, SlicerUtil.countPutfields(slice));
}
@Test
public void testTestThrowCatch()
throws ClassHierarchyException, IllegalArgumentException, CancelException, IOException {
AnalysisScope scope = findOrCreateAnalysisScope();
IClassHierarchy cha = findOrCreateCHA(scope);
Iterable<Entrypoint> entrypoints =
com.ibm.wala.ipa.callgraph.impl.Util.makeMainEntrypoints(
cha, TestConstants.SLICE_TESTTHROWCATCH);
AnalysisOptions options = CallGraphTestUtil.makeAnalysisOptions(scope, entrypoints);
CallGraphBuilder<InstanceKey> builder =
Util.makeZeroOneCFABuilder(Language.JAVA, options, new AnalysisCacheImpl(), cha);
CallGraph cg = builder.makeCallGraph(options, null);
CGNode main = CallGraphSearchUtil.findMainMethod(cg);
Statement s = findCallToDoNothing(main);
System.err.println("Statement: " + s);
// compute a data slice
final PointerAnalysis<InstanceKey> pointerAnalysis = builder.getPointerAnalysis();
Collection<Statement> slice =
Slicer.computeBackwardSlice(
s, cg, pointerAnalysis, DataDependenceOptions.FULL, ControlDependenceOptions.NONE);
Assert.assertEquals("wrong number of allocations", 1, SlicerUtil.countAllocations(slice, true));
Assert.assertEquals("wrong number of throws", 1, SlicerUtil.countThrows(slice, true));
Assert.assertEquals("wrong number of getfields", 1, SlicerUtil.countGetfields(slice, true));
}
@Test
public void testTestMessageFormat()
throws ClassHierarchyException, IllegalArgumentException, CancelException, IOException {
AnalysisScope scope = findOrCreateAnalysisScope();
IClassHierarchy cha = findOrCreateCHA(scope);
Iterable<Entrypoint> entrypoints =
com.ibm.wala.ipa.callgraph.impl.Util.makeMainEntrypoints(
cha, TestConstants.SLICE_TESTMESSAGEFORMAT);
AnalysisOptions options = CallGraphTestUtil.makeAnalysisOptions(scope, entrypoints);
CallGraphBuilder<InstanceKey> builder =
Util.makeZeroCFABuilder(Language.JAVA, options, new AnalysisCacheImpl(), cha);
CallGraph cg = builder.makeCallGraph(options, null);
CGNode main = CallGraphSearchUtil.findMainMethod(cg);
Statement seed = new NormalStatement(main, 2);
System.err.println("Statement: " + seed);
// compute a backwards thin slice
ThinSlicer ts = new ThinSlicer(cg, builder.getPointerAnalysis());
Collection<Statement> slice = ts.computeBackwardThinSlice(seed);
SlicerUtil.dumpSlice(slice);
}
/** test for bug reported on mailing list by Joshua Garcia, 5/16/2010 */
@Test
public void testTestInetAddr()
throws ClassHierarchyException, IllegalArgumentException, CancelException, IOException,
UnsoundGraphException {
AnalysisScope scope = findOrCreateAnalysisScope();
IClassHierarchy cha = findOrCreateCHA(scope);
Iterable<Entrypoint> entrypoints =
com.ibm.wala.ipa.callgraph.impl.Util.makeMainEntrypoints(
cha, TestConstants.SLICE_TESTINETADDR);
AnalysisOptions options = CallGraphTestUtil.makeAnalysisOptions(scope, entrypoints);
CallGraphBuilder<InstanceKey> builder =
Util.makeZeroOneCFABuilder(Language.JAVA, options, new AnalysisCacheImpl(), cha);
CallGraph cg = builder.makeCallGraph(options, null);
SDG<?> sdg =
new SDG<>(
cg,
builder.getPointerAnalysis(),
DataDependenceOptions.NO_BASE_NO_HEAP,
ControlDependenceOptions.FULL);
GraphIntegrity.check(sdg);
}
@Test
public void testJustThrow()
throws ClassHierarchyException, IllegalArgumentException, CancelException, IOException {
AnalysisScope scope = findOrCreateAnalysisScope();
IClassHierarchy cha = findOrCreateCHA(scope);
Iterable<Entrypoint> entrypoints =
com.ibm.wala.ipa.callgraph.impl.Util.makeMainEntrypoints(
cha, TestConstants.SLICE_JUSTTHROW);
AnalysisOptions options = CallGraphTestUtil.makeAnalysisOptions(scope, entrypoints);
CallGraphBuilder<InstanceKey> builder =
Util.makeZeroOneCFABuilder(Language.JAVA, options, new AnalysisCacheImpl(), cha);
CallGraph cg = builder.makeCallGraph(options, null);
CGNode main = CallGraphSearchUtil.findMainMethod(cg);
Statement s = findCallToDoNothing(main);
System.err.println("Statement: " + s);
final PointerAnalysis<InstanceKey> pointerAnalysis = builder.getPointerAnalysis();
Collection<Statement> slice =
Slicer.computeBackwardSlice(
s,
cg,
pointerAnalysis,
DataDependenceOptions.FULL,
ControlDependenceOptions.NO_EXCEPTIONAL_EDGES);
SlicerUtil.dumpSlice(slice);
}
@Test
public void testList()
throws ClassHierarchyException, IllegalArgumentException, CancelException, IOException {
AnalysisScope scope = findOrCreateAnalysisScope();
IClassHierarchy cha = findOrCreateCHA(scope);
Iterable<Entrypoint> entrypoints =
com.ibm.wala.ipa.callgraph.impl.Util.makeMainEntrypoints(cha, "Lslice/TestList");
AnalysisOptions options = CallGraphTestUtil.makeAnalysisOptions(scope, entrypoints);
CallGraphBuilder<InstanceKey> builder =
Util.makeZeroOneContainerCFABuilder(options, new AnalysisCacheImpl(), cha);
CallGraph cg = builder.makeCallGraph(options, null);
CGNode main = CallGraphSearchUtil.findMainMethod(cg);
NormalStatement getCall = (NormalStatement) SlicerUtil.findCallTo(main, "get");
// we need a NormalReturnCaller statement to slice from the return value
NormalReturnCaller nrc = new NormalReturnCaller(main, getCall.getInstructionIndex());
final PointerAnalysis<InstanceKey> pointerAnalysis = builder.getPointerAnalysis();
Collection<Statement> slice =
Slicer.computeBackwardSlice(
nrc,
cg,
pointerAnalysis,
DataDependenceOptions.FULL,
ControlDependenceOptions.NO_EXCEPTIONAL_EDGES);
List<Statement> normalsInMain =
slice.stream()
.filter(s -> s instanceof NormalStatement && s.getNode().equals(main))
.collect(Collectors.toList());
normalsInMain.stream().forEach(System.err::println);
Assert.assertEquals(7, normalsInMain.size());
}
@Test
public void testListIterator()
throws ClassHierarchyException, IllegalArgumentException, CancelException, IOException {
AnalysisScope scope = findOrCreateAnalysisScope();
IClassHierarchy cha = findOrCreateCHA(scope);
Iterable<Entrypoint> entrypoints =
com.ibm.wala.ipa.callgraph.impl.Util.makeMainEntrypoints(cha, "Lslice/TestListIterator");
AnalysisOptions options = CallGraphTestUtil.makeAnalysisOptions(scope, entrypoints);
CallGraphBuilder<InstanceKey> builder =
Util.makeZeroOneContainerCFABuilder(options, new AnalysisCacheImpl(), cha);
CallGraph cg = builder.makeCallGraph(options, null);
CGNode main = CallGraphSearchUtil.findMainMethod(cg);
NormalStatement getCall = (NormalStatement) SlicerUtil.findCallTo(main, "hasNext");
// we need a NormalReturnCaller statement to slice from the return value
NormalReturnCaller nrc = new NormalReturnCaller(main, getCall.getInstructionIndex());
final PointerAnalysis<InstanceKey> pointerAnalysis = builder.getPointerAnalysis();
Collection<Statement> slice =
Slicer.computeBackwardSlice(
nrc,
cg,
pointerAnalysis,
DataDependenceOptions.FULL,
ControlDependenceOptions.NO_INTERPROC_NO_EXCEPTION);
List<Statement> inMain =
slice.stream().filter(s -> s.getNode().equals(main)).collect(Collectors.toList());
// check that we are tracking the size field in a HeapReturnCaller statement for the add() call
Assert.assertTrue(
"couldn't find HeapReturnCaller for size field",
inMain.stream()
.filter(
st -> {
if (st instanceof HeapReturnCaller) {
HeapReturnCaller hrc = (HeapReturnCaller) st;
if (hrc.getCall().getDeclaredTarget().getName().toString().equals("add")) {
PointerKey location = hrc.getLocation();
if (location instanceof InstanceFieldKey) {
InstanceFieldKey ifk = (InstanceFieldKey) location;
return ifk.getField().getName().toString().equals("size");
}
}
}
return false;
})
.findFirst()
.isPresent());
}
@Test
public void testIntegerValueOf()
throws ClassHierarchyException, IllegalArgumentException, CancelException, IOException {
AnalysisScope scope = findOrCreateAnalysisScope();
IClassHierarchy cha = findOrCreateCHA(scope);
Iterable<Entrypoint> entrypoints =
com.ibm.wala.ipa.callgraph.impl.Util.makeMainEntrypoints(cha, "Lslice/TestIntegerValueOf");
AnalysisOptions options = CallGraphTestUtil.makeAnalysisOptions(scope, entrypoints);
CallGraphBuilder<InstanceKey> builder =
Util.makeZeroOneContainerCFABuilder(options, new AnalysisCacheImpl(), cha);
CallGraph cg = builder.makeCallGraph(options, null);
CGNode main = CallGraphSearchUtil.findMainMethod(cg);
Statement s = SlicerUtil.findCallTo(main, "doNothing");
final PointerAnalysis<InstanceKey> pointerAnalysis = builder.getPointerAnalysis();
Collection<Statement> slice =
Slicer.computeBackwardSlice(
s, cg, pointerAnalysis, DataDependenceOptions.NO_HEAP, ControlDependenceOptions.NONE);
// SlicerUtil.dumpSlice(slice);
List<Statement> inMain =
slice.stream().filter(st -> st.getNode().equals(main)).collect(Collectors.toList());
inMain.stream().forEach(System.err::println);
Assert.assertEquals(4, inMain.size());
// returns for Integer.valueOf() and getInt()
Assert.assertEquals(2, inMain.stream().filter(st -> st instanceof NormalReturnCaller).count());
}
}
| 48,218
| 42.28456
| 100
|
java
|
WALA
|
WALA-master/core/src/test/java/com/ibm/wala/core/tests/typeInference/TypeInferenceTest.java
|
/*
* Copyright (c) 2002 - 2006 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.core.tests.typeInference;
import com.ibm.wala.analysis.typeInference.ConeType;
import com.ibm.wala.analysis.typeInference.TypeAbstraction;
import com.ibm.wala.analysis.typeInference.TypeInference;
import com.ibm.wala.classLoader.ClassLoaderFactory;
import com.ibm.wala.classLoader.ClassLoaderFactoryImpl;
import com.ibm.wala.classLoader.IMethod;
import com.ibm.wala.core.tests.util.TestConstants;
import com.ibm.wala.core.tests.util.WalaTestCase;
import com.ibm.wala.core.util.config.AnalysisScopeReader;
import com.ibm.wala.core.util.io.FileProvider;
import com.ibm.wala.core.util.strings.Atom;
import com.ibm.wala.core.util.strings.ImmutableByteArray;
import com.ibm.wala.core.util.strings.UTF8Convert;
import com.ibm.wala.core.util.warnings.Warnings;
import com.ibm.wala.ipa.callgraph.AnalysisCacheImpl;
import com.ibm.wala.ipa.callgraph.AnalysisOptions;
import com.ibm.wala.ipa.callgraph.AnalysisScope;
import com.ibm.wala.ipa.callgraph.IAnalysisCacheView;
import com.ibm.wala.ipa.callgraph.impl.Everywhere;
import com.ibm.wala.ipa.cha.ClassHierarchy;
import com.ibm.wala.ipa.cha.ClassHierarchyException;
import com.ibm.wala.ipa.cha.ClassHierarchyFactory;
import com.ibm.wala.ssa.IR;
import com.ibm.wala.types.MethodReference;
import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;
/**
* Test that the SSA-numbering of variables in the IR is deterministic.
*
* <p>Introduced 05-AUG-03; the default implementation of hashCode was being invoked.
* Object.hashCode is a source of random numbers and has no place in a deterministic program.
*/
public class TypeInferenceTest extends WalaTestCase {
private static final ClassLoader MY_CLASSLOADER = TypeInferenceTest.class.getClassLoader();
private static AnalysisScope scope;
private static ClassHierarchy cha;
private static AnalysisOptions options;
private static IAnalysisCacheView cache;
public static void main(String[] args) {
justThisTest(TypeInferenceTest.class);
}
@BeforeClass
public static void beforeClass() throws Exception {
scope =
AnalysisScopeReader.instance.readJavaScope(
TestConstants.WALA_TESTDATA,
new FileProvider().getFile("J2SEClassHierarchyExclusions.txt"),
MY_CLASSLOADER);
options = new AnalysisOptions(scope, null);
cache = new AnalysisCacheImpl();
ClassLoaderFactory factory = new ClassLoaderFactoryImpl(scope.getExclusions());
try {
cha = ClassHierarchyFactory.make(scope, factory);
} catch (ClassHierarchyException e) {
throw new Exception(e);
}
}
@AfterClass
public static void afterClass() throws Exception {
Warnings.clear();
scope = null;
cha = null;
options = null;
cache = null;
}
@Test
public void test1() {
MethodReference method =
scope.findMethod(
AnalysisScope.APPLICATION,
"LtypeInference/TI",
Atom.findOrCreateUnicodeAtom("foo"),
new ImmutableByteArray(UTF8Convert.toUTF8("()V")));
Assert.assertNotNull("method not found", method);
IMethod imethod = cha.resolveMethod(method);
Assert.assertNotNull("imethod not found", imethod);
IR ir = cache.getIRFactory().makeIR(imethod, Everywhere.EVERYWHERE, options.getSSAOptions());
System.out.println(ir);
TypeInference ti = TypeInference.make(ir, false);
for (int i = 1; i <= ir.getSymbolTable().getMaxValueNumber(); i++) {
System.err.println(i + " " + ti.getType(i));
}
}
@Test
public void test2() {
MethodReference method =
scope.findMethod(
AnalysisScope.APPLICATION,
"LtypeInference/TI",
Atom.findOrCreateUnicodeAtom("bar"),
new ImmutableByteArray(UTF8Convert.toUTF8("(I)V")));
Assert.assertNotNull("method not found", method);
IMethod imethod = cha.resolveMethod(method);
Assert.assertNotNull("imethod not found", imethod);
IR ir = cache.getIRFactory().makeIR(imethod, Everywhere.EVERYWHERE, options.getSSAOptions());
System.out.println(ir);
TypeInference ti = TypeInference.make(ir, true);
Assert.assertNotNull("null type abstraction for parameter", ti.getType(2));
}
@Test
public void test3() {
MethodReference method =
scope.findMethod(
AnalysisScope.APPLICATION,
"LtypeInference/TI",
Atom.findOrCreateUnicodeAtom("inferInt"),
new ImmutableByteArray(UTF8Convert.toUTF8("()V")));
Assert.assertNotNull("method not found", method);
IMethod imethod = cha.resolveMethod(method);
Assert.assertNotNull("imethod not found", imethod);
IR ir = cache.getIRFactory().makeIR(imethod, Everywhere.EVERYWHERE, options.getSSAOptions());
System.out.println(ir);
TypeInference ti = TypeInference.make(ir, true);
TypeAbstraction type = ti.getType(7);
Assert.assertNotNull("null type abstraction", type);
Assert.assertEquals("inferred wrong type", "int", type.toString());
}
@Test
public void test4() {
MethodReference method =
scope.findMethod(
AnalysisScope.APPLICATION,
"LtypeInference/TI",
Atom.findOrCreateUnicodeAtom("useCast"),
new ImmutableByteArray(UTF8Convert.toUTF8("(Ljava/lang/Object;)V")));
Assert.assertNotNull("method not found", method);
IMethod imethod = cha.resolveMethod(method);
Assert.assertNotNull("imethod not found", imethod);
IR ir = cache.getIRFactory().makeIR(imethod, Everywhere.EVERYWHERE, options.getSSAOptions());
System.out.println(ir);
TypeInference ti = TypeInference.make(ir, false);
TypeAbstraction type = ti.getType(4);
Assert.assertNotNull("null type abstraction", type);
Assert.assertTrue(
"inferred wrong type " + type,
type instanceof ConeType
&& ((ConeType) type)
.getTypeReference()
.getName()
.toString()
.equals("Ljava/lang/String"));
}
}
| 6,411
| 35.022472
| 97
|
java
|
WALA
|
WALA-master/core/src/test/java/com/ibm/wala/core/tests/typeargument/TypeArgumentTest.java
|
package com.ibm.wala.core.tests.typeargument;
import com.ibm.wala.core.tests.util.WalaTestCase;
import com.ibm.wala.core.util.warnings.Warnings;
import com.ibm.wala.types.generics.TypeArgument;
import org.junit.AfterClass;
import org.junit.Test;
public class TypeArgumentTest extends WalaTestCase {
public static void main(String[] args) {
justThisTest(TypeArgumentTest.class);
}
@AfterClass
public static void afterClass() throws Exception {
Warnings.clear();
}
@Test
public void test() {
// Test for StringIndexOutOfBoundsException
TypeArgument.make("<Lorg/apache/hadoop/io/Text;[B>");
// Test for "bad type argument list"
TypeArgument.make("<[TP_OUT;>");
}
}
| 706
| 25.185185
| 57
|
java
|
WALA
|
WALA-master/core/src/test/java/com/ibm/wala/demandpa/driver/CompareToZeroOneCFADriver.java
|
/*
* Copyright (c) 2002 - 2014 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
/*
* Refinement Analysis Tools is Copyright (c) 2007 The Regents of the University of California
* (Regents). Provided that this notice and the following two paragraphs are included in any
* distribution of Refinement Analysis Tools or its derivative work, Regents agrees not to assert
* any of Regents' copyright rights in Refinement Analysis Tools against recipient for recipient's
* reproduction, preparation of derivative works, public display, public performance, distribution
* or sublicensing of Refinement Analysis Tools and derivative works, in source code and object code
* form. This agreement not to assert does not confer, by implication, estoppel, or otherwise any
* license or rights in any intellectual property of Regents, including, but not limited to, any
* patents of Regents or Regents' employees.
*
* <p>IN NO EVENT SHALL REGENTS BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR
* CONSEQUENTIAL DAMAGES, INCLUDING LOST PROFITS, ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS
* DOCUMENTATION, EVEN IF REGENTS HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* <p>REGENTS SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE AND FURTHER DISCLAIMS ANY
* STATUTORY WARRANTY OF NON-INFRINGEMENT. THE SOFTWARE AND ACCOMPANYING DOCUMENTATION, IF ANY,
* PROVIDED HEREUNDER IS PROVIDED "AS IS". REGENTS HAS NO OBLIGATION TO PROVIDE MAINTENANCE,
* SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
*/
package com.ibm.wala.demandpa.driver;
import com.ibm.wala.analysis.reflection.InstanceKeyWithNode;
import com.ibm.wala.analysis.typeInference.TypeAbstraction;
import com.ibm.wala.analysis.typeInference.TypeInference;
import com.ibm.wala.classLoader.Language;
import com.ibm.wala.core.tests.callGraph.CallGraphTestUtil;
import com.ibm.wala.core.tests.demandpa.TestInfo;
import com.ibm.wala.core.util.config.AnalysisScopeReader;
import com.ibm.wala.demandpa.alg.DemandRefinementPointsTo;
import com.ibm.wala.demandpa.alg.IDemandPointerAnalysis;
import com.ibm.wala.demandpa.alg.statemachine.DummyStateMachine;
import com.ibm.wala.demandpa.util.CallGraphMapUtil;
import com.ibm.wala.demandpa.util.MemoryAccessMap;
import com.ibm.wala.demandpa.util.SimpleMemoryAccessMap;
import com.ibm.wala.ipa.callgraph.AnalysisCacheImpl;
import com.ibm.wala.ipa.callgraph.AnalysisOptions;
import com.ibm.wala.ipa.callgraph.AnalysisScope;
import com.ibm.wala.ipa.callgraph.CGNode;
import com.ibm.wala.ipa.callgraph.CallGraph;
import com.ibm.wala.ipa.callgraph.CallGraphBuilder;
import com.ibm.wala.ipa.callgraph.Entrypoint;
import com.ibm.wala.ipa.callgraph.impl.Util;
import com.ibm.wala.ipa.callgraph.propagation.HeapModel;
import com.ibm.wala.ipa.callgraph.propagation.InstanceKey;
import com.ibm.wala.ipa.callgraph.propagation.LocalPointerKey;
import com.ibm.wala.ipa.callgraph.propagation.PointerAnalysis;
import com.ibm.wala.ipa.callgraph.propagation.SSAPropagationCallGraphBuilder;
import com.ibm.wala.ipa.cha.ClassHierarchy;
import com.ibm.wala.ipa.cha.ClassHierarchyException;
import com.ibm.wala.ipa.cha.ClassHierarchyFactory;
import com.ibm.wala.ssa.IR;
import com.ibm.wala.types.MethodReference;
import com.ibm.wala.util.CancelException;
import com.ibm.wala.util.debug.Assertions;
import com.ibm.wala.util.intset.OrdinalSet;
import java.io.File;
import java.io.IOException;
import java.util.Collection;
/**
* Driver that tests analysis results against ZeroOneCFA analysis.
*
* @author Manu Sridharan
*/
public class CompareToZeroOneCFADriver {
public static void main(String[] args) {
// for (String testCase : TestInfo.ALL_TEST_CASES) {
// runUnitTestCase(testCase);
// }
// runUnitTestCase(TestInfo.TEST_PRIMITIVES);
// runApplication("/home/manu/research/DOMO/tests/JLex.jar");
}
@SuppressWarnings("unused")
private static void runUnitTestCase(String mainClass)
throws IllegalArgumentException, CancelException, IOException {
System.err.println("=======---------------=============");
System.err.println(("ANALYZING " + mainClass + "\n\n"));
// describe the "scope", what is the program we're analyzing
AnalysisScope scope =
CallGraphTestUtil.makeJ2SEAnalysisScope(
TestInfo.SCOPE_FILE, CallGraphTestUtil.REGRESSION_EXCLUSIONS);
Object warnings = new Object();
// build a type hierarchy
ClassHierarchy cha = null;
try {
cha = ClassHierarchyFactory.make(scope);
} catch (ClassHierarchyException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// set up call graph construction options; mainly what should be considered
// entrypoints?
Iterable<Entrypoint> entrypoints =
com.ibm.wala.ipa.callgraph.impl.Util.makeMainEntrypoints(cha, mainClass);
AnalysisOptions options = CallGraphTestUtil.makeAnalysisOptions(scope, entrypoints);
// run existing pointer analysis
doTests(cha, options);
System.err.println("ALL FINE");
}
@SuppressWarnings("unused")
private static void runApplication(String appJar)
throws IllegalArgumentException, CancelException, IOException {
System.err.println("=======---------------=============");
System.err.println(("ANALYZING " + appJar + "\n\n"));
AnalysisScope scope =
AnalysisScopeReader.instance.makeJavaBinaryAnalysisScope(
appJar, new File(CallGraphTestUtil.REGRESSION_EXCLUSIONS));
// TODO: return the warning set (need a CAPA type)
// invoke DOMO to build a DOMO class hierarchy object
Object warnings = new Object();
ClassHierarchy cha = null;
try {
cha = ClassHierarchyFactory.make(scope);
} catch (ClassHierarchyException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Iterable<Entrypoint> entrypoints =
com.ibm.wala.ipa.callgraph.impl.Util.makeMainEntrypoints(cha);
AnalysisOptions options = new AnalysisOptions(scope, entrypoints);
doTests(cha, options);
System.err.println("ALL FINE");
}
private static void doTests(final ClassHierarchy cha, AnalysisOptions options)
throws IllegalArgumentException, CancelException {
final SSAPropagationCallGraphBuilder builder =
Util.makeVanillaZeroOneCFABuilder(Language.JAVA, options, new AnalysisCacheImpl(), cha);
final CallGraph oldCG = builder.makeCallGraph(options, null);
final PointerAnalysis<InstanceKey> pa = builder.getPointerAnalysis();
// now, run our analysis
// build an RTA call graph
CallGraphBuilder<InstanceKey> rtaBuilder =
Util.makeRTABuilder(options, new AnalysisCacheImpl(), cha);
final CallGraph cg = rtaBuilder.makeCallGraph(options, null);
// System.err.println(cg.toString());
MemoryAccessMap fam =
new SimpleMemoryAccessMap(cg, rtaBuilder.getPointerAnalysis().getHeapModel(), false);
final IDemandPointerAnalysis dmp = makeDemandPointerAnalysis(options, cha, cg, fam);
final class Helper {
void checkPointersInMethod(CGNode node) {
// TODO remove this hack
if (node.getMethod().getReference().toString().contains("clone()Ljava/lang/Object;")) {
System.err.println(("SKIPPING " + node));
return;
}
CGNode oldNode = CallGraphMapUtil.mapCGNode(node, cg, oldCG);
if (oldNode == null) {
return;
}
System.err.println(("METHOD " + node));
IR ir = node.getIR();
TypeInference ti = TypeInference.make(ir, false);
for (int i = 1; i <= ir.getSymbolTable().getMaxValueNumber(); i++) {
TypeAbstraction t = ti.getType(i);
if (t != null) {
final HeapModel heapModel = dmp.getHeapModel();
LocalPointerKey pk = (LocalPointerKey) heapModel.getPointerKeyForLocal(node, i);
LocalPointerKey oldPk =
(LocalPointerKey) CallGraphMapUtil.mapPointerKey(pk, cg, oldCG, heapModel);
Collection<InstanceKey> p2set = dmp.getPointsTo(pk);
OrdinalSet<InstanceKey> otherP2Set = pa.getPointsToSet(oldPk);
System.err.println(("OLD POINTS-TO " + otherP2Set));
for (InstanceKey key : otherP2Set) {
if (knownBug(key)) {
continue;
}
InstanceKey newKey = CallGraphMapUtil.mapInstKey(key, oldCG, cg, heapModel);
if (!p2set.contains(newKey)) {
System.err.println("BADNESS");
System.err.println(("pointer key " + pk));
System.err.println(("missing " + newKey));
Assertions.UNREACHABLE();
}
}
}
}
}
}
Helper h = new Helper();
for (CGNode node : cg) {
h.checkPointersInMethod(node);
}
}
private static boolean knownBug(InstanceKey key) {
// if (key instanceof MultiNewArrayAllocationSiteKey) {
// return true;
// }
if (key instanceof InstanceKeyWithNode) {
CGNode node = ((InstanceKeyWithNode) key).getNode();
MethodReference methodRef = node.getMethod().getReference();
if (methodRef
.toString()
.equals("< Primordial, Ljava/lang/Object, clone()Ljava/lang/Object; >")) {
return true;
}
}
return false;
}
private static IDemandPointerAnalysis makeDemandPointerAnalysis(
AnalysisOptions options, ClassHierarchy cha, CallGraph cg, MemoryAccessMap fam) {
SSAPropagationCallGraphBuilder builder =
Util.makeVanillaZeroOneCFABuilder(Language.JAVA, options, new AnalysisCacheImpl(), cha);
// return new TestNewGraphPointsTo(cg, builder, fam, cha, warnings);
DemandRefinementPointsTo fullDemandPointsTo =
DemandRefinementPointsTo.makeWithDefaultFlowGraph(
cg, builder, fam, cha, options, new DummyStateMachine.Factory<>());
// fullDemandPointsTo.setOnTheFly(true);
// fullDemandPointsTo.setRefineFields(true);
return fullDemandPointsTo;
}
}
| 10,401
| 42.161826
| 100
|
java
|
WALA
|
WALA-master/core/src/test/java/com/ibm/wala/demandpa/driver/TestAgainstSimpleDriver.java
|
/*
* Copyright (c) 2002 - 2014 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
/*
* Refinement Analysis Tools is Copyright (c) 2007 The Regents of the University of California
* (Regents). Provided that this notice and the following two paragraphs are included in any
* distribution of Refinement Analysis Tools or its derivative work, Regents agrees not to assert
* any of Regents' copyright rights in Refinement Analysis Tools against recipient for recipient's
* reproduction, preparation of derivative works, public display, public performance, distribution
* or sublicensing of Refinement Analysis Tools and derivative works, in source code and object code
* form. This agreement not to assert does not confer, by implication, estoppel, or otherwise any
* license or rights in any intellectual property of Regents, including, but not limited to, any
* patents of Regents or Regents' employees.
*
* <p>IN NO EVENT SHALL REGENTS BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR
* CONSEQUENTIAL DAMAGES, INCLUDING LOST PROFITS, ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS
* DOCUMENTATION, EVEN IF REGENTS HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* <p>REGENTS SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE AND FURTHER DISCLAIMS ANY
* STATUTORY WARRANTY OF NON-INFRINGEMENT. THE SOFTWARE AND ACCOMPANYING DOCUMENTATION, IF ANY,
* PROVIDED HEREUNDER IS PROVIDED "AS IS". REGENTS HAS NO OBLIGATION TO PROVIDE MAINTENANCE,
* SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
*/
package com.ibm.wala.demandpa.driver;
import com.ibm.wala.analysis.typeInference.TypeAbstraction;
import com.ibm.wala.analysis.typeInference.TypeInference;
import com.ibm.wala.classLoader.Language;
import com.ibm.wala.core.tests.callGraph.CallGraphTestUtil;
import com.ibm.wala.core.tests.demandpa.TestInfo;
import com.ibm.wala.demandpa.alg.DemandRefinementPointsTo;
import com.ibm.wala.demandpa.alg.IDemandPointerAnalysis;
import com.ibm.wala.demandpa.alg.SimpleDemandPointsTo;
import com.ibm.wala.demandpa.alg.refinepolicy.AlwaysRefineCGPolicy;
import com.ibm.wala.demandpa.alg.refinepolicy.AlwaysRefineFieldsPolicy;
import com.ibm.wala.demandpa.alg.refinepolicy.SinglePassRefinementPolicy;
import com.ibm.wala.demandpa.alg.statemachine.DummyStateMachine;
import com.ibm.wala.demandpa.util.MemoryAccessMap;
import com.ibm.wala.demandpa.util.SimpleMemoryAccessMap;
import com.ibm.wala.ipa.callgraph.AnalysisCacheImpl;
import com.ibm.wala.ipa.callgraph.AnalysisOptions;
import com.ibm.wala.ipa.callgraph.AnalysisScope;
import com.ibm.wala.ipa.callgraph.CGNode;
import com.ibm.wala.ipa.callgraph.CallGraph;
import com.ibm.wala.ipa.callgraph.CallGraphBuilder;
import com.ibm.wala.ipa.callgraph.Entrypoint;
import com.ibm.wala.ipa.callgraph.impl.Util;
import com.ibm.wala.ipa.callgraph.propagation.InstanceKey;
import com.ibm.wala.ipa.callgraph.propagation.LocalPointerKey;
import com.ibm.wala.ipa.callgraph.propagation.PointerKey;
import com.ibm.wala.ipa.callgraph.propagation.SSAPropagationCallGraphBuilder;
import com.ibm.wala.ipa.cha.ClassHierarchy;
import com.ibm.wala.ipa.cha.ClassHierarchyException;
import com.ibm.wala.ipa.cha.ClassHierarchyFactory;
import com.ibm.wala.ssa.IR;
import com.ibm.wala.util.CancelException;
import java.io.IOException;
import java.util.Collection;
/**
* Driver that tests a pointer analysis results against the results of {@link SimpleDemandPointsTo}.
*
* @author Manu Sridharan
*/
public class TestAgainstSimpleDriver {
private static final boolean VERBOSE = false;
public static void main(String[] args)
throws IllegalArgumentException, CancelException, IOException {
// for (String String : ALL_TEST_CASES) {
// runAnalysisForString(String.mainClass, String.scopeFileName);
// }
runAnalysisForTestCase(TestInfo.TEST_ARRAY_SET_ITER);
System.err.println("computed all points-to sets successfully");
}
private static void runAnalysisForTestCase(String mainClass)
throws IllegalArgumentException, CancelException, IOException {
System.err.println("=======---------------=============");
System.err.println(("ANALYZING " + mainClass + "\n\n"));
// describe the "scope", what is the program we're analyzing
AnalysisScope scope =
CallGraphTestUtil.makeJ2SEAnalysisScope(
TestInfo.SCOPE_FILE, CallGraphTestUtil.REGRESSION_EXCLUSIONS);
// build a type hierarchy
ClassHierarchy cha = null;
try {
cha = ClassHierarchyFactory.make(scope);
} catch (ClassHierarchyException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// set up call graph construction options; mainly what should be considered
// entrypoints?
Iterable<Entrypoint> entrypoints =
com.ibm.wala.ipa.callgraph.impl.Util.makeMainEntrypoints(cha, mainClass);
AnalysisOptions options = CallGraphTestUtil.makeAnalysisOptions(scope, entrypoints);
// build an RTA call graph
CallGraphBuilder<InstanceKey> rtaBuilder =
Util.makeRTABuilder(options, new AnalysisCacheImpl(), cha);
final CallGraph cg = rtaBuilder.makeCallGraph(options, null);
// System.err.println(cg.toString());
MemoryAccessMap fam =
new SimpleMemoryAccessMap(cg, rtaBuilder.getPointerAnalysis().getHeapModel(), false);
// System.err.println(fam.toString());
IDemandPointerAnalysis dmp = makeDemandPointerAnalysis(options, cha, cg, fam);
IDemandPointerAnalysis simpleDmp =
new SimpleDemandPointsTo(cg, dmp.getHeapModel(), fam, cha, options);
CGNode main = cg.getEntrypointNodes().iterator().next();
IR ir = main.getIR();
TypeInference ti = TypeInference.make(ir, false);
for (int i = 1; i <= ir.getSymbolTable().getMaxValueNumber(); i++) {
TypeAbstraction t = ti.getType(i);
if (t != null) {
LocalPointerKey v = (LocalPointerKey) dmp.getHeapModel().getPointerKeyForLocal(main, i);
Collection<InstanceKey> p = dmp.getPointsTo(v);
Collection<InstanceKey> oldP = simpleDmp.getPointsTo(v);
if (!sameContents(p, oldP)) {
System.err.println(("different result for " + v));
System.err.println(("old " + oldP + "\n\nnew " + p));
}
printResult(v, p);
}
}
}
private static <T> boolean sameContents(Collection<T> c1, Collection<T> c2) {
return c1.containsAll(c2) && c2.containsAll(c1);
}
private static void printResult(PointerKey pk, Collection<InstanceKey> result) {
if (VERBOSE) {
System.err.println("points-to for " + pk);
if (result.isEmpty()) {
System.err.println(" EMPTY!");
}
for (InstanceKey instanceKey : result) {
System.err.println(" " + instanceKey);
}
}
}
private static IDemandPointerAnalysis makeDemandPointerAnalysis(
AnalysisOptions options, ClassHierarchy cha, CallGraph cg, MemoryAccessMap fam) {
SSAPropagationCallGraphBuilder builder =
Util.makeVanillaZeroOneCFABuilder(Language.JAVA, options, new AnalysisCacheImpl(), cha);
// return new TestNewGraphPointsTo(cg, builder, fam, cha, warnings);
DemandRefinementPointsTo fullDemandPointsTo =
DemandRefinementPointsTo.makeWithDefaultFlowGraph(
cg, builder, fam, cha, options, new DummyStateMachine.Factory<>());
// fullDemandPointsTo.setCGRefinePolicy(new AlwaysRefineCGPolicy());
// fullDemandPointsTo.setFieldRefinePolicy(new AlwaysRefineFieldsPolicy());
fullDemandPointsTo.setRefinementPolicyFactory(
new SinglePassRefinementPolicy.Factory(
new AlwaysRefineFieldsPolicy(), new AlwaysRefineCGPolicy()));
return fullDemandPointsTo;
}
}
| 8,068
| 44.587571
| 100
|
java
|
WALA
|
WALA-master/core/src/test/java/com/ibm/wala/demandpa/driver/WalaUtil.java
|
/*
* This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html.
*
* This file is a derivative of code released by the University of
* California under the terms listed below.
*
* Refinement Analysis Tools is Copyright (c) 2007 The Regents of the
* University of California (Regents). Provided that this notice and
* the following two paragraphs are included in any distribution of
* Refinement Analysis Tools or its derivative work, Regents agrees
* not to assert any of Regents' copyright rights in Refinement
* Analysis Tools against recipient for recipient's reproduction,
* preparation of derivative works, public display, public
* performance, distribution or sublicensing of Refinement Analysis
* Tools and derivative works, in source code and object code form.
* This agreement not to assert does not confer, by implication,
* estoppel, or otherwise any license or rights in any intellectual
* property of Regents, including, but not limited to, any patents
* of Regents or Regents' employees.
*
* IN NO EVENT SHALL REGENTS BE LIABLE TO ANY PARTY FOR DIRECT,
* INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES,
* INCLUDING LOST PROFITS, ARISING OUT OF THE USE OF THIS SOFTWARE
* AND ITS DOCUMENTATION, EVEN IF REGENTS HAS BEEN ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* REGENTS SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE AND FURTHER DISCLAIMS ANY STATUTORY
* WARRANTY OF NON-INFRINGEMENT. THE SOFTWARE AND ACCOMPANYING
* DOCUMENTATION, IF ANY, PROVIDED HEREUNDER IS PROVIDED "AS
* IS". REGENTS HAS NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT,
* UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
*/
package com.ibm.wala.demandpa.driver;
import com.ibm.wala.ipa.callgraph.CGNode;
import com.ibm.wala.ipa.callgraph.CallGraph;
import com.ibm.wala.properties.WalaProperties;
import com.ibm.wala.ssa.IR;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Properties;
/**
* Various utility methods for working with WALA.
*
* @author Manu Sridharan
*/
public class WalaUtil {
public static void dumpAllIR(CallGraph cg, String benchName, Properties p)
throws IllegalArgumentException, IllegalArgumentException {
if (cg == null) {
throw new IllegalArgumentException("cg == null");
}
if (p == null) {
throw new IllegalArgumentException("p == null");
}
System.err.print("dumping ir...");
String irFile =
p.getProperty(WalaProperties.OUTPUT_DIR) + File.separatorChar + benchName + "-ir.txt";
try (final PrintWriter writer = new PrintWriter(new BufferedWriter(new FileWriter(irFile)))) {
for (CGNode node : cg) {
IR ir = node.getIR();
if (ir == null) continue;
writer.println(node);
writer.println("+++++++++++++++++++++++++++++++++");
writer.println(ir);
writer.println("");
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.err.println("done");
}
}
| 3,351
| 37.976744
| 98
|
java
|
WALA
|
WALA-master/core/src/test/java/com/ibm/wala/examples/analysis/ConstructAllIRs.java
|
/*
* Copyright (c) 2008 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.examples.analysis;
import com.ibm.wala.classLoader.IClass;
import com.ibm.wala.classLoader.IMethod;
import com.ibm.wala.core.util.config.AnalysisScopeReader;
import com.ibm.wala.core.util.ref.ReferenceCleanser;
import com.ibm.wala.ipa.callgraph.AnalysisCacheImpl;
import com.ibm.wala.ipa.callgraph.AnalysisOptions;
import com.ibm.wala.ipa.callgraph.AnalysisScope;
import com.ibm.wala.ipa.callgraph.IAnalysisCacheView;
import com.ibm.wala.ipa.callgraph.impl.Everywhere;
import com.ibm.wala.ipa.cha.ClassHierarchy;
import com.ibm.wala.ipa.cha.ClassHierarchyException;
import com.ibm.wala.ipa.cha.ClassHierarchyFactory;
import com.ibm.wala.util.perf.Stopwatch;
import java.io.IOException;
/**
* An analysis skeleton that simply constructs IRs for all methods in a class hierarchy. Illustrates
* the use of {@link ReferenceCleanser} to improve running time / reduce memory usage.
*/
public class ConstructAllIRs {
/** Should we periodically clear out soft reference caches in an attempt to help the GC? */
private static final boolean PERIODIC_WIPE_SOFT_CACHES = true;
/** Interval which defines the period to clear soft reference caches */
private static final int WIPE_SOFT_CACHE_INTERVAL = 2500;
/** Counter for wiping soft caches */
private static int wipeCount = 0;
/** First command-line argument should be location of scope file for application to analyze */
public static void main(String[] args) throws IOException, ClassHierarchyException {
String scopeFile = args[0];
// measure running time
Stopwatch s = new Stopwatch();
s.start();
AnalysisScope scope =
AnalysisScopeReader.instance.readJavaScope(
scopeFile, null, ConstructAllIRs.class.getClassLoader());
// build a type hierarchy
System.out.print("building class hierarchy...");
ClassHierarchy cha = ClassHierarchyFactory.make(scope);
System.out.println("done");
// register class hierarchy and AnalysisCache with the reference cleanser, so that their soft
// references are appropriately wiped
ReferenceCleanser.registerClassHierarchy(cha);
AnalysisOptions options = new AnalysisOptions();
IAnalysisCacheView cache = new AnalysisCacheImpl(options.getSSAOptions());
ReferenceCleanser.registerCache(cache);
System.out.print("building IRs...");
for (IClass klass : cha) {
for (IMethod method : klass.getDeclaredMethods()) {
wipeSoftCaches();
// construct an IR; it will be cached
cache.getIR(method, Everywhere.EVERYWHERE);
}
}
System.out.println("done");
s.stop();
System.out.println("RUNNING TIME: " + s.getElapsedMillis());
}
private static void wipeSoftCaches() {
if (PERIODIC_WIPE_SOFT_CACHES) {
wipeCount++;
if (wipeCount >= WIPE_SOFT_CACHE_INTERVAL) {
wipeCount = 0;
ReferenceCleanser.clearSoftCaches();
}
}
}
}
| 3,285
| 35.921348
| 100
|
java
|
WALA
|
WALA-master/core/src/test/java/com/ibm/wala/examples/analysis/CountParameters.java
|
/*
* Copyright (c) 2002 - 2006 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.examples.analysis;
import com.ibm.wala.classLoader.IClass;
import com.ibm.wala.classLoader.IMethod;
import com.ibm.wala.core.util.config.AnalysisScopeReader;
import com.ibm.wala.ipa.callgraph.AnalysisScope;
import com.ibm.wala.ipa.cha.ClassHierarchyException;
import com.ibm.wala.ipa.cha.ClassHierarchyFactory;
import com.ibm.wala.ipa.cha.IClassHierarchy;
import java.io.IOException;
/**
* This is a simple example WALA application.
*
* <p>This counts the number of parameters to each method in the primordial loader (the J2SE
* standard libraries), and prints the result.
*
* @author sfink
*/
public class CountParameters {
private static final ClassLoader MY_CLASSLOADER = CountParameters.class.getClassLoader();
/** Use the 'CountParameters' launcher to run this program with the appropriate classpath */
public static void main(String[] args) throws IOException, ClassHierarchyException {
// build an analysis scope representing the standard libraries, excluding no classes
AnalysisScope scope =
AnalysisScopeReader.instance.readJavaScope("primordial.txt", null, MY_CLASSLOADER);
// build a class hierarchy
System.err.print("Build class hierarchy...");
IClassHierarchy cha = ClassHierarchyFactory.make(scope);
System.err.println("Done");
int nClasses = 0;
int nMethods = 0;
int nParameters = 0;
for (IClass c : cha) {
nClasses++;
for (IMethod m : c.getDeclaredMethods()) {
nMethods++;
nParameters += m.getNumberOfParameters();
}
}
System.out.println(nClasses + " classes");
System.out.println(nMethods + " methods");
System.out.println((float) nParameters / (float) nMethods + " parameters per method");
}
}
| 2,129
| 33.354839
| 94
|
java
|
WALA
|
WALA-master/core/src/test/java/com/ibm/wala/examples/analysis/GetLoadedFields.java
|
/*
* Copyright (c) 2002 - 2006 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.examples.analysis;
import com.ibm.wala.classLoader.CodeScanner;
import com.ibm.wala.classLoader.IClass;
import com.ibm.wala.classLoader.IMethod;
import com.ibm.wala.core.util.config.AnalysisScopeReader;
import com.ibm.wala.ipa.callgraph.AnalysisScope;
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.shrike.shrikeCT.InvalidClassFileException;
import com.ibm.wala.types.FieldReference;
import com.ibm.wala.util.collections.HashMapFactory;
import java.io.IOException;
import java.util.Collection;
import java.util.Map;
/**
* This is a simple example WALA application.
*
* <p>For each method in the standard libraries, it maps the IMethod to the set of fields the method
* reads.
*
* @author sfink
*/
public class GetLoadedFields {
private static final ClassLoader MY_CLASSLOADER = GetLoadedFields.class.getClassLoader();
/** Use the 'GetLoadedFields' launcher to run this program with the appropriate classpath */
public static void main(String[] args)
throws IOException, ClassHierarchyException, InvalidClassFileException {
// build an analysis scope representing the standard libraries, excluding no classes
AnalysisScope scope =
AnalysisScopeReader.instance.readJavaScope("primordial.txt", null, MY_CLASSLOADER);
// build a class hierarchy
System.err.print("Build class hierarchy...");
IClassHierarchy cha = ClassHierarchyFactory.make(scope);
System.err.println("Done");
int nMethods = 0;
int nFields = 0;
Map<IMethod, Collection<FieldReference>> method2Field = HashMapFactory.make();
for (IClass c : cha) {
for (IMethod m : c.getDeclaredMethods()) {
nMethods++;
Collection<FieldReference> fields = CodeScanner.getFieldsRead(m);
nFields += fields.size();
method2Field.put(m, fields);
}
}
System.out.println(nMethods + " methods");
System.out.println((float) nFields / (float) nMethods + " fields read per method");
}
}
| 2,471
| 34.826087
| 100
|
java
|
WALA
|
WALA-master/core/src/test/java/com/ibm/wala/examples/analysis/SimpleThreadEscapeAnalysis.java
|
/*
* Copyright (c) 2006 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.examples.analysis;
import com.ibm.wala.classLoader.ArrayClass;
import com.ibm.wala.classLoader.IClass;
import com.ibm.wala.classLoader.IField;
import com.ibm.wala.classLoader.IMethod;
import com.ibm.wala.classLoader.JarFileModule;
import com.ibm.wala.classLoader.Language;
import com.ibm.wala.client.AbstractAnalysisEngine;
import com.ibm.wala.ipa.callgraph.AnalysisOptions;
import com.ibm.wala.ipa.callgraph.CGNode;
import com.ibm.wala.ipa.callgraph.CallGraph;
import com.ibm.wala.ipa.callgraph.CallGraphBuilder;
import com.ibm.wala.ipa.callgraph.Entrypoint;
import com.ibm.wala.ipa.callgraph.IAnalysisCacheView;
import com.ibm.wala.ipa.callgraph.impl.Util;
import com.ibm.wala.ipa.callgraph.propagation.HeapModel;
import com.ibm.wala.ipa.callgraph.propagation.InstanceKey;
import com.ibm.wala.ipa.callgraph.propagation.PointerAnalysis;
import com.ibm.wala.ipa.callgraph.propagation.PointerKey;
import com.ibm.wala.ipa.cha.IClassHierarchy;
import com.ibm.wala.properties.WalaProperties;
import com.ibm.wala.types.TypeReference;
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.OrdinalSet;
import java.io.File;
import java.io.IOException;
import java.util.Collection;
import java.util.Properties;
import java.util.Set;
import java.util.jar.JarFile;
/**
* A simple thread-level escape analysis: this code computes the set of classes of which some
* instance may be accessed by some thread other than the one that created it.
*
* <p>The algorithm is not very bright; it is based on the observation that there are only three
* ways for an object to pass from one thread to another.
*
* <UL>
* <LI>The object is stored into a static variable.
* <LI>The object is stored into an instance field of a Thread
* <LI>The object is reachable from a field of another escaping object.
* </UL>
*
* <p>This observation is implemented in the obvious way:
*
* <OL>
* <LI>All static fields are collected
* <LI>All Thread constructor parameters are collected
* <LI>The points-to sets of these values represent the base set of escapees.
* <LI>All object reachable from fields of these objects are added
* <LI>This process continues until a fixpoint is reached
* <LI>The abstract objects in the points-to sets are converted to types
* <LI>This set of types is returned
* </OL>
*
* @author Julian Dolby
*/
public class SimpleThreadEscapeAnalysis
extends AbstractAnalysisEngine<InstanceKey, CallGraphBuilder<InstanceKey>, Void> {
private final Set<JarFile> applicationJarFiles;
private final String applicationMainClass;
/**
* The two input parameters define the program to analyze: the jars of .class files and the main
* class to start from.
*/
public SimpleThreadEscapeAnalysis(Set<JarFile> applicationJarFiles, String applicationMainClass) {
this.applicationJarFiles = applicationJarFiles;
this.applicationMainClass = applicationMainClass;
}
@Override
protected CallGraphBuilder<InstanceKey> getCallGraphBuilder(
IClassHierarchy cha, AnalysisOptions options, IAnalysisCacheView cache) {
return Util.makeZeroCFABuilder(Language.JAVA, options, cache, cha);
}
/**
* Given a root path, add it to the set if it is a jar, or traverse it recursively if it is a
* directory.
*/
private void collectJars(File f, Set<JarFile> result) throws IOException {
if (f.isDirectory()) {
File[] files = f.listFiles();
for (File file : files) {
collectJars(file, result);
}
} else if (f.getAbsolutePath().endsWith(".jar")) {
try (final JarFile jar = new JarFile(f, false)) {
result.add(jar);
}
}
}
/** Collect the set of JarFiles that constitute the system libraries of the running JRE. */
private JarFile[] getSystemJars() throws IOException {
String javaHomePath = "garbage";
Set<JarFile> jarFiles = HashSetFactory.make();
// first, see if wala.properties has been set up
try {
Properties p = WalaProperties.loadProperties();
javaHomePath = p.getProperty(WalaProperties.J2SE_DIR);
} catch (WalaException e) {
// no luck.
}
// if not, try assuming the running JRE looks normal
File x = new File(javaHomePath);
if (!(x.exists() && x.isDirectory())) {
javaHomePath = System.getProperty("java.home");
if (!javaHomePath.endsWith(File.separator)) {
javaHomePath += File.separator;
}
javaHomePath += "lib";
}
// find jars from chosen JRE lib path
collectJars(new File(javaHomePath), jarFiles);
return jarFiles.toArray(new JarFile[0]);
}
/**
* Take the given set of JarFiles that constitute the program, and return a set of Module files as
* expected by the WALA machinery.
*/
private Set<JarFileModule> getModuleFiles() {
Set<JarFileModule> result = HashSetFactory.make();
for (JarFile jarFile : applicationJarFiles) {
result.add(new JarFileModule(jarFile));
}
return result;
}
/** The heart of the analysis. */
public Set<IClass> gatherThreadEscapingClasses()
throws IOException, IllegalArgumentException, CancelException {
//
// set the application to analyze
//
setModuleFiles(getModuleFiles());
//
// set the system jar files to use.
// change this if you want to use a specific jre version
//
setJ2SELibraries(getSystemJars());
//
// the application and libraries are set, now build the scope...
//
buildAnalysisScope();
//
// ...and the class hierarchy
//
IClassHierarchy cha = buildClassHierarchy();
assert cha != null : "failed to create class hierarchy";
setClassHierarchy(cha);
//
// entrypoints are where analysis starts
//
Iterable<Entrypoint> roots = Util.makeMainEntrypoints(cha, applicationMainClass);
//
// analysis options controls aspects of call graph construction
//
AnalysisOptions options = getDefaultOptions(roots);
//
// build the call graph
//
buildCallGraph(cha, options, true, null);
//
// extract data for analysis
//
CallGraph cg = getCallGraph();
PointerAnalysis<? extends InstanceKey> pa = getPointerAnalysis();
//
// collect all places where objects can escape their creating thread:
// 1) all static fields
// 2) arguments to Thread constructors
//
Set<PointerKey> escapeAnalysisRoots = HashSetFactory.make();
HeapModel heapModel = pa.getHeapModel();
// 1) static fields
for (IClass cls : cha) {
Collection<IField> staticFields = cls.getDeclaredStaticFields();
for (IField sf : staticFields) {
if (sf.getFieldTypeReference().isReferenceType()) {
escapeAnalysisRoots.add(heapModel.getPointerKeyForStaticField(sf));
}
}
}
// 2) instance fields of Threads
// (we hack this by getting the 'this' parameter of all ctor calls;
// this works because the next phase will add all objects transitively
// reachable from fields of types in these pointer keys, and all
// Thread objects must be constructed somewhere)
Collection<IClass> threads = cha.computeSubClasses(TypeReference.JavaLangThread);
for (IClass cls : threads) {
for (IMethod m : cls.getDeclaredMethods()) {
if (m.isInit()) {
Set<CGNode> nodes = cg.getNodes(m.getReference());
for (CGNode n : nodes) {
escapeAnalysisRoots.add(heapModel.getPointerKeyForLocal(n, 1));
}
}
}
}
//
// compute escaping types: all types flowing to escaping roots and
// all types transitively reachable through their fields.
//
Set<InstanceKey> escapingInstanceKeys = HashSetFactory.make();
//
// pass 1: get abstract objects (instance keys) for escaping locations
//
for (PointerKey root : escapeAnalysisRoots) {
OrdinalSet<? extends InstanceKey> objects = pa.getPointsToSet(root);
for (InstanceKey obj : objects) {
escapingInstanceKeys.add(obj);
}
}
//
// passes 2+: get fields of escaping keys, and add pointed-to keys
//
Set<InstanceKey> newKeys = HashSetFactory.make();
do {
newKeys.clear();
for (InstanceKey key : escapingInstanceKeys) {
IClass type = key.getConcreteType();
if (type.isReferenceType()) {
if (type.isArrayClass()) {
if (((ArrayClass) type).getElementClass() != null) {
PointerKey fk = heapModel.getPointerKeyForArrayContents(key);
OrdinalSet<? extends InstanceKey> fobjects = pa.getPointsToSet(fk);
for (InstanceKey fobj : fobjects) {
if (!escapingInstanceKeys.contains(fobj)) {
newKeys.add(fobj);
}
}
}
} else {
Collection<IField> fields = type.getAllInstanceFields();
for (IField f : fields) {
if (f.getFieldTypeReference().isReferenceType()) {
PointerKey fk = heapModel.getPointerKeyForInstanceField(key, f);
OrdinalSet<? extends InstanceKey> fobjects = pa.getPointsToSet(fk);
for (InstanceKey fobj : fobjects) {
if (!escapingInstanceKeys.contains(fobj)) {
newKeys.add(fobj);
}
}
}
}
}
}
}
escapingInstanceKeys.addAll(newKeys);
} while (!newKeys.isEmpty());
//
// get set of types from set of instance keys
//
Set<IClass> escapingTypes = HashSetFactory.make();
for (InstanceKey key : escapingInstanceKeys) {
escapingTypes.add(key.getConcreteType());
}
return escapingTypes;
}
/**
* This main program shows one example use of thread escape analysis: producing a set of fields to
* be monitored for a dynamic race detector. The idea is that any field might have a race with two
* exceptions: final fields do not have races since there are no writes to them, and volatile
* fields have atomic read and write semantics provided by the VM. Hence, this piece of code
* produces a list of all other fields.
*/
public static void main(String[] args)
throws IOException, IllegalArgumentException, CancelException {
String mainClassName = args[0];
Set<JarFile> jars = HashSetFactory.make();
for (int i = 1; i < args.length; i++) {
jars.add(new JarFile(args[i], false));
}
Set<IClass> escapingTypes =
new SimpleThreadEscapeAnalysis(jars, mainClassName).gatherThreadEscapingClasses();
for (IClass cls : escapingTypes) {
if (!cls.isArrayClass()) {
for (IField f : cls.getAllFields()) {
if (!f.isVolatile() && !f.isFinal()) {
System.err.println(f.getReference());
}
}
}
}
}
}
| 11,351
| 33.09009
| 100
|
java
|
WALA
|
WALA-master/core/src/test/java/com/ibm/wala/examples/analysis/dataflow/DataflowTest.java
|
/*
* Copyright (c) 2008 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.examples.analysis.dataflow;
import com.ibm.wala.classLoader.IMethod;
import com.ibm.wala.classLoader.Language;
import com.ibm.wala.core.tests.callGraph.CallGraphTestUtil;
import com.ibm.wala.core.tests.util.TestConstants;
import com.ibm.wala.core.tests.util.WalaTestCase;
import com.ibm.wala.core.util.config.AnalysisScopeReader;
import com.ibm.wala.dataflow.IFDS.ISupergraph;
import com.ibm.wala.dataflow.IFDS.TabulationResult;
import com.ibm.wala.dataflow.graph.BitVectorSolver;
import com.ibm.wala.ipa.callgraph.AnalysisCacheImpl;
import com.ibm.wala.ipa.callgraph.AnalysisOptions;
import com.ibm.wala.ipa.callgraph.AnalysisScope;
import com.ibm.wala.ipa.callgraph.CGNode;
import com.ibm.wala.ipa.callgraph.CallGraph;
import com.ibm.wala.ipa.callgraph.CallGraphBuilder;
import com.ibm.wala.ipa.callgraph.CallGraphBuilderCancelException;
import com.ibm.wala.ipa.callgraph.Entrypoint;
import com.ibm.wala.ipa.callgraph.IAnalysisCacheView;
import com.ibm.wala.ipa.callgraph.impl.Everywhere;
import com.ibm.wala.ipa.callgraph.impl.Util;
import com.ibm.wala.ipa.callgraph.propagation.InstanceKey;
import com.ibm.wala.ipa.cfg.BasicBlockInContext;
import com.ibm.wala.ipa.cfg.ExplodedInterproceduralCFG;
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.IR;
import com.ibm.wala.ssa.SSAOptions;
import com.ibm.wala.ssa.analysis.ExplodedControlFlowGraph;
import com.ibm.wala.ssa.analysis.IExplodedBasicBlock;
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.config.FileOfClasses;
import com.ibm.wala.util.intset.IntIterator;
import com.ibm.wala.util.intset.IntSet;
import java.io.ByteArrayInputStream;
import java.util.ArrayList;
import java.util.List;
import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;
/** Tests of various flow analysis engines. */
public class DataflowTest extends WalaTestCase {
private static AnalysisScope scope;
private static IClassHierarchy cha;
// more aggressive exclusions to avoid library blowup
// in interprocedural tests
private static final String EXCLUSIONS =
"java\\/awt\\/.*\n"
+ "javax\\/swing\\/.*\n"
+ "sun\\/awt\\/.*\n"
+ "sun\\/swing\\/.*\n"
+ "com\\/sun\\/.*\n"
+ "sun\\/.*\n"
+ "org\\/netbeans\\/.*\n"
+ "org\\/openide\\/.*\n"
+ "com\\/ibm\\/crypto\\/.*\n"
+ "com\\/ibm\\/security\\/.*\n"
+ "org\\/apache\\/xerces\\/.*\n"
+ "java\\/security\\/.*\n"
+ "";
@BeforeClass
public static void beforeClass() throws Exception {
scope =
AnalysisScopeReader.instance.readJavaScope(
TestConstants.WALA_TESTDATA, null, DataflowTest.class.getClassLoader());
scope.setExclusions(new FileOfClasses(new ByteArrayInputStream(EXCLUSIONS.getBytes("UTF-8"))));
try {
cha = ClassHierarchyFactory.make(scope);
} catch (ClassHierarchyException e) {
throw new Exception(e);
}
}
/*
* (non-Javadoc)
*
* @see junit.framework.TestCase#tearDown()
*/
@AfterClass
public static void afterClass() throws Exception {
scope = null;
cha = null;
}
@Test
public void testIntraproc1() {
IAnalysisCacheView cache = new AnalysisCacheImpl();
final MethodReference ref =
MethodReference.findOrCreate(
ClassLoaderReference.Application, "Ldataflow/StaticDataflow", "test1", "()V");
IMethod method = cha.resolveMethod(ref);
IR ir = cache.getIRFactory().makeIR(method, Everywhere.EVERYWHERE, SSAOptions.defaultOptions());
ExplodedControlFlowGraph ecfg = ExplodedControlFlowGraph.make(ir);
IntraprocReachingDefs reachingDefs = new IntraprocReachingDefs(ecfg, cha);
BitVectorSolver<IExplodedBasicBlock> solver = reachingDefs.analyze();
for (IExplodedBasicBlock ebb : ecfg) {
if (ebb.getNumber() == 4) {
IntSet out = solver.getOut(ebb).getValue();
Assert.assertEquals(1, out.size());
Assert.assertTrue(out.contains(1));
}
}
}
@Test
public void testIntraproc2() {
IAnalysisCacheView cache = new AnalysisCacheImpl();
final MethodReference ref =
MethodReference.findOrCreate(
ClassLoaderReference.Application, "Ldataflow/StaticDataflow", "test2", "()V");
IMethod method = cha.resolveMethod(ref);
IR ir = cache.getIRFactory().makeIR(method, Everywhere.EVERYWHERE, SSAOptions.defaultOptions());
ExplodedControlFlowGraph ecfg = ExplodedControlFlowGraph.make(ir);
IntraprocReachingDefs reachingDefs = new IntraprocReachingDefs(ecfg, cha);
BitVectorSolver<IExplodedBasicBlock> solver = reachingDefs.analyze();
for (IExplodedBasicBlock ebb : ecfg) {
if (ebb.getNumber() == 10) {
IntSet out = solver.getOut(ebb).getValue();
Assert.assertEquals(2, out.size());
Assert.assertTrue(out.contains(0));
Assert.assertTrue(out.contains(2));
}
}
}
@Test
public void testContextInsensitive()
throws IllegalArgumentException, CallGraphBuilderCancelException {
Iterable<Entrypoint> entrypoints =
com.ibm.wala.ipa.callgraph.impl.Util.makeMainEntrypoints(cha, "Ldataflow/StaticDataflow");
AnalysisOptions options = CallGraphTestUtil.makeAnalysisOptions(scope, entrypoints);
CallGraphBuilder<InstanceKey> builder =
Util.makeZeroOneCFABuilder(Language.JAVA, options, new AnalysisCacheImpl(), cha);
CallGraph cg = builder.makeCallGraph(options, null);
ExplodedInterproceduralCFG icfg = ExplodedInterproceduralCFG.make(cg);
ContextInsensitiveReachingDefs reachingDefs = new ContextInsensitiveReachingDefs(icfg, cha);
BitVectorSolver<BasicBlockInContext<IExplodedBasicBlock>> solver = reachingDefs.analyze();
for (BasicBlockInContext<IExplodedBasicBlock> bb : icfg) {
if (bb.getNode().toString().contains("testInterproc")) {
IExplodedBasicBlock delegate = bb.getDelegate();
if (delegate.getNumber() == 4) {
IntSet solution = solver.getOut(bb).getValue();
IntIterator intIterator = solution.intIterator();
List<Pair<CGNode, Integer>> applicationDefs = new ArrayList<>();
while (intIterator.hasNext()) {
int next = intIterator.next();
final Pair<CGNode, Integer> def = reachingDefs.getNodeAndInstrForNumber(next);
if (def.fst
.getMethod()
.getDeclaringClass()
.getClassLoader()
.getReference()
.equals(ClassLoaderReference.Application)) {
System.out.println(def);
applicationDefs.add(def);
}
}
Assert.assertEquals(2, applicationDefs.size());
}
}
}
}
@Test
public void testContextSensitive() throws IllegalArgumentException, CancelException {
Iterable<Entrypoint> entrypoints =
com.ibm.wala.ipa.callgraph.impl.Util.makeMainEntrypoints(cha, "Ldataflow/StaticDataflow");
AnalysisOptions options = CallGraphTestUtil.makeAnalysisOptions(scope, entrypoints);
CallGraphBuilder<InstanceKey> builder =
Util.makeZeroOneCFABuilder(Language.JAVA, options, new AnalysisCacheImpl(), cha);
CallGraph cg = builder.makeCallGraph(options, null);
ContextSensitiveReachingDefs reachingDefs = new ContextSensitiveReachingDefs(cg);
TabulationResult<BasicBlockInContext<IExplodedBasicBlock>, CGNode, Pair<CGNode, Integer>>
result = reachingDefs.analyze();
ISupergraph<BasicBlockInContext<IExplodedBasicBlock>, CGNode> supergraph =
reachingDefs.getSupergraph();
for (BasicBlockInContext<IExplodedBasicBlock> bb : supergraph) {
if (bb.getNode().toString().contains("testInterproc")) {
IExplodedBasicBlock delegate = bb.getDelegate();
if (delegate.getNumber() == 4) {
IntSet solution = result.getResult(bb);
IntIterator intIterator = solution.intIterator();
List<Pair<CGNode, Integer>> applicationDefs = new ArrayList<>();
while (intIterator.hasNext()) {
int next = intIterator.next();
final Pair<CGNode, Integer> def = reachingDefs.getDomain().getMappedObject(next);
if (def.fst
.getMethod()
.getDeclaringClass()
.getClassLoader()
.getReference()
.equals(ClassLoaderReference.Application)) {
System.out.println(def);
applicationDefs.add(def);
}
}
Assert.assertEquals(1, applicationDefs.size());
}
}
}
}
}
| 9,240
| 39.530702
| 100
|
java
|
WALA
|
WALA-master/core/src/test/java/com/ibm/wala/examples/analysis/dataflow/InitializerTest.java
|
/*
* Copyright (c) 2002 - 2014 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.examples.analysis.dataflow;
import com.ibm.wala.classLoader.IClass;
import com.ibm.wala.classLoader.Language;
import com.ibm.wala.core.tests.callGraph.CallGraphTestUtil;
import com.ibm.wala.core.tests.util.TestConstants;
import com.ibm.wala.core.util.config.AnalysisScopeReader;
import com.ibm.wala.core.util.io.FileProvider;
import com.ibm.wala.dataflow.IFDS.ISupergraph;
import com.ibm.wala.dataflow.IFDS.TabulationResult;
import com.ibm.wala.ipa.callgraph.AnalysisCacheImpl;
import com.ibm.wala.ipa.callgraph.AnalysisOptions;
import com.ibm.wala.ipa.callgraph.AnalysisScope;
import com.ibm.wala.ipa.callgraph.CGNode;
import com.ibm.wala.ipa.callgraph.CallGraph;
import com.ibm.wala.ipa.callgraph.CallGraphBuilder;
import com.ibm.wala.ipa.callgraph.CallGraphBuilderCancelException;
import com.ibm.wala.ipa.callgraph.Entrypoint;
import com.ibm.wala.ipa.callgraph.impl.Util;
import com.ibm.wala.ipa.callgraph.propagation.InstanceKey;
import com.ibm.wala.ipa.cfg.BasicBlockInContext;
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.analysis.IExplodedBasicBlock;
import com.ibm.wala.util.intset.IntIterator;
import com.ibm.wala.util.intset.IntSet;
import java.io.IOException;
import org.junit.Assert;
public class InitializerTest {
public static void main(String[] args) {
AnalysisScope scope = null;
try {
scope =
AnalysisScopeReader.instance.readJavaScope(
TestConstants.WALA_TESTDATA,
new FileProvider().getFile("J2SEClassHierarchyExclusions.txt"),
InitializerTest.class.getClassLoader());
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
IClassHierarchy cha = null;
try {
cha = ClassHierarchyFactory.make(scope);
} catch (ClassHierarchyException e) {
e.printStackTrace();
}
Iterable<Entrypoint> entrypoints =
com.ibm.wala.ipa.callgraph.impl.Util.makeMainEntrypoints(cha, "LstaticInit/TestStaticInit");
AnalysisOptions options = CallGraphTestUtil.makeAnalysisOptions(scope, entrypoints);
CallGraphBuilder<InstanceKey> builder =
Util.makeZeroOneCFABuilder(Language.JAVA, options, new AnalysisCacheImpl(), cha);
CallGraph cg = null;
try {
cg = builder.makeCallGraph(options, null);
} catch (IllegalArgumentException | CallGraphBuilderCancelException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("Start");
StaticInitializer reachingDefs = new StaticInitializer(cg);
TabulationResult<BasicBlockInContext<IExplodedBasicBlock>, CGNode, IClass> result =
reachingDefs.analyze();
ISupergraph<BasicBlockInContext<IExplodedBasicBlock>, CGNode> supergraph =
reachingDefs.getSupergraph();
for (BasicBlockInContext<IExplodedBasicBlock> bb : supergraph) {
if (bb.getNode().toString().contains("doNothing")) {
// System.out.println("Do!");
IExplodedBasicBlock delegate = bb.getDelegate();
if (delegate.getNumber() == 4) {
IntSet solution = result.getResult(bb);
IntIterator intIterator = solution.intIterator();
while (intIterator.hasNext()) {
int next = intIterator.next();
System.out.println(reachingDefs.getDomain().getMappedObject(next));
}
Assert.assertEquals(3, solution.size());
}
}
}
System.out.println("End");
}
}
| 3,964
| 36.40566
| 100
|
java
|
WALA
|
WALA-master/core/src/test/java/com/ibm/wala/util/io/FileProviderTest.java
|
/*
* Copyright (c) 2013 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.util.io;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.matchesPattern;
import static org.junit.Assert.assertEquals;
import com.ibm.wala.core.util.io.FileProvider;
import com.ibm.wala.util.PlatformUtil;
import java.net.MalformedURLException;
import java.net.URL;
import org.junit.Test;
public class FileProviderTest {
@Test
public void testValidFile() throws MalformedURLException {
// setup:
URL url = new URL("file:///c:/my/File.jar");
String expected = "/c:/my/File.jar";
// exercise:
String actual = new FileProvider().filePathFromURL(url);
// verify:
assertEquals(expected, actual);
}
@Test
public void testURLWithInvalidURIChars() throws MalformedURLException {
// setup:
URL url = new URL("file:///[Eclipse]/File.jar");
// exercise:
String actual = new FileProvider().filePathFromURL(url);
// verify:
assertThat(
actual,
PlatformUtil.onWindows()
? matchesPattern("\\A/[A-Z]:/\\[Eclipse]/File.jar\\z")
: equalTo("/[Eclipse]/File.jar"));
}
@Test
public void testURLWithSpace() throws MalformedURLException {
// setup:
URL url = new URL("file:///With%20Space/File.jar");
// exercise:
String actual = new FileProvider().filePathFromURL(url);
// verify:
assertThat(
actual,
PlatformUtil.onWindows()
? matchesPattern("\\A/[A-Z]:/With Space/File\\.jar\\z")
: equalTo("/With Space/File.jar"));
}
}
| 1,953
| 29.061538
| 73
|
java
|
WALA
|
WALA-master/core/src/testFixtures/java/com/ibm/wala/core/tests/ir/AnnotationTest.java
|
/*
* Copyright (c) 2013 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.core.tests.ir;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import com.ibm.wala.classLoader.BytecodeClass;
import com.ibm.wala.classLoader.IBytecodeMethod;
import com.ibm.wala.classLoader.IClass;
import com.ibm.wala.classLoader.IField;
import com.ibm.wala.classLoader.IMethod;
import com.ibm.wala.core.tests.callGraph.CallGraphTestUtil;
import com.ibm.wala.core.tests.util.TestConstants;
import com.ibm.wala.core.tests.util.WalaTestCase;
import com.ibm.wala.core.util.config.AnalysisScopeReader;
import com.ibm.wala.core.util.io.FileProvider;
import com.ibm.wala.core.util.strings.Atom;
import com.ibm.wala.ipa.callgraph.AnalysisScope;
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.shrike.shrikeBT.IInstruction;
import com.ibm.wala.shrike.shrikeCT.InvalidClassFileException;
import com.ibm.wala.types.ClassLoaderReference;
import com.ibm.wala.types.FieldReference;
import com.ibm.wala.types.MethodReference;
import com.ibm.wala.types.Selector;
import com.ibm.wala.types.TypeReference;
import com.ibm.wala.types.annotations.Annotation;
import com.ibm.wala.util.collections.HashSetFactory;
import com.ibm.wala.util.collections.Pair;
import java.io.IOException;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Set;
import org.junit.Test;
public abstract class AnnotationTest extends WalaTestCase {
private final IClassHierarchy cha;
/**
* Should we only check for annotations whose retention is {@link
* java.lang.annotation.RetentionPolicy#RUNTIME}? Useful for d8 on Android, which strips
* everything but runtime retention annotations
*/
private final boolean checkRuntimeRetentionOnly;
protected AnnotationTest(IClassHierarchy cha, boolean checkRuntimeRetentionOnly) {
this.cha = cha;
this.checkRuntimeRetentionOnly = checkRuntimeRetentionOnly;
}
public AnnotationTest(boolean checkRuntimeRetentionOnly)
throws ClassHierarchyException, IOException {
this(makeCHA(), checkRuntimeRetentionOnly);
}
public AnnotationTest() throws ClassHierarchyException, IOException {
this(false);
}
public static IClassHierarchy makeCHA() throws IOException, ClassHierarchyException {
AnalysisScope scope =
AnalysisScopeReader.instance.readJavaScope(
TestConstants.WALA_TESTDATA,
new FileProvider().getFile(CallGraphTestUtil.REGRESSION_EXCLUSIONS),
AnnotationTest.class.getClassLoader());
return ClassHierarchyFactory.make(scope);
}
public static <T> void assertEqualCollections(Collection<T> expected, Collection<T> actual) {
if (expected == null) {
expected = Collections.emptySet();
}
if (actual == null) {
actual = Collections.emptySet();
}
if (expected.size() != actual.size()) {
fail("expected=" + expected + " actual=" + actual);
}
for (T a : expected) {
assertTrue("missing " + a.toString(), actual.contains(a));
}
}
@Test
public void testClassAnnotations1() throws Exception {
TypeReference typeUnderTest =
TypeReference.findOrCreate(
ClassLoaderReference.Application, "Lannotations/AnnotatedClass1");
Collection<Annotation> expectedRuntimeInvisibleAnnotations = HashSetFactory.make();
expectedRuntimeInvisibleAnnotations.add(
Annotation.make(
TypeReference.findOrCreate(
ClassLoaderReference.Application, "Lannotations/RuntimeInvisableAnnotation")));
expectedRuntimeInvisibleAnnotations.add(
Annotation.make(
TypeReference.findOrCreate(
ClassLoaderReference.Application, "Lannotations/DefaultVisableAnnotation")));
Collection<Annotation> expectedRuntimeVisibleAnnotations = HashSetFactory.make();
expectedRuntimeVisibleAnnotations.add(
Annotation.make(
TypeReference.findOrCreate(
ClassLoaderReference.Application, "Lannotations/RuntimeVisableAnnotation")));
testClassAnnotations(
typeUnderTest, expectedRuntimeInvisibleAnnotations, expectedRuntimeVisibleAnnotations);
}
@Test
public void testClassAnnotations2() throws Exception {
TypeReference typeUnderTest =
TypeReference.findOrCreate(
ClassLoaderReference.Application, "Lannotations/AnnotatedClass2");
Collection<Annotation> expectedRuntimeInvisibleAnnotations = HashSetFactory.make();
expectedRuntimeInvisibleAnnotations.add(
Annotation.make(
TypeReference.findOrCreate(
ClassLoaderReference.Application, "Lannotations/RuntimeInvisableAnnotation")));
expectedRuntimeInvisibleAnnotations.add(
Annotation.make(
TypeReference.findOrCreate(
ClassLoaderReference.Application, "Lannotations/RuntimeInvisableAnnotation2")));
Collection<Annotation> expectedRuntimeVisibleAnnotations = HashSetFactory.make();
expectedRuntimeVisibleAnnotations.add(
Annotation.make(
TypeReference.findOrCreate(
ClassLoaderReference.Application, "Lannotations/RuntimeVisableAnnotation")));
expectedRuntimeVisibleAnnotations.add(
Annotation.make(
TypeReference.findOrCreate(
ClassLoaderReference.Application, "Lannotations/RuntimeVisableAnnotation2")));
testClassAnnotations(
typeUnderTest, expectedRuntimeInvisibleAnnotations, expectedRuntimeVisibleAnnotations);
}
private void testClassAnnotations(
TypeReference typeUnderTest,
Collection<Annotation> expectedRuntimeInvisibleAnnotations,
Collection<Annotation> expectedRuntimeVisibleAnnotations)
throws InvalidClassFileException {
IClass classUnderTest = cha.lookupClass(typeUnderTest);
assertNotNull(typeUnderTest.toString() + " not found", classUnderTest);
assertTrue(classUnderTest + " must be BytecodeClass", classUnderTest instanceof BytecodeClass);
BytecodeClass<?> bcClassUnderTest = (BytecodeClass<?>) classUnderTest;
Collection<Annotation> runtimeInvisibleAnnotations = bcClassUnderTest.getAnnotations(true);
Collection<Annotation> runtimeVisibleAnnotations = bcClassUnderTest.getAnnotations(false);
if (!checkRuntimeRetentionOnly) {
assertEqualCollections(expectedRuntimeInvisibleAnnotations, runtimeInvisibleAnnotations);
}
assertEqualCollections(expectedRuntimeVisibleAnnotations, runtimeVisibleAnnotations);
}
@SuppressWarnings("unchecked")
@Test
public void testClassAnnotations3() throws Exception {
TypeReference typeRef =
TypeReference.findOrCreate(
ClassLoaderReference.Application, "Lannotations/AnnotatedClass3");
IClass klass = cha.lookupClass(typeRef);
assertNotNull(typeRef + " must exist", klass);
BytecodeClass<?> shrikeClass = (BytecodeClass<?>) klass;
Collection<Annotation> classAnnotations = shrikeClass.getAnnotations(false);
assertEquals(
"[Annotation type <Application,Lannotations/AnnotationWithParams> {strParam=classStrParam}]",
classAnnotations.toString());
MethodReference methodRefUnderTest =
MethodReference.findOrCreate(typeRef, Selector.make("foo()V"));
IMethod methodUnderTest = cha.resolveMethod(methodRefUnderTest);
assertNotNull(methodRefUnderTest + " not found", methodUnderTest);
assertTrue(
methodUnderTest + " must be IBytecodeMethod", methodUnderTest instanceof IBytecodeMethod);
IBytecodeMethod<IInstruction> bcMethodUnderTest =
(IBytecodeMethod<IInstruction>) methodUnderTest;
Collection<Annotation> runtimeVisibleAnnotations = bcMethodUnderTest.getAnnotations(false);
assertEquals(1, runtimeVisibleAnnotations.size());
Annotation x = runtimeVisibleAnnotations.iterator().next();
assertEquals(
TypeReference.findOrCreate(
ClassLoaderReference.Application, "Lannotations/AnnotationWithParams"),
x.getType());
for (Pair<String, String> n :
new Pair[] {
Pair.make("enumParam", "EnumElementValue [type=Lannotations/AnnotationEnum;, val=VAL1]"),
Pair.make("strArrParam", "ArrayElementValue [vals=[biz, boz]]"),
Pair.make(
"annotParam",
"AnnotationElementValue [type=Lannotations/AnnotationWithSingleParam;, elementValues={value=sdfevs}]"),
Pair.make("strParam", "sdfsevs"),
Pair.make("intParam", "25"),
Pair.make("klassParam", "Ljava/lang/Integer;")
}) {
assertEquals(n.snd, x.getNamedArguments().get(n.fst).toString());
}
}
@Test
public void testClassAnnotations4() throws Exception {
TypeReference typeRef =
TypeReference.findOrCreate(
ClassLoaderReference.Application, "Lannotations/AnnotatedClass4");
FieldReference fieldRefUnderTest =
FieldReference.findOrCreate(
typeRef, Atom.findOrCreateUnicodeAtom("foo"), TypeReference.Int);
IField fieldUnderTest = cha.resolveField(fieldRefUnderTest);
assertNotNull(fieldRefUnderTest + " not found", fieldUnderTest);
Collection<Annotation> annots = fieldUnderTest.getAnnotations();
Collection<Annotation> expectedAnnotations = HashSetFactory.make();
expectedAnnotations.add(
Annotation.make(
TypeReference.findOrCreate(
ClassLoaderReference.Application, "Lannotations/RuntimeVisableAnnotation")));
if (!checkRuntimeRetentionOnly) {
expectedAnnotations.add(
Annotation.make(
TypeReference.findOrCreate(
ClassLoaderReference.Application, "Lannotations/RuntimeInvisableAnnotation")));
}
assertEqualCollections(expectedAnnotations, annots);
}
@Test
public void testParamAnnotations1() throws Exception {
TypeReference typeRef =
TypeReference.findOrCreate(
ClassLoaderReference.Application, "Lannotations/ParameterAnnotations1");
checkParameterAnnots(
typeRef,
"foo(Ljava/lang/String;)V",
new String[] {"Annotation type <Application,Lannotations/RuntimeVisableAnnotation>"});
checkParameterAnnots(
typeRef,
"bar(Ljava/lang/Integer;)V",
new String[] {
"Annotation type <Application,Lannotations/AnnotationWithParams> {annotParam=AnnotationElementValue [type=Lannotations/AnnotationWithSingleParam;, elementValues={value=sdfevs}], enumParam=EnumElementValue [type=Lannotations/AnnotationEnum;, val=VAL1], intParam=25, klassParam=Ljava/lang/Integer;, strArrParam=ArrayElementValue [vals=[biz, boz]], strParam=sdfsevs}"
});
checkParameterAnnots(
typeRef,
"foo2(Ljava/lang/String;Ljava/lang/Integer;)V",
new String[] {"Annotation type <Application,Lannotations/RuntimeVisableAnnotation>"},
checkRuntimeRetentionOnly
? new String[] {}
: new String[] {
"Annotation type <Application,Lannotations/RuntimeInvisableAnnotation>"
});
checkParameterAnnots(
typeRef,
"foo3(Ljava/lang/String;Ljava/lang/Integer;)V",
new String[] {"Annotation type <Application,Lannotations/RuntimeVisableAnnotation>"},
checkRuntimeRetentionOnly
? new String[] {}
: new String[] {
"Annotation type <Application,Lannotations/RuntimeInvisableAnnotation>"
});
checkParameterAnnots(
typeRef,
"foo4(Ljava/lang/String;Ljava/lang/Integer;)V",
checkRuntimeRetentionOnly
? new String[] {"Annotation type <Application,Lannotations/RuntimeVisableAnnotation>"}
: new String[] {
"Annotation type <Application,Lannotations/RuntimeInvisableAnnotation>",
"Annotation type <Application,Lannotations/RuntimeVisableAnnotation>"
},
new String[0]);
}
protected void checkParameterAnnots(
TypeReference typeRef, String selector, String[]... expected) {
MethodReference methodRefUnderTest =
MethodReference.findOrCreate(typeRef, Selector.make(selector));
IMethod methodUnderTest = cha.resolveMethod(methodRefUnderTest);
assertNotNull(methodRefUnderTest + " not found", methodUnderTest);
assertTrue(
methodUnderTest + " must be bytecode method", methodUnderTest instanceof IBytecodeMethod);
IBytecodeMethod<?> IBytecodeMethodUnderTest = (IBytecodeMethod<?>) methodUnderTest;
Collection<Annotation>[] parameterAnnotations =
IBytecodeMethodUnderTest.getParameterAnnotations();
assertEquals(expected.length, parameterAnnotations.length);
for (int i = 0; i < expected.length; i++) {
Set<String> e = HashSetFactory.make();
e.addAll(Arrays.asList(expected[i]));
Set<String> a = HashSetFactory.make();
if (parameterAnnotations[i] != null) {
for (Annotation x : parameterAnnotations[i]) {
a.add(x.toString());
}
}
assertEquals(e + " must be " + a, e, a);
}
}
}
| 13,553
| 40.576687
| 374
|
java
|
WALA
|
WALA-master/core/src/testFixtures/java/com/ibm/wala/core/tests/shrike/DynamicCallGraphTestBase.java
|
/*
* Copyright (c) 2002 - 2014 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.core.tests.shrike;
import com.ibm.wala.core.tests.util.WalaTestCase;
import com.ibm.wala.ipa.callgraph.CGNode;
import com.ibm.wala.ipa.callgraph.CallGraph;
import com.ibm.wala.properties.WalaProperties;
import com.ibm.wala.shrike.cg.OfflineDynamicCallGraph;
import com.ibm.wala.shrike.shrikeBT.analysis.Analyzer.FailureException;
import com.ibm.wala.shrike.shrikeCT.InvalidClassFileException;
import com.ibm.wala.types.ClassLoaderReference;
import com.ibm.wala.types.MethodReference;
import com.ibm.wala.types.Selector;
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.io.TemporaryFile;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Set;
import java.util.StringTokenizer;
import java.util.function.Predicate;
import java.util.zip.GZIPInputStream;
import org.apache.tools.ant.Project;
import org.apache.tools.ant.taskdefs.Java;
import org.apache.tools.ant.types.Path;
import org.junit.Assert;
public abstract class DynamicCallGraphTestBase extends WalaTestCase {
protected boolean testPatchCalls = false;
private boolean instrumentedJarBuilt = false;
private final java.nio.file.Path instrumentedJarLocation;
private final java.nio.file.Path cgLocation;
protected DynamicCallGraphTestBase() {
try {
instrumentedJarLocation = Files.createTempFile("wala-test", ".jar");
instrumentedJarLocation.toFile().deleteOnExit();
cgLocation = Files.createTempFile("cg", ".txt");
cgLocation.toFile().deleteOnExit();
} catch (IOException problem) {
throw new RuntimeException(problem);
}
}
protected void instrument(String testJarLocation)
throws IOException, ClassNotFoundException, InvalidClassFileException, FailureException {
if (!instrumentedJarBuilt) {
System.err.println("core data jar to instrument: " + testJarLocation);
Files.deleteIfExists(instrumentedJarLocation);
String rtJar = null;
for (String jar : WalaProperties.getJ2SEJarFiles()) {
if (jar.endsWith(File.separator + "rt.jar")
|| jar.endsWith(File.separator + "classes.jar")) {
rtJar = jar;
}
}
List<String> args =
new ArrayList<>(Arrays.asList(testJarLocation, "-o", instrumentedJarLocation.toString()));
if (rtJar != null) {
args.addAll(Arrays.asList("--rt-jar", rtJar));
}
if (testPatchCalls) {
args.add("--patch-calls");
}
OfflineDynamicCallGraph.main(args.toArray(new String[0]));
Assert.assertTrue(
"expected to create " + instrumentedJarLocation, Files.exists(instrumentedJarLocation));
instrumentedJarBuilt = true;
}
}
protected void run(String mainClass, String exclusionsFile, String... args)
throws IOException, SecurityException, IllegalArgumentException, InterruptedException {
Project p = new Project();
final File projectDir = Files.createTempDirectory("wala-test").toFile();
projectDir.deleteOnExit();
p.setBaseDir(projectDir);
p.init();
p.fireBuildStarted();
Java childJvm = new Java();
childJvm.setTaskName("test_" + mainClass.replace('.', '_'));
childJvm.setClasspath(
new Path(
p,
getClasspathEntry("shrike")
+ ":"
+ getClasspathEntry("util")
+ ":"
+ instrumentedJarLocation));
childJvm.setClassname(mainClass);
String jvmArgs =
"-noverify -Xmx500M -DdynamicCGFile=" + cgLocation + " -DdynamicCGHandleMissing=true";
if (exclusionsFile != null) {
File tmpFile =
TemporaryFile.urlToFile(
"exclusions.txt", getClass().getClassLoader().getResource(exclusionsFile));
jvmArgs += " -DdynamicCGFilter=" + tmpFile.getCanonicalPath();
}
childJvm.createJvmarg().setLine(jvmArgs);
for (String a : args) {
childJvm.createArg().setValue(a);
}
childJvm.setFailonerror(true);
childJvm.setFork(true);
Files.deleteIfExists(cgLocation);
childJvm.init();
String commandLine = childJvm.getCommandLine().toString();
System.err.println(commandLine);
Process x = Runtime.getRuntime().exec(commandLine, null, new File("build"));
x.waitFor();
Assert.assertTrue("expected to create call graph", Files.exists(cgLocation));
}
interface EdgesTest {
void edgesTest(CallGraph staticCG, CGNode caller, MethodReference callee);
}
private static MethodReference callee(String calleeClass, String calleeMethod) {
return MethodReference.findOrCreate(
TypeReference.findOrCreate(ClassLoaderReference.Application, 'L' + calleeClass),
Selector.make(calleeMethod));
}
protected void checkEdges(CallGraph staticCG) throws IOException {
checkEdges(staticCG, x -> true);
}
protected void checkEdges(CallGraph staticCG, Predicate<MethodReference> filter)
throws IOException {
final Set<Pair<CGNode, CGNode>> edges = HashSetFactory.make();
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.add(x)) {
System.err.println("found expected edge " + caller + " --> " + callee);
}
},
filter);
}
protected void checkNodes(CallGraph staticCG) throws IOException {
checkNodes(staticCG, x -> true);
}
protected void checkNodes(CallGraph staticCG, Predicate<MethodReference> filter)
throws IOException {
final Set<MethodReference> notFound = HashSetFactory.make();
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);
Assert.assertTrue("could not find " + notFound, notFound.isEmpty());
}
protected void check(CallGraph staticCG, EdgesTest test, Predicate<MethodReference> filter)
throws IOException {
int lines = 0;
try (final BufferedReader dynamicEdgesFile =
new BufferedReader(
new InputStreamReader(new GZIPInputStream(Files.newInputStream(cgLocation))))) {
String line;
loop:
while ((line = dynamicEdgesFile.readLine()) != null) {
if (line.startsWith("call to") || line.startsWith("return from")) {
continue;
}
lines++;
StringTokenizer edge = new StringTokenizer(line, "\t");
CGNode caller;
String callerClass = edge.nextToken();
if ("root".equals(callerClass)) {
caller = staticCG.getFakeRootNode();
} else if ("clinit".equals(callerClass)) {
caller = staticCG.getFakeWorldClinitNode();
} else if ("callbacks".equals(callerClass)) {
continue loop;
} else {
String callerMethod = edge.nextToken();
if (callerMethod.startsWith("lambda$")) {
continue loop;
}
MethodReference callerRef =
MethodReference.findOrCreate(
TypeReference.findOrCreate(ClassLoaderReference.Application, 'L' + callerClass),
Selector.make(callerMethod));
Set<CGNode> nodes = staticCG.getNodes(callerRef);
if (!filter.test(callerRef)) {
continue loop;
}
Assert.assertEquals(callerRef.toString(), 1, nodes.size());
caller = nodes.iterator().next();
}
String calleeClass = edge.nextToken();
String calleeMethod = edge.nextToken();
MethodReference callee = callee(calleeClass, calleeMethod);
if (!filter.test(callee)) {
continue loop;
}
test.edgesTest(staticCG, caller, callee);
}
}
Assert.assertTrue("more than one edge", lines > 0);
}
}
| 8,917
| 33.835938
| 100
|
java
|
WALA
|
WALA-master/core/src/testFixtures/java/com/ibm/wala/core/tests/util/WalaTestCase.java
|
/*
* Copyright (c) 2002 - 2006 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.core.tests.util;
import com.ibm.wala.core.util.warnings.Warnings;
import com.ibm.wala.ipa.callgraph.AnalysisCacheImpl;
import com.ibm.wala.ipa.callgraph.IAnalysisCacheView;
import com.ibm.wala.ssa.SSAOptions;
import com.ibm.wala.util.heapTrace.HeapTracer;
import java.io.File;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.stream.Collectors;
import org.junit.After;
import org.junit.Before;
import org.junit.runner.JUnitCore;
/** Simple extension to JUnit test case. */
public abstract class WalaTestCase {
private static final boolean ANALYZE_LEAKS = false;
public static boolean useShortProfile() {
String profile = System.getProperty("com.ibm.wala.junit.profile", "long");
if (profile.equals("short")) {
return true;
} else {
return false;
}
}
@Before
public void setUp() throws Exception {}
@After
public void tearDown() throws Exception {
Warnings.clear();
if (ANALYZE_LEAKS) {
HeapTracer.analyzeLeaks();
}
}
protected IAnalysisCacheView makeAnalysisCache() {
return makeAnalysisCache(SSAOptions.defaultOptions());
}
protected IAnalysisCacheView makeAnalysisCache(SSAOptions ssaOptions) {
return new AnalysisCacheImpl(ssaOptions);
}
/**
* Utility function: each DetoxTestCase subclass can have a main() method that calls this, to
* create a test suite consisting of just this test. Useful when investigating a single failing
* test.
*/
protected static void justThisTest(Class<?> testClass) {
JUnitCore.runClasses(testClass);
}
protected static String getClasspathEntry(String elt) {
final String normalizedElt = Paths.get(elt).normalize().toString();
final String result =
Arrays.stream(System.getProperty("java.class.path").split(File.pathSeparator))
.map(candidate -> Paths.get(candidate).normalize())
.filter(candidate -> candidate.toString().contains(normalizedElt))
.map(
found -> {
final String foundString = found.toString();
return found.toFile().isDirectory()
? foundString + File.separatorChar
: foundString;
})
.collect(Collectors.joining(File.pathSeparator));
assert !result.isEmpty() : "cannot find " + elt;
return result;
}
}
| 2,764
| 31.151163
| 97
|
java
|
WALA
|
WALA-master/core/src/testFixtures/java/com/ibm/wala/tests/util/SlowTests.java
|
package com.ibm.wala.tests.util;
/**
* JUnit category marker for slow tests
*
* <p>Add “{@code -PexcludeSlowTests}” to the Gradle command line for faster test turnaround at the
* expense of worse test coverage.
*/
public interface SlowTests {}
| 250
| 24.1
| 99
|
java
|
WALA
|
WALA-master/core/src/testSubjects/java/annotations/AnnotatedClass1.java
|
/*
* Copyright (c) 2013 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package annotations;
@RuntimeInvisableAnnotation
@RuntimeVisableAnnotation
@DefaultVisableAnnotation
public class AnnotatedClass1 {
@RuntimeVisableAnnotationForMethod
@RuntimeInvisableAnnotationForMethod
public void m1() {}
}
| 602
| 26.409091
| 72
|
java
|
WALA
|
WALA-master/core/src/testSubjects/java/annotations/AnnotatedClass2.java
|
/*
* Copyright (c) 2013 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package annotations;
@RuntimeInvisableAnnotation
@RuntimeInvisableAnnotation2
@RuntimeVisableAnnotation
@RuntimeVisableAnnotation2
public class AnnotatedClass2 {}
| 532
| 28.611111
| 72
|
java
|
WALA
|
WALA-master/core/src/testSubjects/java/annotations/AnnotatedClass3.java
|
/*
* Copyright (c) 2008 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package annotations;
@AnnotationWithParams(strParam = "classStrParam")
public class AnnotatedClass3 {
@AnnotationWithParams(
enumParam = AnnotationEnum.VAL1,
strArrParam = {"biz", "boz"},
annotParam = @AnnotationWithSingleParam("sdfevs"),
strParam = "sdfsevs",
intParam = 25,
klassParam = Integer.class)
public static void foo() {}
@AnnotationWithParams(strArrParam = {})
public static void emptyArray() {}
}
| 824
| 28.464286
| 72
|
java
|
WALA
|
WALA-master/core/src/testSubjects/java/annotations/AnnotatedClass4.java
|
/*
* Copyright (c) 2008 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package annotations;
/** class with annotated fields */
public class AnnotatedClass4 {
@RuntimeInvisableAnnotation @RuntimeVisableAnnotation public static int foo;
}
| 538
| 28.944444
| 78
|
java
|
WALA
|
WALA-master/core/src/testSubjects/java/annotations/AnnotationEnum.java
|
/*
* Copyright (c) 2008 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package annotations;
public enum AnnotationEnum {
VAL1,
VAL2
}
| 436
| 24.705882
| 72
|
java
|
WALA
|
WALA-master/core/src/testSubjects/java/annotations/AnnotationWithParams.java
|
/*
* Copyright (c) 2008 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package annotations;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
@Retention(RetentionPolicy.RUNTIME)
public @interface AnnotationWithParams {
String strParam() default "strdef";
int intParam() default 0;
Class<?> klassParam() default Object.class;
AnnotationEnum enumParam() default AnnotationEnum.VAL2;
String[] strArrParam() default {"foo", "baz"};
int[] intArrParam() default {3, 4};
AnnotationWithSingleParam annotParam() default @AnnotationWithSingleParam("fsf");
}
| 902
| 26.363636
| 83
|
java
|
WALA
|
WALA-master/core/src/testSubjects/java/annotations/AnnotationWithSingleParam.java
|
/*
* Copyright (c) 2008 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package annotations;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
@Retention(RetentionPolicy.RUNTIME)
public @interface AnnotationWithSingleParam {
String value() default "";
}
| 589
| 27.095238
| 72
|
java
|
WALA
|
WALA-master/core/src/testSubjects/java/annotations/DefaultVisableAnnotation.java
|
/*
* Copyright (c) 2013 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package annotations;
public @interface DefaultVisableAnnotation {}
| 436
| 30.214286
| 72
|
java
|
WALA
|
WALA-master/core/src/testSubjects/java/annotations/ParameterAnnotations1.java
|
/*
* Copyright (c) 2013 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package annotations;
public class ParameterAnnotations1 {
public static void foo(@RuntimeVisableAnnotation String s) {}
public static void bar(
@AnnotationWithParams(
enumParam = AnnotationEnum.VAL1,
strArrParam = {"biz", "boz"},
annotParam = @AnnotationWithSingleParam("sdfevs"),
strParam = "sdfsevs",
intParam = 25,
klassParam = Integer.class)
Integer i) {}
public static void foo2(
@RuntimeVisableAnnotation String s, @RuntimeInvisableAnnotation Integer i) {}
public void foo3(@RuntimeVisableAnnotation String s, @RuntimeInvisableAnnotation Integer i) {}
public void foo4(@RuntimeInvisableAnnotation @RuntimeVisableAnnotation String s, Integer i) {}
}
| 1,145
| 32.705882
| 96
|
java
|
WALA
|
WALA-master/core/src/testSubjects/java/annotations/RuntimeInvisableAnnotation.java
|
/*
* Copyright (c) 2013 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package annotations;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
@Retention(RetentionPolicy.CLASS)
public @interface RuntimeInvisableAnnotation {}
| 557
| 30
| 72
|
java
|
WALA
|
WALA-master/core/src/testSubjects/java/annotations/RuntimeInvisableAnnotation2.java
|
/*
* Copyright (c) 2013 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package annotations;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
@Retention(RetentionPolicy.CLASS)
public @interface RuntimeInvisableAnnotation2 {}
| 558
| 30.055556
| 72
|
java
|
WALA
|
WALA-master/core/src/testSubjects/java/annotations/RuntimeInvisableAnnotationForMethod.java
|
/*
* Copyright (c) 2013 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package annotations;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.CLASS)
@Target(ElementType.METHOD)
public @interface RuntimeInvisableAnnotationForMethod {}
| 671
| 31
| 72
|
java
|
WALA
|
WALA-master/core/src/testSubjects/java/annotations/RuntimeVisableAnnotation.java
|
/*
* Copyright (c) 2013 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package annotations;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
@Retention(RetentionPolicy.RUNTIME)
public @interface RuntimeVisableAnnotation {}
| 557
| 30
| 72
|
java
|
WALA
|
WALA-master/core/src/testSubjects/java/annotations/RuntimeVisableAnnotation2.java
|
/*
* Copyright (c) 2013 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package annotations;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
@Retention(RetentionPolicy.RUNTIME)
public @interface RuntimeVisableAnnotation2 {}
| 558
| 30.055556
| 72
|
java
|
WALA
|
WALA-master/core/src/testSubjects/java/annotations/RuntimeVisableAnnotationForMethod.java
|
/*
* Copyright (c) 2013 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package annotations;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface RuntimeVisableAnnotationForMethod {}
| 671
| 31
| 72
|
java
|
WALA
|
WALA-master/core/src/testSubjects/java/annotations/TypeAnnotatedClass1.java
|
/*
* Copyright (c) 2016 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Martin Hecker, KIT - initial implementation
*/
package annotations;
import java.util.List;
import java.util.Set;
public class TypeAnnotatedClass1 extends @TypeAnnotationTypeUse Object {
@TypeAnnotationTypeUse List<Set<@TypeAnnotationTypeUse TypeAnnotatedClass1>> field;
@TypeAnnotationTypeUse
Integer foo(@TypeAnnotationTypeUse int a, @TypeAnnotationTypeUse Object b) {
@TypeAnnotationTypeUse int x = 3;
@TypeAnnotationTypeUse Object y = new Object();
if (y instanceof @TypeAnnotationTypeUse(someKey = "lul") String) {
x = 7;
}
try {
throw new NullPointerException();
} catch (@TypeAnnotationTypeUse RuntimeException e) {
x = 911;
}
return x;
}
}
| 1,030
| 24.775
| 85
|
java
|
WALA
|
WALA-master/core/src/testSubjects/java/annotations/TypeAnnotatedClass2.java
|
/*
* Copyright (c) 2016 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Martin Hecker, KIT - initial implementation
*/
package annotations;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.util.List;
import java.util.Map;
public class TypeAnnotatedClass2 extends @TypeAnnotationTypeUse Object {
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE_USE})
@interface A {}
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE_USE})
@interface B {}
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE_USE})
@interface C {}
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE_USE})
@interface D {}
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE_USE})
@interface E {}
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE_USE})
@interface F {}
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE_USE})
@interface G {}
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE_USE})
@interface H {}
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE_USE})
@interface I {}
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE_USE})
@interface J {}
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE_USE})
@interface K {}
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE_USE})
@interface L {}
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE_USE})
@interface M {}
@A Map<@B ? extends @C String, @D List<@E Object>> field1;
@I String @F [] @G [] @H [] field2;
@A List<@B Comparable<@F Object @C [] @D [] @E []>> field3;
@C Outer.@B Middle.@A Inner field4;
Outer2.Middle<@D Foo.@C Bar>.Inner<@B String @A []> field5;
}
class Outer {
class Middle {
class Inner {}
}
}
class Outer2 {
class Middle<S> {
class Inner<T> {}
}
}
class Foo {
class Bar {}
}
| 2,263
| 22.583333
| 72
|
java
|
WALA
|
WALA-master/core/src/testSubjects/java/annotations/TypeAnnotationTypeUse.java
|
/*
* Copyright (c) 2016 Joana IFC project,
* Programming Paradigms Group,
* Karlsruhe Institute of Technology (KIT).
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* martin.hecker@kit.edu, KIT -
*/
package annotations;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.CLASS)
@Target({ElementType.TYPE_USE})
public @interface TypeAnnotationTypeUse {
String someKey() default "lol";
}
| 756
| 28.115385
| 72
|
java
|
WALA
|
WALA-master/core/src/testSubjects/java/arrayAlias/TestArrayAlias.java
|
/*
* Copyright (c) 2008 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package arrayAlias;
public class TestArrayAlias {
public static void main(String[] args) {
Object[] o = new Integer[10];
testMayAlias1(o, (Integer[]) o);
Object[] o2 = new Object[20];
testMayAlias2(o2, (Object[][]) o2);
testMayAlias3((Integer[]) o, (String[]) o);
}
private static void testMayAlias1(Object[] o, Integer[] o2) {}
private static void testMayAlias2(Object[] o, Object[][] o2) {}
private static void testMayAlias3(Integer[] o, String[] o2) {}
}
| 861
| 28.724138
| 72
|
java
|
WALA
|
WALA-master/core/src/testSubjects/java/arrayAlias/TestZeroLengthArray.java
|
/*
* Copyright (c) 2008 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package arrayAlias;
public class TestZeroLengthArray {
public static void main(String[] args) {
Object[] arr = new Object[0];
// this will throw an exception; use it to test pointer analysis precision
arr[0] = new Object();
}
}
| 614
| 28.285714
| 78
|
java
|
WALA
|
WALA-master/core/src/testSubjects/java/arraybounds/Detectable.java
|
package arraybounds;
/**
* All array accesses in the following class are unnecessary and they will be detected correctly by
* the array bounds analysis.
*
* @author Stephan Gocht {@code <stephan@gobro.de>}
*/
public class Detectable {
private int[] memberArr = new int[5];
/**
* Note: This is correct, even if memberArr is not final!
*
* @return memberArr[i]
*/
public int memberLocalGet(int i) {
int[] arr = memberArr;
if (i >= 0 && i < arr.length) {
return arr[i];
} else {
throw new IllegalArgumentException();
}
}
public int[] constantCreation() {
return new int[] {3, 4, 5};
}
public int get(int i, int[] arr) {
if (i >= 0 && i < arr.length) {
return arr[i];
} else {
throw new IllegalArgumentException();
}
}
public void loop(int[] arr) {
for (int i = 0; i < arr.length; i++) {
arr[i] = 0;
}
}
public boolean equals(int[] a, int[] b) {
int lenA = a.length;
int lenB = b.length;
boolean result;
if (lenA == lenB) {
result = true;
for (int i = 0; i < lenA; i++) {
if (a[i] != b[i]) {
result = false;
}
}
} else {
result = false;
}
return result;
}
public void copy(int[] src, int[] dst) {
int lenSrc = src.length;
int lenDst = dst.length;
if (lenSrc < lenDst) {
for (int i = 0; i < lenSrc; i++) {
dst[i] = src[i];
}
} else {
throw new IllegalArgumentException();
}
}
/** swaps elements of a and b for all i: 0 <= i < min(a.length, b.length) */
public void swapWithMin(int[] a, int[] b) {
final int l1 = a.length;
final int l2 = b.length;
int length;
if (l1 < l2) {
length = l1;
} else {
length = l2;
}
for (int i = 0; i < length; i++) {
int tmp = a[i];
a[i] = b[i];
b[i] = tmp;
}
}
/** Invert the order of all elements of arr with index i: fromIndex <= i < toIndex. */
public void partialInvert(int[] arr, int fromIndex, int toIndex) {
if (fromIndex >= 0 && toIndex <= arr.length && fromIndex < toIndex) {
for (int next = fromIndex; next < toIndex; ++next) {
int tmp = arr[toIndex - 1];
int i;
for (i = toIndex - 1; i > next; --i) {
arr[i] = arr[i - 1];
}
arr[i] = tmp; // i == next
}
}
}
/**
* The constant 3 is stored in a variable. The pi construction for the variable allows to detect,
* that the array access is in bound.
*
* <p>Compare to {@link NotDetectable#dueToConstantPropagation(int[])}
*
* @return arr[3]
*/
public int nonFinalConstant(int[] arr) {
int i = 3;
if (i < arr.length) {
return arr[i];
} else {
throw new IllegalArgumentException();
}
}
/**
* Workaround for {@link NotDetectable#constants(int[])}
*
* <p>Note: It is important, that the variable five, is compared directly to the length, and that
* further computations are performed with this variable.
*
* @return arr[3]
*/
public int constantsWorkaround(int[] arr) {
int five = 5;
if (arr.length > five) {
return arr[five - 2];
} else {
throw new IllegalArgumentException();
}
}
/**
* Actually aliasing is only working, because it is removed during construction by wala.
*
* @return arr[i]
*/
public int aliasing(int i, int[] arr) {
int[] a = arr;
int[] b = arr;
if (0 <= i && i < a.length) {
return b[i];
} else {
throw new IllegalArgumentException();
}
}
public String afterLoop(int[] arr) {
int len = arr.length - 1;
StringBuilder buffer = new StringBuilder();
int zero = 0;
if (zero < arr.length) {
int i = zero;
while (i < len) {
buffer.append(arr[i]);
buffer.append(", ");
i++;
}
buffer.append(arr[i]);
}
return buffer.toString();
}
public static void quickSort(int[] arr, int left, int right) {
if (0 <= left && right <= arr.length && left < right - 1) {
int pivot = arr[left];
int lhs = left + 1;
int rhs = right - 1;
while (lhs < rhs) {
while (arr[lhs] <= pivot && lhs < right - 1) {
lhs++;
}
while (arr[rhs] >= pivot && rhs > left) {
rhs--;
}
if (lhs < rhs) {
int tmp = arr[lhs];
arr[lhs] = arr[rhs];
arr[rhs] = tmp;
}
}
if (arr[lhs] < pivot) {
arr[left] = arr[lhs];
arr[lhs] = pivot;
}
quickSort(arr, left, lhs);
quickSort(arr, lhs, right);
}
}
}
| 4,670
| 21.674757
| 99
|
java
|
WALA
|
WALA-master/core/src/testSubjects/java/arraybounds/NotDetectable.java
|
package arraybounds;
/**
* All array accesses in the following class are unnecessary but they will not be detected correctly
* by the array bounds analysis.
*
* @author Stephan Gocht {@code <stephan@gobro.de>}
*/
public class NotDetectable {
private final int[] memberArr = new int[5];
/**
* Member calls are not supported. See {@link Detectable#memberLocalGet(int)} for workaround.
*
* @return memberArr[i]
*/
public int memberGet(int i) {
if (i >= 0 && i < memberArr.length) {
return memberArr[i];
} else {
throw new IllegalArgumentException();
}
}
private int getLength() {
return memberArr.length;
}
/**
* Interprocedural analysis is not supported.
*
* @return memberArr[i]
*/
public int interproceduralGet(int i) {
if (i >= 0 && i < getLength()) {
return memberArr[i];
} else {
throw new IllegalArgumentException();
}
}
/**
* This example does not work: We know 5 > 3 and sometimes length > 5 > 3. In case of
* variables this conditional relation is resolved by introducing pi nodes. For constants pi nodes
* can be generated, but the pi variables will not be used (maybe due to constant propagation?).
* Additionally 5 != 3, so even if we would use pi-variables for 5, there would be no relation to
* 3: 0 -(5)-> 5, 5 -(-5)-> 0, {5,length} -(0)-> 5', 0 -(3)-> 3, 3 -(-3)-> 0 Given
* the inequality graph above, we know that 5,5',3 are larger than 0 and 5 larger 3 and length is
* larger than 5', but not 5' larger than 3. Which is not always the case in general anyway.
*
* <p>This may be implemented by replacing each use of a constant dominated by a definition of a
* pi of a constant, with a fresh variable, that is connected to the inequality graph accordingly.
*
* <p>For a workaround see {@link Detectable#nonFinalConstant(int[])}
*
* @return arr[3]
*/
public int constants(int[] arr) {
if (arr.length > 5) {
return arr[3];
} else {
throw new IllegalArgumentException();
}
}
/**
* As the variable i is final, constant propagation will prevent the detection (See also {@link
* NotDetectable#constants(int[])}), for a working example see {@link
* Detectable#nonFinalConstant(int[])}.
*
* @return arr[3]
*/
public int dueToConstantPropagation(int[] arr) {
final int i = 3;
if (i < arr.length) {
return arr[i];
} else {
throw new IllegalArgumentException();
}
}
public int indirectComparison(int[] arr) {
int i = 3;
int e = i + 1;
if (e < arr.length) {
return arr[i];
} else {
throw new IllegalArgumentException();
}
}
/**
* Neither modulo, multiplication or division with constants will work.
*
* <p>Note: Any operation can be performed BEFORE comparing a variable to the array length.
*
* @return arr[i]
*/
public int modulo(int[] arr, int i) {
if (0 <= i && i < arr.length) {
return arr[i % 2];
} else {
throw new IllegalArgumentException();
}
}
/**
* Neither subtraction of variables nor inverting variables will work.
*
* <p>Note: Any operation can be performed BEFORE comparing a variable to the array length.
*
* @return arr[i]
*/
public int variableSubtraction(int[] arr, int i) {
if (0 <= i && i < arr.length) {
int i2 = 0 - i;
int i3 = -i2;
return arr[i3];
} else {
throw new IllegalArgumentException();
}
}
/**
* The analysis can not detect, that forward is false every other iteration. So there is a
* positive and a negative loop. The positive loop is bound by the loop condition, while the
* negative loop is unbound, so index might be smaller than zero. This should result in the lower
* bound check beeing necessary.
*
* @return sum of all elements in arr
*/
public int nonMonotounous(int arr[]) {
int index = 0;
int sum = 0;
boolean forward = true;
while (index < arr.length) {
sum += arr[index];
if (forward) {
index += 2;
} else {
index -= 1;
}
forward = !forward;
}
return sum;
}
/** Multidimensional Arrays are not supported yet. */
public int multiDimensional() {
int arr[][] = new int[5][10];
return arr[2][3];
}
}
| 4,362
| 27.331169
| 100
|
java
|
WALA
|
WALA-master/core/src/testSubjects/java/arraybounds/NotInBound.java
|
package arraybounds;
/**
* All array accesses in the following class are necessary and they will be detected correctly by
* the array bounds analysis.
*
* @author Stephan Gocht {@code <stephan@gobro.de>}
*/
public class NotInBound {
public int phiOverwrite(int[] arr, boolean condition) {
if (arr.length > 0) {
int l = arr.length;
if (condition) {
l = 5;
}
return arr[l - 1];
} else {
throw new IllegalArgumentException();
}
}
public void offByOne(int[] arr) {
for (int i = 0; i <= arr.length; i++) {
arr[i] = 0;
}
}
public int unknownLength(int[] arr) {
return arr[4];
}
public int ambiguity(int[] arr1, int[] arr2, int i) {
int[] arr = arr2;
if (0 <= i && i < arr.length) {
arr = arr1;
return arr[i];
} else {
throw new IllegalArgumentException();
}
}
public int innerLoop(int[] arr) {
int sum = 0;
int i = 0;
while (i < arr.length) {
while (i < 6) {
i++;
sum += arr[i];
}
}
return sum;
}
public int comparedWrong(int[] arr, int index) {
if (index > 0 && index > arr.length) {
return arr[index];
} else {
throw new IllegalArgumentException();
}
}
public int nonTrackedOperationIsSafe(int[] arr, int index) {
if (index > 0 && index > arr.length) {
return arr[2 * index];
} else {
throw new IllegalArgumentException();
}
}
public int unboundNegativeLoop(int[] arr, int index) {
int sum = 0;
for (int i = 5; i < arr.length; i--) {
sum += arr[i];
}
return sum;
}
}
| 1,629
| 19.632911
| 97
|
java
|
WALA
|
WALA-master/core/src/testSubjects/java/bug144/A.java
|
package bug144;
import java.util.HashSet;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;
class A {
void m() {
Set<Object> set = new HashSet<>();
Stream<Object> stream = set.parallelStream();
stream.sorted();
stream.collect(Collectors.toList()); // this call forces the error.
}
public static void main(String[] args) {
new A().m();
}
}
| 410
| 19.55
| 71
|
java
|
WALA
|
WALA-master/core/src/testSubjects/java/cell/Cell.java
|
/*
* Copyright (c) 2007 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package cell;
public class Cell<T> {
private T field;
public Cell(T t1) {
field = t1;
}
public void set(T t2) {
this.field = t2;
}
}
| 522
| 20.791667
| 72
|
java
|
WALA
|
WALA-master/core/src/testSubjects/java/cfg/MonitorTest.java
|
/*
* Copyright (c) 2013 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package cfg;
public class MonitorTest {
void sync1() {
Object a = new Object();
synchronized (this) {
synchronized (a) {
dummy();
}
}
}
void sync2() {
Object a = new Object();
synchronized (this) {
//noinspection EmptySynchronizedStatement
synchronized (a) {
// Nothing here.
}
}
}
void sync3() {
Object a = new Object();
Object b = new Object();
Object c = new Object();
synchronized (a) {
synchronized (b) {
synchronized (c) {
dummy();
}
}
}
}
void dummy() {}
}
| 978
| 19.395833
| 72
|
java
|
WALA
|
WALA-master/core/src/testSubjects/java/cfg/exc/inter/CallFieldAccess.java
|
package cfg.exc.inter;
import cfg.exc.intra.B;
import cfg.exc.intra.FieldAccess;
import cfg.exc.intra.FieldAccessDynamic;
public class CallFieldAccess {
static boolean unknown;
public static void main(String[] args) {
unknown = (args.length == 0);
callIfException();
callIfNoException();
callDynamicIfException();
callDynamicIfNoException();
callIf2Exception();
callIf2NoException();
callDynamicIf2Exception();
callDynamicIf2NoException();
callGetException();
callDynamicGetException();
}
static B callIfException() {
return FieldAccess.testIf(unknown, new B(), null);
}
static B callIfNoException() {
return FieldAccess.testIf(unknown, new B(), new B());
}
static B callDynamicIfException() {
FieldAccessDynamic fad = new FieldAccessDynamic();
return fad.testIf(unknown, new B(), null);
}
static B callDynamicIfNoException() {
FieldAccessDynamic fad = new FieldAccessDynamic();
return fad.testIf(unknown, new B(), new B());
}
static B callIf2Exception() {
return FieldAccess.testIf2(unknown, null, null);
}
static B callIf2NoException() {
return FieldAccess.testIf2(unknown, new B(), null);
}
static B callDynamicIf2Exception() {
FieldAccessDynamic fad = new FieldAccessDynamic();
return fad.testIf2(unknown, null, null);
}
static B callDynamicIf2NoException() {
FieldAccessDynamic fad = new FieldAccessDynamic();
return fad.testIf2(unknown, new B(), null);
}
static B callGetException() {
B b = new B();
return FieldAccess.testGet(unknown, b);
}
static B callDynamicGetException() {
FieldAccessDynamic fad = new FieldAccessDynamic();
B b = new B();
return fad.testGet(unknown, b);
}
}
| 1,758
| 23.774648
| 57
|
java
|
WALA
|
WALA-master/core/src/testSubjects/java/cfg/exc/intra/B.java
|
package cfg.exc.intra;
/** @author Martin Hecker */
public class B {
public int f;
public B b;
}
| 102
| 11.875
| 28
|
java
|
WALA
|
WALA-master/core/src/testSubjects/java/cfg/exc/intra/FieldAccess.java
|
/*
* This file is part of the Joana IFC project. It is developed at the Programming Paradigms Group of
* the Karlsruhe Institute of Technology.
*
* <p>For further details on licensing please read the information at http://joana.ipd.kit.edu or
* contact the authors.
*/
package cfg.exc.intra;
public class FieldAccess {
public static B testParam(boolean unknown, B b1, B b2) {
b1 = null;
return b1;
}
public static B testParam2(boolean unknown, B b1, B b2) {
b1.f = 42;
return b1;
}
public static B testIf(boolean unknown, B b1, B b2) {
b1.f = 42;
b2.f = 17;
B b3;
if (unknown) {
b3 = b1;
} else {
b3 = b2;
}
return b3;
}
public static B testIf2(boolean unknown, B b1, B b2) {
b1.f = 42;
B b3;
if (unknown) {
b3 = b1;
} else {
b3 = b2;
}
return b3;
}
public static B testIfContinued(boolean unknown, B b1, B b2, B b4) {
b1.f = 42;
B b3;
if (unknown) {
b3 = b1;
} else {
b3 = b2;
}
if (unknown) {
b1.f = 42;
}
b3.f = 17;
return b2;
}
public static B testIf3(boolean unknown, B b1) {
if (unknown) {
b1.f = 42;
} else {
System.out.println("rofl");
}
return b1;
}
public static B testWhile(boolean unknown, B b1) {
b1.f = 42;
B b3 = null;
while (unknown) {
b3 = b1;
}
return b3;
}
public static B testWhile2(boolean unknown, B b1) {
b1.f = 42;
B b3 = new B();
b3.f = 17;
while (unknown) {
b3 = b1;
}
return b3;
}
public static B testGet(boolean unknown, B b1) {
b1.f = 42;
B b3 = b1.b;
if (unknown) {
b3.f = 17;
}
return b3;
}
public static void main(String[] args) {
B b1 = new B();
B b2 = new B();
final boolean unknown = (args.length == 0);
testIf(unknown, b1, b2);
}
}
| 1,915
| 14.704918
| 100
|
java
|
WALA
|
WALA-master/core/src/testSubjects/java/cfg/exc/intra/FieldAccessDynamic.java
|
/*
* This file is part of the Joana IFC project. It is developed at the Programming Paradigms Group of
* the Karlsruhe Institute of Technology.
*
* <p>For further details on licensing please read the information at http://joana.ipd.kit.edu or
* contact the authors.
*/
package cfg.exc.intra;
public class FieldAccessDynamic {
public B testParam(boolean unknown, B b1, B b2) {
b1 = null;
return b1;
}
public B testParam2(boolean unknown, B b1, B b2) {
b1.f = 42;
return b1;
}
public B testIf(boolean unknown, B b1, B b2) {
b1.f = 42;
b2.f = 17;
B b3;
if (unknown) {
b3 = b1;
} else {
b3 = b2;
}
return b3;
}
public B testIf2(boolean unknown, B b1, B b2) {
b1.f = 42;
B b3;
if (unknown) {
b3 = b1;
} else {
b3 = b2;
}
return b3;
}
public B testIfContinued(boolean unknown, B b1, B b2, B b4) {
b1.f = 42;
B b3;
if (unknown) {
b3 = b1;
} else {
b3 = b2;
}
if (unknown) {
b1.f = 42;
}
b3.f = 17;
return b2;
}
public B testIf3(boolean unknown, B b1) {
if (unknown) {
b1.f = 42;
} else {
System.out.println("rofl");
}
return b1;
}
public B testWhile(boolean unknown, B b1) {
b1.f = 42;
B b3 = null;
while (unknown) {
b3 = b1;
}
return b3;
}
public B testWhile2(boolean unknown, B b1) {
b1.f = 42;
B b3 = new B();
b3.f = 17;
while (unknown) {
b3 = b1;
}
return b3;
}
public B testGet(boolean unknown, B b1) {
b1.f = 42;
B b3 = b1.b;
if (unknown) {
b3.f = 17;
}
return b3;
}
public static void main(String[] args) {
B b1 = new B();
B b2 = new B();
final boolean unknown = (args.length == 0);
FieldAccessDynamic fa = new FieldAccessDynamic();
fa.testIf(unknown, b1, b2);
}
}
| 1,916
| 14.585366
| 100
|
java
|
WALA
|
WALA-master/core/src/testSubjects/java/classConstant/ClassConstant.java
|
/*
* Copyright (c) 2013 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package classConstant;
class ClassConstant {
public static void main(String args[]) {
Class<ClassConstant> x = ClassConstant.class;
x.hashCode();
}
}
| 532
| 25.65
| 72
|
java
|
WALA
|
WALA-master/core/src/testSubjects/java/cornerCases/Abstract1.java
|
/*
* Copyright (c) 2007 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package cornerCases;
/** @author sfink */
public abstract class Abstract1 {
void foo() {}
}
| 464
| 24.833333
| 72
|
java
|
WALA
|
WALA-master/core/src/testSubjects/java/cornerCases/Abstract2.java
|
/*
* Copyright (c) 2007 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package cornerCases;
/** @author sfink */
public abstract class Abstract2 {
void foo() {}
}
| 464
| 24.833333
| 72
|
java
|
WALA
|
WALA-master/core/src/testSubjects/java/cornerCases/AliasNames.java
|
/*
* Copyright (c) 2007 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package cornerCases;
public class AliasNames {
public static void foo(String[] a) {
String s = a[0];
}
}
| 483
| 24.473684
| 72
|
java
|
WALA
|
WALA-master/core/src/testSubjects/java/cornerCases/Concrete2.java
|
/*
* Copyright (c) 2007 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package cornerCases;
/** @author sfink */
public class Concrete2 extends Abstract2 {}
| 455
| 29.4
| 72
|
java
|
WALA
|
WALA-master/core/src/testSubjects/java/cornerCases/Locals.java
|
/*
* Copyright (c) 2007 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package cornerCases;
/**
* @author sfink
* <p>Simple input test for local variable table
*/
public class Locals {
public static void foo(String[] a) {
System.out.println(a);
Object b = a;
System.out.println(b);
}
}
| 608
| 23.36
| 72
|
java
|
WALA
|
WALA-master/core/src/testSubjects/java/cornerCases/Main.java
|
/*
* Copyright (c) 2002 - 2006 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package cornerCases;
import javax.swing.tree.RowMapper;
/**
* @author sfink
* <p>TODO To change the template for this generated type comment go to Window - Preferences -
* Java - Code Style - Code Templates
*/
public class Main {
public static void main(String[] args) {
testCastToString();
}
/** Test bug 38496: propagation of a string constant to a checkcast */
private static void testCastToString() {
Object o = "a constant string";
String s = (String) o;
s.toString();
}
public static class YuckyField {
RowMapper f;
}
/** Bug 38540: type inference crashed on this method when class FontSupport was not found */
public static Object foo() {
getRowMapper();
return new YuckyField().f;
}
public static RowMapper getRowMapper() {
return null;
}
}
| 1,200
| 24.020833
| 98
|
java
|
WALA
|
WALA-master/core/src/testSubjects/java/cornerCases/TryFinally.java
|
/*
* Copyright (c) 2009 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package cornerCases;
import java.io.BufferedInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
public class TryFinally {
public void test1(InputStream i1, InputStream i2) throws IOException {
BufferedInputStream in = new BufferedInputStream(i1);
try {
FileOutputStream zipOut = new FileOutputStream("someFile.txt");
try {
zipOut.write(0);
} finally {
zipOut.close();
}
} finally {
in.close();
}
}
}
| 887
| 25.117647
| 72
|
java
|
WALA
|
WALA-master/core/src/testSubjects/java/cornerCases/YuckyInterface.java
|
/*
* Copyright (c) 2007 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package cornerCases;
import javax.swing.tree.RowMapper;
/**
* @author sfink
* <p>When analyzed with Java60RegressionExclusions exclusions, the superinterface RowMapper
* should not be found because we exclude javax.swing.*
*/
public interface YuckyInterface extends RowMapper {}
| 661
| 30.52381
| 96
|
java
|
WALA
|
WALA-master/core/src/testSubjects/java/cpa/CPATest1.java
|
package cpa;
public class CPATest1 {
protected abstract static class N {
abstract N op(N other);
}
public static class I extends N {
int I;
I(int i) {
this.I = i;
}
@Override
N op(N other) {
if (other instanceof I) {
return new I(I + ((I) other).I);
} else {
return new F(I + ((F) other).F);
}
}
}
public static class F extends N {
double F;
public F(double f) {
F = f;
}
@Override
N op(N other) {
if (other instanceof I) {
return new F(F + ((I) other).I);
} else {
return new F(F + ((F) other).F);
}
}
}
public static N id(N x) {
return x;
}
public static void main(String[] args) {
F f = new F(3.4);
I i = new I(7);
F r1 = (F) id(f.op(f));
F r2 = (F) id(f.op(i));
I r3 = (I) id(i.op(f));
I r4 = (I) id(i.op(i));
}
}
| 908
| 15.232143
| 42
|
java
|
WALA
|
WALA-master/core/src/testSubjects/java/cpa/CPATest2.java
|
package cpa;
public class CPATest2 {
protected abstract static class N {
abstract N op(int x, N other);
}
public static class I extends N {
int I;
I(int i) {
this.I = i;
}
@Override
N op(int x, N other) {
if (other instanceof I) {
return new I(I + ((I) other).I);
} else {
return new F(I + ((F) other).F);
}
}
}
public static class F extends N {
double F;
public F(double f) {
F = f;
}
@Override
N op(int x, N other) {
if (other instanceof I) {
return new F(F + ((I) other).I);
} else {
return new F(F + ((F) other).F);
}
}
}
public static N id(N x, int i) {
return x;
}
public static void main(String[] args) {
F f = new F(3.4);
I i = new I(7);
F r1 = (F) id(f.op(0, f), 0);
F r2 = (F) id(f.op(0, i), 0);
I r3 = (I) id(i.op(0, f), 0);
I r4 = (I) id(i.op(0, i), 0);
}
}
| 960
| 16.160714
| 42
|
java
|
WALA
|
WALA-master/core/src/testSubjects/java/dataflow/StaticDataflow.java
|
/*
* Copyright (c) 2010 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package dataflow;
/** test cases for dataflow analysis involving static fields. */
public class StaticDataflow {
static int f;
static int g;
public static void test1() {
f = 3;
f = 3;
}
public static void test2() {
f = 4;
g = 3;
if (f == 5) {
g = 2;
} else {
g = 7;
}
}
public static void main(String[] args) {
testInterproc();
}
private static void testInterproc() {
f = 3;
m();
g = 4;
m();
}
private static void m() {
f = 2;
}
}
| 895
| 16.92
| 72
|
java
|
WALA
|
WALA-master/core/src/testSubjects/java/defaultMethods/DefaultMethods.java
|
package defaultMethods;
public class DefaultMethods {
private static class Test1 implements Interface1 {}
private static class Test2 implements Interface2 {}
private static class Test3 implements Interface1, Interface2 {
@Override
public int silly() {
return 3;
}
}
public static void main(String[] args) {
int v1 = (new Test1().silly());
int v2 = (new Test2().silly());
int v3 = (new Test3().silly());
}
}
| 454
| 19.681818
| 64
|
java
|
WALA
|
WALA-master/core/src/testSubjects/java/defaultMethods/Interface1.java
|
package defaultMethods;
public interface Interface1 {
default int silly() {
return 1;
}
}
| 100
| 10.222222
| 29
|
java
|
WALA
|
WALA-master/core/src/testSubjects/java/defaultMethods/Interface2.java
|
package defaultMethods;
public interface Interface2 {
default int silly() {
return 2;
}
}
| 100
| 10.222222
| 29
|
java
|
WALA
|
WALA-master/core/src/testSubjects/java/demandpa/A.java
|
/*
* This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html.
*
* This file is a derivative of code released by the University of
* California under the terms listed below.
*
* Refinement Analysis Tools is Copyright (c) 2007 The Regents of the
* University of California (Regents). Provided that this notice and
* the following two paragraphs are included in any distribution of
* Refinement Analysis Tools or its derivative work, Regents agrees
* not to assert any of Regents' copyright rights in Refinement
* Analysis Tools against recipient for recipient's reproduction,
* preparation of derivative works, public display, public
* performance, distribution or sublicensing of Refinement Analysis
* Tools and derivative works, in source code and object code form.
* This agreement not to assert does not confer, by implication,
* estoppel, or otherwise any license or rights in any intellectual
* property of Regents, including, but not limited to, any patents
* of Regents or Regents' employees.
*
* IN NO EVENT SHALL REGENTS BE LIABLE TO ANY PARTY FOR DIRECT,
* INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES,
* INCLUDING LOST PROFITS, ARISING OUT OF THE USE OF THIS SOFTWARE
* AND ITS DOCUMENTATION, EVEN IF REGENTS HAS BEEN ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* REGENTS SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE AND FURTHER DISCLAIMS ANY STATUTORY
* WARRANTY OF NON-INFRINGEMENT. THE SOFTWARE AND ACCOMPANYING
* DOCUMENTATION, IF ANY, PROVIDED HEREUNDER IS PROVIDED "AS
* IS". REGENTS HAS NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT,
* UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
*/
package demandpa;
class A {
Object f;
Object foo() {
return new Integer(3);
}
public Object getF() {
return f;
}
public void setF(Object f) {
this.f = f;
}
}
| 2,107
| 36.642857
| 72
|
java
|
WALA
|
WALA-master/core/src/testSubjects/java/demandpa/ArraySet.java
|
/*
* This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html.
*
* This file is a derivative of code released by the University of
* California under the terms listed below.
*
* Refinement Analysis Tools is Copyright (c) 2007 The Regents of the
* University of California (Regents). Provided that this notice and
* the following two paragraphs are included in any distribution of
* Refinement Analysis Tools or its derivative work, Regents agrees
* not to assert any of Regents' copyright rights in Refinement
* Analysis Tools against recipient for recipient's reproduction,
* preparation of derivative works, public display, public
* performance, distribution or sublicensing of Refinement Analysis
* Tools and derivative works, in source code and object code form.
* This agreement not to assert does not confer, by implication,
* estoppel, or otherwise any license or rights in any intellectual
* property of Regents, including, but not limited to, any patents
* of Regents or Regents' employees.
*
* IN NO EVENT SHALL REGENTS BE LIABLE TO ANY PARTY FOR DIRECT,
* INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES,
* INCLUDING LOST PROFITS, ARISING OUT OF THE USE OF THIS SOFTWARE
* AND ITS DOCUMENTATION, EVEN IF REGENTS HAS BEEN ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* REGENTS SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE AND FURTHER DISCLAIMS ANY STATUTORY
* WARRANTY OF NON-INFRINGEMENT. THE SOFTWARE AND ACCOMPANYING
* DOCUMENTATION, IF ANY, PROVIDED HEREUNDER IS PROVIDED "AS
* IS". REGENTS HAS NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT,
* UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
*/
package demandpa;
class ArraySet {
static void foo() {}
Object[] elems = new Object[10];
void add(Object o) {
elems[0] = o;
}
Object get() {
return elems[0];
}
Iter iterator() {
return new ArraySetIter();
}
class ArraySetIter implements Iter {
@Override
public Object next() {
return elems[0];
}
}
}
| 2,275
| 34.015385
| 72
|
java
|
WALA
|
WALA-master/core/src/testSubjects/java/demandpa/B.java
|
/*
* This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html.
*
* This file is a derivative of code released by the University of
* California under the terms listed below.
*
* Refinement Analysis Tools is Copyright (c) 2007 The Regents of the
* University of California (Regents). Provided that this notice and
* the following two paragraphs are included in any distribution of
* Refinement Analysis Tools or its derivative work, Regents agrees
* not to assert any of Regents' copyright rights in Refinement
* Analysis Tools against recipient for recipient's reproduction,
* preparation of derivative works, public display, public
* performance, distribution or sublicensing of Refinement Analysis
* Tools and derivative works, in source code and object code form.
* This agreement not to assert does not confer, by implication,
* estoppel, or otherwise any license or rights in any intellectual
* property of Regents, including, but not limited to, any patents
* of Regents or Regents' employees.
*
* IN NO EVENT SHALL REGENTS BE LIABLE TO ANY PARTY FOR DIRECT,
* INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES,
* INCLUDING LOST PROFITS, ARISING OUT OF THE USE OF THIS SOFTWARE
* AND ITS DOCUMENTATION, EVEN IF REGENTS HAS BEEN ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* REGENTS SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE AND FURTHER DISCLAIMS ANY STATUTORY
* WARRANTY OF NON-INFRINGEMENT. THE SOFTWARE AND ACCOMPANYING
* DOCUMENTATION, IF ANY, PROVIDED HEREUNDER IS PROVIDED "AS
* IS". REGENTS HAS NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT,
* UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
*/
package demandpa;
class B extends A {
@Override
Object foo() {
return new Float(4);
}
}
| 2,017
| 42.869565
| 72
|
java
|
WALA
|
WALA-master/core/src/testSubjects/java/demandpa/DemandPATestUtil.java
|
/*
* This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html.
*
* This file is a derivative of code released by the University of
* California under the terms listed below.
*
* Refinement Analysis Tools is Copyright (c) 2007 The Regents of the
* University of California (Regents). Provided that this notice and
* the following two paragraphs are included in any distribution of
* Refinement Analysis Tools or its derivative work, Regents agrees
* not to assert any of Regents' copyright rights in Refinement
* Analysis Tools against recipient for recipient's reproduction,
* preparation of derivative works, public display, public
* performance, distribution or sublicensing of Refinement Analysis
* Tools and derivative works, in source code and object code form.
* This agreement not to assert does not confer, by implication,
* estoppel, or otherwise any license or rights in any intellectual
* property of Regents, including, but not limited to, any patents
* of Regents or Regents' employees.
*
* IN NO EVENT SHALL REGENTS BE LIABLE TO ANY PARTY FOR DIRECT,
* INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES,
* INCLUDING LOST PROFITS, ARISING OUT OF THE USE OF THIS SOFTWARE
* AND ITS DOCUMENTATION, EVEN IF REGENTS HAS BEEN ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* REGENTS SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE AND FURTHER DISCLAIMS ANY STATUTORY
* WARRANTY OF NON-INFRINGEMENT. THE SOFTWARE AND ACCOMPANYING
* DOCUMENTATION, IF ANY, PROVIDED HEREUNDER IS PROVIDED "AS
* IS". REGENTS HAS NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT,
* UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
*/
package demandpa;
/**
* utility functions for identifying interesting variables in tests and making otherwise unused
* variables used
*
* @author manu
*/
public class DemandPATestUtil {
public static void makeVarUsed(Object o) {}
public static void testThisVar(Object o) {}
}
| 2,206
| 41.442308
| 95
|
java
|
WALA
|
WALA-master/core/src/testSubjects/java/demandpa/DummyHashMap.java
|
/*
* Copyright (c) 2008 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package demandpa;
/** doesn't actually work; just for testing pointer analysis */
public class DummyHashMap {
Object[] keys = new Object[10];
Object[] values = new Object[10];
public void put(Object object, Object object2) {
int ind = object.hashCode() % keys.length;
keys[ind] = object;
values[ind] = object2;
}
public Iter keyIter() {
return new Iter() {
@Override
public Object next() {
return keys[0];
}
};
}
public Iter valuesIter() {
return new Iter() {
@Override
public Object next() {
return values[0];
}
};
}
public Object get(Object key1) {
return values[0];
}
private Iter keyOrValueIter(int type) {
return type == 0 ? keyIter() : valuesIter();
}
public Iter elements() {
return keyOrValueIter(-1);
}
}
| 1,213
| 19.931034
| 72
|
java
|
WALA
|
WALA-master/core/src/testSubjects/java/demandpa/DummyHashSet.java
|
/*
* Copyright (c) 2008 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package demandpa;
public class DummyHashSet {
private final DummyHashMap hashMap = new DummyHashMap();
public void add(Object object) {
hashMap.put(object, object);
}
public Iter iterator() {
return hashMap.keyIter();
}
}
| 612
| 23.52
| 72
|
java
|
WALA
|
WALA-master/core/src/testSubjects/java/demandpa/DummyLinkedList.java
|
/*
* Copyright (c) 2008 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package demandpa;
public class DummyLinkedList {
static class Element {
Element next;
Object data;
}
Element head = null;
public void add(Object o) {
if (head == null) {
head = new Element();
head.data = o;
} else {
Element tmp = head;
while (tmp.next != null) {
tmp = tmp.next;
}
Element newElement = new Element();
newElement.data = o;
tmp.next = newElement;
}
}
public Object get(int ind) {
Element tmp = head;
for (int i = 0; i < ind; i++) {
tmp = tmp.next;
}
return tmp.data;
}
public Iter iterator() {
return new Iter() {
@Override
public Object next() {
// just return some arbitrary element, from the point of view of flow-insensitive points-to
// analysis
Element tmp = head;
while (tmp.data == tmp.next) { // shouldn't be able to interpret this condition
tmp = tmp.next;
}
return tmp.data;
}
};
}
}
| 1,384
| 21.704918
| 99
|
java
|
WALA
|
WALA-master/core/src/testSubjects/java/demandpa/FlowsToTestArraySetIter.java
|
/*
* Copyright (c) 2008 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package demandpa;
/** @author manu */
public class FlowsToTestArraySetIter {
public static void main(String[] args) {
ArraySet s1 = new ArraySet();
ArraySet s2 = new ArraySet();
s1.add(new FlowsToType());
s2.add(new B());
A a = (A) s1.iterator().next();
B b = (B) s2.iterator().next();
DemandPATestUtil.makeVarUsed(b);
DemandPATestUtil.makeVarUsed(a);
}
}
| 762
| 27.259259
| 72
|
java
|
WALA
|
WALA-master/core/src/testSubjects/java/demandpa/FlowsToTestFields.java
|
/*
* Copyright (c) 2008 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package demandpa;
/** @author manu */
public class FlowsToTestFields {
public static void main(String[] args) {
Object o1 = new FlowsToType();
Object o2 = new Object();
A a1 = new A();
A a2 = new A();
a1.f = o1;
a2.f = o2;
Object o3 = a1.f;
Object o4 = a2.f;
DemandPATestUtil.makeVarUsed(o3);
DemandPATestUtil.makeVarUsed(o4);
}
}
| 745
| 24.724138
| 72
|
java
|
WALA
|
WALA-master/core/src/testSubjects/java/demandpa/FlowsToTestFieldsHarder.java
|
/*
* Copyright (c) 2008 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package demandpa;
/** @author manu */
public class FlowsToTestFieldsHarder {
public static void main(String[] args) {
Object o1 = new FlowsToType();
A a1 = new A();
a1.f = o1;
A a2 = new A();
a2.f = a1;
A a3 = (A) a2.f;
Object o2 = a3.f;
DemandPATestUtil.makeVarUsed(o2);
}
}
| 682
| 24.296296
| 72
|
java
|
WALA
|
WALA-master/core/src/testSubjects/java/demandpa/FlowsToTestHashSet.java
|
/*
* Copyright (c) 2008 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package demandpa;
/** @author manu */
public class FlowsToTestHashSet {
public static void main(String[] args) {
DummyHashSet s1 = new DummyHashSet();
DummyHashSet s2 = new DummyHashSet();
s1.add(new FlowsToType());
s2.add(new Object());
Object o1 = s1.iterator().next();
Object o2 = s2.iterator().next();
DemandPATestUtil.makeVarUsed(o1);
DemandPATestUtil.makeVarUsed(o2);
}
}
| 784
| 28.074074
| 72
|
java
|
WALA
|
WALA-master/core/src/testSubjects/java/demandpa/FlowsToTestId.java
|
/*
* Copyright (c) 2008 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package demandpa;
/** @author manu */
public class FlowsToTestId {
static Object id(Object o) {
return o;
}
public static void main(String[] args) {
Object o1 = new FlowsToType();
Object o2 = new Object();
Object o3 = id(o1);
Object o4 = id(o2);
DemandPATestUtil.makeVarUsed(o3);
DemandPATestUtil.makeVarUsed(o4);
}
}
| 725
| 24.034483
| 72
|
java
|
WALA
|
WALA-master/core/src/testSubjects/java/demandpa/FlowsToTestLocals.java
|
/*
* Copyright (c) 2008 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package demandpa;
public class FlowsToTestLocals {
public static void main(String[] args) {
Object x = new FlowsToType();
DemandPATestUtil.makeVarUsed(x);
}
}
| 541
| 26.1
| 72
|
java
|
WALA
|
WALA-master/core/src/testSubjects/java/demandpa/FlowsToType.java
|
/*
* Copyright (c) 2008 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package demandpa;
/**
* A dummy type used for testing flows-to queries.
*
* @author manu
*/
public class FlowsToType {}
| 493
| 25
| 72
|
java
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.