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/main/java/com/ibm/wala/ipa/callgraph/propagation/FilteredPointerKey.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.ipa.callgraph.propagation; import com.ibm.wala.classLoader.IClass; import com.ibm.wala.classLoader.IMethod; import com.ibm.wala.ipa.callgraph.ContextItem; import com.ibm.wala.util.intset.IntSet; import com.ibm.wala.util.intset.IntSetAction; import com.ibm.wala.util.intset.IntSetUtil; import com.ibm.wala.util.intset.MutableIntSet; import java.util.Arrays; /** A {@link PointerKey} which carries a type filter, used during pointer analysis */ public interface FilteredPointerKey extends PointerKey { interface TypeFilter extends ContextItem { boolean addFiltered(PropagationSystem system, PointsToSetVariable L, PointsToSetVariable R); boolean addInverseFiltered( PropagationSystem system, PointsToSetVariable L, PointsToSetVariable R); boolean isRootFilter(); } class SingleClassFilter implements TypeFilter { private final IClass concreteType; public SingleClassFilter(IClass concreteType) { this.concreteType = concreteType; } @Override public String toString() { return "SingleClassFilter: " + concreteType; } public IClass getConcreteType() { return concreteType; } @Override public int hashCode() { return concreteType.hashCode(); } @Override public boolean equals(Object o) { return (o instanceof SingleClassFilter) && ((SingleClassFilter) o).getConcreteType().equals(concreteType); } @Override public boolean addFiltered( PropagationSystem system, PointsToSetVariable L, PointsToSetVariable R) { IntSet f = system.getInstanceKeysForClass(concreteType); return (f == null) ? false : L.addAllInIntersection(R, f); } @Override public boolean addInverseFiltered( PropagationSystem system, PointsToSetVariable L, PointsToSetVariable R) { IntSet f = system.getInstanceKeysForClass(concreteType); // SJF: this is horribly inefficient. we really don't want to do // diffs in here. TODO: fix it. probably keep not(f) cached and // use addAllInIntersection return (f == null) ? L.addAll(R) : L.addAll(IntSetUtil.diff(R.getValue(), f)); } @Override public boolean isRootFilter() { return concreteType.equals(concreteType.getClassHierarchy().getRootClass()); } } class MultipleClassesFilter implements TypeFilter { private final IClass[] concreteType; public MultipleClassesFilter(IClass[] concreteType) { this.concreteType = concreteType; } @Override public String toString() { return "MultipleClassesFilter: " + Arrays.toString(concreteType); } public IClass[] getConcreteTypes() { return concreteType; } @Override public int hashCode() { return concreteType[0].hashCode(); } @Override public boolean equals(Object o) { if (!(o instanceof MultipleClassesFilter)) { return false; } MultipleClassesFilter f = (MultipleClassesFilter) o; if (concreteType.length != f.concreteType.length) { return false; } for (int i = 0; i < concreteType.length; i++) { if (!concreteType[i].equals(f.concreteType[i])) { return false; } } return true; } private IntSet bits(PropagationSystem system) { IntSet f = null; for (IClass cls : concreteType) { if (f == null) { f = system.getInstanceKeysForClass(cls); } else { f = f.union(system.getInstanceKeysForClass(cls)); } } return f; } @Override public boolean addFiltered( PropagationSystem system, PointsToSetVariable L, PointsToSetVariable R) { IntSet f = bits(system); return (f == null) ? false : L.addAllInIntersection(R, f); } @Override public boolean addInverseFiltered( PropagationSystem system, PointsToSetVariable L, PointsToSetVariable R) { IntSet f = bits(system); // SJF: this is horribly inefficient. we really don't want to do // diffs in here. TODO: fix it. probably keep not(f) cached and // use addAllInIntersection return (f == null) ? L.addAll(R) : L.addAll(IntSetUtil.diff(R.getValue(), f)); } @Override public boolean isRootFilter() { return concreteType.length == 1 && concreteType[0].getClassHierarchy().getRootClass().equals(concreteType[0]); } } class SingleInstanceFilter implements TypeFilter { private final InstanceKey concreteType; public SingleInstanceFilter(InstanceKey concreteType) { this.concreteType = concreteType; } @Override public String toString() { return "SingleInstanceFilter: " + concreteType + " (" + concreteType.getClass() + ')'; } public InstanceKey getInstance() { return concreteType; } @Override public int hashCode() { return concreteType.hashCode(); } @Override public boolean equals(Object o) { return (o instanceof SingleInstanceFilter) && ((SingleInstanceFilter) o).getInstance().equals(concreteType); } @Override public boolean addFiltered( PropagationSystem system, PointsToSetVariable L, PointsToSetVariable R) { int idx = system.findOrCreateIndexForInstanceKey(concreteType); if (R.contains(idx)) { return L.add(idx); } return false; } @Override public boolean addInverseFiltered( PropagationSystem system, PointsToSetVariable L, PointsToSetVariable R) { int idx = system.findOrCreateIndexForInstanceKey(concreteType); if (!R.contains(idx) || L.contains(idx)) { return L.addAll(R); } else { MutableIntSet copy = IntSetUtil.makeMutableCopy(R.getValue()); copy.remove(idx); return L.addAll(copy); } } @Override public boolean isRootFilter() { return false; } } class TargetMethodFilter implements TypeFilter { private final IMethod targetMethod; public TargetMethodFilter(IMethod targetMethod) { this.targetMethod = targetMethod; } @Override public String toString() { return "TargetMethodFilter: " + targetMethod; } public IMethod getMethod() { return targetMethod; } @Override public int hashCode() { return targetMethod.hashCode(); } @Override public boolean equals(Object o) { return (o instanceof TargetMethodFilter) && ((TargetMethodFilter) o).getMethod().equals(targetMethod); } private class UpdateAction implements IntSetAction { private boolean result = false; private final PointsToSetVariable L; private final PropagationSystem system; private final boolean sense; private UpdateAction(PropagationSystem system, PointsToSetVariable L, boolean sense) { this.L = L; this.sense = sense; this.system = system; } @Override public void act(int i) { InstanceKey I = system.getInstanceKey(i); IClass C = I.getConcreteType(); if ((C.getMethod(targetMethod.getSelector()) == targetMethod) == sense) { if (L.add(i)) { result = true; } } } } @Override public boolean addFiltered( PropagationSystem system, PointsToSetVariable L, PointsToSetVariable R) { if (R.getValue() == null) { return false; } else { UpdateAction act = new UpdateAction(system, L, true); R.getValue().foreach(act); return act.result; } } @Override public boolean addInverseFiltered( PropagationSystem system, PointsToSetVariable L, PointsToSetVariable R) { if (R.getValue() == null) { return false; } else { UpdateAction act = new UpdateAction(system, L, false); R.getValue().foreach(act); return act.result; } } @Override public boolean isRootFilter() { return false; } } /** * @return the class which should govern filtering of instances to which this pointer points, or * null if no filtering needed */ TypeFilter getTypeFilter(); }
8,603
26.576923
98
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/ipa/callgraph/propagation/HeapModel.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.ipa.callgraph.propagation; import com.ibm.wala.ipa.cha.IClassHierarchy; import java.util.Iterator; /** A {@link HeapModel} embodies how a pointer analysis abstracts heap locations. */ public interface HeapModel extends InstanceKeyFactory, PointerKeyFactory { /** @return an Iterator of all PointerKeys that are modeled. */ Iterator<PointerKey> iteratePointerKeys(); /** @return the governing class hierarchy for this heap model */ IClassHierarchy getClassHierarchy(); }
878
34.16
84
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/ipa/callgraph/propagation/IPointerOperator.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.ipa.callgraph.propagation; /** An operator in pointer analysis constraints. */ public interface IPointerOperator { /** Is the operator complex; i.e., might it give rise to new constraints? */ boolean isComplex(); }
617
31.526316
78
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/ipa/callgraph/propagation/IPointsToSolver.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.ipa.callgraph.propagation; import com.ibm.wala.util.CancelException; import com.ibm.wala.util.MonitorUtil.IProgressMonitor; /** Basic interface for a pointer analysis solver. */ public interface IPointsToSolver { void solve(IProgressMonitor monitor) throws IllegalArgumentException, CancelException; }
703
32.52381
88
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/ipa/callgraph/propagation/InstanceFieldKey.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.ipa.callgraph.propagation; import com.ibm.wala.classLoader.IField; /** An pointer key which represents a unique set for a field associated with a set of instances. */ public class InstanceFieldKey extends AbstractFieldPointerKey { private final IField field; public InstanceFieldKey(InstanceKey instance, IField field) { super(instance); if (field == null) { throw new IllegalArgumentException("field is null"); } if (instance == null) { throw new IllegalArgumentException("instance is null"); } this.field = field; } @Override public boolean equals(Object obj) { if (obj instanceof InstanceFieldKey) { if (obj.getClass().equals(getClass())) { InstanceFieldKey other = (InstanceFieldKey) obj; boolean result = field.equals(other.field) && instance.equals(other.instance); return result; } else { return false; } } else { return false; } } @Override public int hashCode() { return 6229 * field.hashCode() + instance.hashCode(); } @Override public String toString() { return "[" + instance + ',' + field + ']'; } public IField getField() { return field; } }
1,605
25.327869
99
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/ipa/callgraph/propagation/InstanceFieldKeyWithFilter.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.ipa.callgraph.propagation; import com.ibm.wala.classLoader.IClass; import com.ibm.wala.classLoader.IField; import com.ibm.wala.ipa.cha.IClassHierarchy; import com.ibm.wala.types.TypeReference; /** an instance field pointer key key that carries a type filter */ public class InstanceFieldKeyWithFilter extends InstanceFieldKey implements FilteredPointerKey { private final IClass filter; public InstanceFieldKeyWithFilter(IClassHierarchy cha, InstanceKey instance, IField field) { super(instance, field); if (field == null) { throw new IllegalArgumentException("field is null"); } if (cha == null) { throw new IllegalArgumentException("cha is null"); } IClass fieldType = cha.lookupClass(field.getFieldTypeReference()); if (fieldType == null) { // TODO: assertions.unreachable() this.filter = cha.lookupClass(TypeReference.JavaLangObject); } else { this.filter = fieldType; } } @Override public TypeFilter getTypeFilter() { return new SingleClassFilter(filter); } }
1,449
30.521739
96
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/ipa/callgraph/propagation/InstanceFieldPointerKey.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.ipa.callgraph.propagation; public interface InstanceFieldPointerKey extends PointerKey { /** @return the instance key which is the "container" for this pointer */ InstanceKey getInstanceKey(); }
597
32.222222
75
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/ipa/callgraph/propagation/InstanceKey.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.ipa.callgraph.propagation; import com.ibm.wala.classLoader.IClass; import com.ibm.wala.classLoader.NewSiteReference; import com.ibm.wala.ipa.callgraph.CGNode; import com.ibm.wala.ipa.callgraph.CallGraph; import com.ibm.wala.ipa.callgraph.ContextItem; import com.ibm.wala.util.collections.Pair; import java.util.Iterator; /** * An InstanceKey serves as the representative for an equivalence class of objects in the heap, that * can be pointed to. * * <p>For example, for 0-CFA, an InstanceKey would embody an &lt;IClass&gt;... we model all * instances of a particular class * * <p>For 0-1-CFA, an InstanceKey could be &lt;IMethod,statement #&gt;, representing a particular * allocation statement in a particular method. */ public interface InstanceKey extends ContextItem { /** * For now, we assert that each InstanceKey represents a set of classes which are all of the same * concrete type (modulo the fact that all arrays of references are considered concrete type * []Object;) */ IClass getConcreteType(); /** * Get the creation sites of {@code this}, i.e., the statements that may allocate objects * represented by {@code this}. A creation site is a pair (n,s), where n is the containing {@link * CGNode} in the given {@link CallGraph} {@code CG} and s is the allocating {@link * NewSiteReference}. */ Iterator<Pair<CGNode, NewSiteReference>> getCreationSites(CallGraph CG); }
1,824
37.020833
100
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/ipa/callgraph/propagation/InstanceKeyFactory.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.ipa.callgraph.propagation; import com.ibm.wala.classLoader.NewSiteReference; import com.ibm.wala.classLoader.ProgramCounter; import com.ibm.wala.ipa.callgraph.CGNode; import com.ibm.wala.types.TypeReference; /** An object that abstracts how to model instances in the heap. */ public interface InstanceKeyFactory { /** @return the instance key that represents a particular allocation */ InstanceKey getInstanceKeyForAllocation(CGNode node, NewSiteReference allocation); /** * @return the instance key that represents the array allocated as the dim_th dimension at a * particular allocation */ InstanceKey getInstanceKeyForMultiNewArray(CGNode node, NewSiteReference allocation, int dim); /** * @return the instance key that represents a constant with value S, when considered as a * particular type */ <T> InstanceKey getInstanceKeyForConstant(TypeReference type, T S); /** * @return the instance key that represents the exception of type _type_ thrown by a particular * PEI. */ InstanceKey getInstanceKeyForPEI(CGNode node, ProgramCounter instr, TypeReference type); /** * @param objType TODO * @return the instance key that represents the metadata object obj */ InstanceKey getInstanceKeyForMetadataObject(Object obj, TypeReference objType); }
1,715
35.510638
97
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/ipa/callgraph/propagation/LocalPointerKey.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.ipa.callgraph.propagation; import com.ibm.wala.ipa.callgraph.CGNode; /** A pointer key which provides a unique set for each local in each call graph node. */ public class LocalPointerKey extends AbstractLocalPointerKey { private final CGNode node; private final int valueNumber; public LocalPointerKey(CGNode node, int valueNumber) { super(); this.node = node; this.valueNumber = valueNumber; if (valueNumber <= 0) { throw new IllegalArgumentException("illegal valueNumber: " + valueNumber); } if (node == null) { throw new IllegalArgumentException("null node"); } } @Override public final boolean equals(Object obj) { if (obj instanceof LocalPointerKey) { LocalPointerKey other = (LocalPointerKey) obj; return node.equals(other.node) && valueNumber == other.valueNumber; } else { return false; } } @Override public final int hashCode() { return node.hashCode() * 23 + valueNumber; } @Override public String toString() { return "[" + node + ", v" + valueNumber + ']'; } @Override public final CGNode getNode() { return node; } public final int getValueNumber() { return valueNumber; } public final boolean isParameter() { return valueNumber <= node.getMethod().getNumberOfParameters(); } }
1,726
25.166667
88
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/ipa/callgraph/propagation/LocalPointerKeyWithFilter.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.ipa.callgraph.propagation; import com.ibm.wala.ipa.callgraph.CGNode; /** a local pointer key that carries a type filter */ public class LocalPointerKeyWithFilter extends LocalPointerKey implements FilteredPointerKey { private final TypeFilter typeFilter; public LocalPointerKeyWithFilter(CGNode node, int valueNumber, TypeFilter typeFilter) { super(node, valueNumber); assert typeFilter != null; this.typeFilter = typeFilter; } @Override public TypeFilter getTypeFilter() { return typeFilter; } }
926
28.903226
94
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/ipa/callgraph/propagation/MultiNewArrayInNode.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.ipa.callgraph.propagation; import com.ibm.wala.classLoader.ArrayClass; import com.ibm.wala.classLoader.IClass; import com.ibm.wala.classLoader.NewSiteReference; import com.ibm.wala.ipa.callgraph.CGNode; /** An {@link InstanceKey} which represents a multinewarray allocation site in a {@link CGNode}. */ public final class MultiNewArrayInNode extends AllocationSiteInNode { private final int dim; /** * @return null if the element type is a primitive * @throws IllegalArgumentException if T == null */ private static IClass myElementType(ArrayClass T, int d) throws IllegalArgumentException, IllegalArgumentException { if (T == null) { throw new IllegalArgumentException("T == null"); } if (d == 0) { return T.getElementClass(); } else { ArrayClass element = (ArrayClass) T.getElementClass(); if (element == null) { return null; } else { return myElementType(element, d - 1); } } } public MultiNewArrayInNode(CGNode node, NewSiteReference allocation, ArrayClass type, int dim) { super(node, allocation, myElementType(type, dim)); this.dim = dim; } @Override public boolean equals(Object obj) { // instanceof is OK because this class is final if (obj instanceof MultiNewArrayInNode) { MultiNewArrayInNode other = (MultiNewArrayInNode) obj; return (dim == other.dim && getNode().equals(other.getNode()) && getSite().equals(other.getSite())); } else { return false; } } @Override public int hashCode() { return 9967 * dim + getNode().hashCode() * 8647 * getSite().hashCode(); } @Override public String toString() { return super.toString() + "<dim:" + dim + '>'; } public int getDim() { return dim; } }
2,198
27.934211
99
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/ipa/callgraph/propagation/NodeKey.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.ipa.callgraph.propagation; import com.ibm.wala.ipa.callgraph.CGNode; /** A key which represents a set corresponding to a call graph node. */ public abstract class NodeKey extends AbstractLocalPointerKey { private final CGNode node; protected NodeKey(CGNode node) { if (node == null) { throw new IllegalArgumentException("null node"); } this.node = node; } protected boolean internalEquals(Object obj) { if (obj instanceof NodeKey) { NodeKey other = (NodeKey) obj; return node.equals(other.node); } else { return false; } } protected int internalHashCode() { return node.hashCode() * 1621; } /** @return the node this key represents */ @Override public CGNode getNode() { return node; } @Override public abstract boolean equals(Object obj); @Override public abstract int hashCode(); }
1,273
24.48
72
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/ipa/callgraph/propagation/NormalAllocationInNode.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.ipa.callgraph.propagation; import com.ibm.wala.classLoader.IClass; import com.ibm.wala.classLoader.NewSiteReference; import com.ibm.wala.ipa.callgraph.CGNode; /** * An {@link InstanceKey} which represents a "normal" (not multinewarray) {@link NewSiteReference} * in a {@link CGNode}. */ public final class NormalAllocationInNode extends AllocationSiteInNode { public NormalAllocationInNode(CGNode node, NewSiteReference allocation, IClass type) { super(node, allocation, type); } @Override public boolean equals(Object obj) { // instanceof is OK because this class is final if (obj instanceof NormalAllocationInNode) { AllocationSiteInNode other = (AllocationSiteInNode) obj; return getNode().equals(other.getNode()) && getSite().equals(other.getSite()); } else { return false; } } @Override public int hashCode() { return getNode().hashCode() * 8647 + getSite().hashCode(); } }
1,340
30.928571
98
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/ipa/callgraph/propagation/PointerAnalysis.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.ipa.callgraph.propagation; import com.ibm.wala.analysis.pointers.HeapGraph; import com.ibm.wala.ipa.cha.IClassHierarchy; import com.ibm.wala.util.intset.OrdinalSet; import com.ibm.wala.util.intset.OrdinalSetMapping; import java.util.Collection; /** Abstract definition of pointer analysis */ public interface PointerAnalysis<T extends InstanceKey> { /** * @param key representative of an equivalence class of pointers * @return Set of InstanceKey, representing the instance abstractions that define the points-to * set computed for the pointer key */ OrdinalSet<T> getPointsToSet(PointerKey key); /** @return an Object that determines how to model abstract locations in the heap. */ HeapModel getHeapModel(); /** @return a graph view of the pointer analysis solution */ HeapGraph<T> getHeapGraph(); /** * @return the bijection between InstanceKey &lt;=&gt; Integer that defines the interpretation of * points-to-sets. */ OrdinalSetMapping<T> getInstanceKeyMapping(); /** @return all pointer keys known */ Iterable<PointerKey> getPointerKeys(); /** @return all instance keys known */ Collection<T> getInstanceKeys(); /** did the pointer analysis use a type filter for a given points-to set? (this is ugly). */ boolean isFiltered(PointerKey pk); IClassHierarchy getClassHierarchy(); }
1,748
32.634615
99
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/ipa/callgraph/propagation/PointerAnalysisImpl.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.ipa.callgraph.propagation; import com.ibm.wala.classLoader.IClass; import com.ibm.wala.classLoader.IField; import com.ibm.wala.classLoader.Language; import com.ibm.wala.classLoader.NewSiteReference; import com.ibm.wala.classLoader.ProgramCounter; import com.ibm.wala.ipa.callgraph.CGNode; import com.ibm.wala.ipa.callgraph.CallGraph; import com.ibm.wala.ipa.cha.IClassHierarchy; import com.ibm.wala.ssa.DefUse; import com.ibm.wala.ssa.IR; import com.ibm.wala.ssa.SSAAbstractInvokeInstruction; import com.ibm.wala.ssa.SSAArrayLoadInstruction; import com.ibm.wala.ssa.SSACheckCastInstruction; import com.ibm.wala.ssa.SSAGetCaughtExceptionInstruction; import com.ibm.wala.ssa.SSAGetInstruction; import com.ibm.wala.ssa.SSAInstruction; import com.ibm.wala.ssa.SSAInvokeInstruction; import com.ibm.wala.ssa.SSANewInstruction; import com.ibm.wala.ssa.SSAPhiInstruction; import com.ibm.wala.ssa.SSAPiInstruction; import com.ibm.wala.ssa.SSAThrowInstruction; import com.ibm.wala.types.FieldReference; import com.ibm.wala.types.TypeReference; import com.ibm.wala.util.collections.HashSetFactory; import com.ibm.wala.util.collections.Iterator2Iterable; import com.ibm.wala.util.debug.Assertions; import com.ibm.wala.util.intset.IntSet; import com.ibm.wala.util.intset.MutableMapping; import com.ibm.wala.util.intset.MutableSparseIntSet; import com.ibm.wala.util.intset.OrdinalSet; import java.util.Collection; import java.util.Iterator; import java.util.List; import java.util.Set; /** General representation of the results of pointer analysis */ public class PointerAnalysisImpl extends AbstractPointerAnalysis { /** mapping from PointerKey to PointsToSetVariable */ private final PointsToMap pointsToMap; /** Meta-data regarding heap abstractions */ private final HeapModel H; /** An object that abstracts how to model pointers in the heap. */ protected final PointerKeyFactory pointerKeys; /** An object that abstracts how to model instances in the heap. */ private final InstanceKeyFactory iKeyFactory; protected final PropagationCallGraphBuilder builder; public PointerAnalysisImpl( PropagationCallGraphBuilder builder, CallGraph cg, PointsToMap pointsToMap, MutableMapping<InstanceKey> instanceKeys, PointerKeyFactory pointerKeys, InstanceKeyFactory iKeyFactory) { super(cg, instanceKeys); this.builder = builder; this.pointerKeys = pointerKeys; this.iKeyFactory = iKeyFactory; this.pointsToMap = pointsToMap; if (iKeyFactory == null) { throw new IllegalArgumentException("null iKeyFactory"); } H = makeHeapModel(); } @Override public String toString() { StringBuilder result = new StringBuilder("PointerAnalysis:\n"); for (PointerKey p : Iterator2Iterable.make(pointsToMap.iterateKeys())) { OrdinalSet<InstanceKey> O = getPointsToSet(p); result.append(" ").append(p).append(" ->\n"); for (InstanceKey instanceKey : O) { result.append(" ").append(instanceKey).append('\n'); } } return result.toString(); } protected HeapModel makeHeapModel() { return new HModel(); } /** * @see * com.ibm.wala.ipa.callgraph.propagation.PointerAnalysis#getPointsToSet(com.ibm.wala.ipa.callgraph.propagation.PointerKey) */ @Override @SuppressWarnings("unchecked") public OrdinalSet<InstanceKey> getPointsToSet(PointerKey key) { if (pointsToMap.isImplicit(key)) { return computeImplicitPointsToSet(key); } // special logic to handle contents of char[] from string constants. if (key instanceof InstanceFieldKey) { InstanceFieldKey ifk = (InstanceFieldKey) key; if (ifk.getInstanceKey() instanceof ConstantKey) { ConstantKey<?> i = (ConstantKey<?>) ifk.getInstanceKey(); if (i.getValue() instanceof String && i.getConcreteType().getClassLoader().getLanguage().equals(Language.JAVA)) { StringConstantCharArray contents = StringConstantCharArray.make((ConstantKey<String>) i); instanceKeys.add(contents); Collection<InstanceKey> singleton = HashSetFactory.make(); singleton.add(contents); return OrdinalSet.toOrdinalSet(singleton, instanceKeys); } } } PointsToSetVariable v = pointsToMap.getPointsToSet(key); if (v == null) { return OrdinalSet.empty(); } else { IntSet S = v.getValue(); return new OrdinalSet<>(S, instanceKeys); } } /** did the pointer analysis use a type filter for a given points-to set? (this is ugly). */ @Override public boolean isFiltered(PointerKey key) { if (pointsToMap.isImplicit(key)) { return false; } PointsToSetVariable v = pointsToMap.getPointsToSet(key); if (v == null) { return false; } else { return v.getPointerKey() instanceof FilteredPointerKey; } } public static class ImplicitPointsToSetVisitor extends SSAInstruction.Visitor { protected final PointerAnalysisImpl analysis; protected final CGNode node; protected final LocalPointerKey lpk; protected OrdinalSet<InstanceKey> pointsToSet = null; protected ImplicitPointsToSetVisitor(PointerAnalysisImpl analysis, LocalPointerKey lpk) { this.lpk = lpk; this.node = lpk.getNode(); this.analysis = analysis; } @Override public void visitNew(SSANewInstruction instruction) { pointsToSet = OrdinalSet.empty(); } @Override public void visitInvoke(SSAInvokeInstruction instruction) { pointsToSet = analysis.computeImplicitPointsToSetAtCall(lpk, node, instruction); } @Override public void visitCheckCast(SSACheckCastInstruction instruction) { pointsToSet = analysis.computeImplicitPointsToSetAtCheckCast(node, instruction); } @Override public void visitGetCaughtException(SSAGetCaughtExceptionInstruction instruction) { pointsToSet = analysis.computeImplicitPointsToSetAtCatch(node, instruction); } @Override public void visitGet(SSAGetInstruction instruction) { pointsToSet = analysis.computeImplicitPointsToSetAtGet(node, instruction); } @Override public void visitPhi(SSAPhiInstruction instruction) { pointsToSet = analysis.computeImplicitPointsToSetAtPhi(node, instruction); } @Override public void visitPi(SSAPiInstruction instruction) { pointsToSet = analysis.computeImplicitPointsToSetAtPi(node, instruction); } @Override public void visitArrayLoad(SSAArrayLoadInstruction instruction) { pointsToSet = analysis.computeImplicitPointsToSetAtALoad(node, instruction); } } protected ImplicitPointsToSetVisitor makeImplicitPointsToVisitor(LocalPointerKey lpk) { return new ImplicitPointsToSetVisitor(this, lpk); } private OrdinalSet<InstanceKey> computeImplicitPointsToSet(PointerKey key) { if (key instanceof LocalPointerKey) { LocalPointerKey lpk = (LocalPointerKey) key; CGNode node = lpk.getNode(); IR ir = node.getIR(); DefUse du = node.getDU(); if (((SSAPropagationCallGraphBuilder) builder) .contentsAreInvariant(ir.getSymbolTable(), du, lpk.getValueNumber())) { // cons up the points-to set for invariant contents InstanceKey[] ik = ((SSAPropagationCallGraphBuilder) builder) .getInvariantContents(ir.getSymbolTable(), du, node, lpk.getValueNumber(), H, true); return toOrdinalSet(ik); } else { SSAInstruction def = du.getDef(lpk.getValueNumber()); if (def != null) { ImplicitPointsToSetVisitor v = makeImplicitPointsToVisitor(lpk); def.visit(v); if (v.pointsToSet != null) { return v.pointsToSet; } else { Assertions.UNREACHABLE("saw " + key + ": time to implement for " + def.getClass()); return null; } } else { Assertions.UNREACHABLE("unexpected null def for " + key); return null; } } } else { Assertions.UNREACHABLE("unexpected implicit key " + key + " that's not a local pointer key"); return null; } } private OrdinalSet<InstanceKey> computeImplicitPointsToSetAtPi( CGNode node, SSAPiInstruction instruction) { MutableSparseIntSet S = MutableSparseIntSet.makeEmpty(); for (int i = 0; i < instruction.getNumberOfUses(); i++) { int vn = instruction.getUse(i); if (vn != -1) { PointerKey lpk = pointerKeys.getPointerKeyForLocal(node, vn); OrdinalSet<InstanceKey> pointees = getPointsToSet(lpk); IntSet set = pointees.getBackingSet(); if (set != null) { S.addAll(set); } } } return new OrdinalSet<>(S, instanceKeys); } private OrdinalSet<InstanceKey> computeImplicitPointsToSetAtPhi( CGNode node, SSAPhiInstruction instruction) { MutableSparseIntSet S = MutableSparseIntSet.makeEmpty(); for (int i = 0; i < instruction.getNumberOfUses(); i++) { int vn = instruction.getUse(i); if (vn != -1) { PointerKey lpk = pointerKeys.getPointerKeyForLocal(node, vn); OrdinalSet<InstanceKey> pointees = getPointsToSet(lpk); IntSet set = pointees.getBackingSet(); if (set != null) { S.addAll(set); } } } return new OrdinalSet<>(S, instanceKeys); } private OrdinalSet<InstanceKey> computeImplicitPointsToSetAtALoad( CGNode node, SSAArrayLoadInstruction instruction) { PointerKey arrayRef = pointerKeys.getPointerKeyForLocal(node, instruction.getArrayRef()); MutableSparseIntSet S = MutableSparseIntSet.makeEmpty(); OrdinalSet<InstanceKey> refs = getPointsToSet(arrayRef); for (InstanceKey ik : refs) { PointerKey key = pointerKeys.getPointerKeyForArrayContents(ik); OrdinalSet<InstanceKey> pointees = getPointsToSet(key); IntSet set = pointees.getBackingSet(); if (set != null) { S.addAll(set); } } return new OrdinalSet<>(S, instanceKeys); } private OrdinalSet<InstanceKey> computeImplicitPointsToSetAtGet( CGNode node, SSAGetInstruction instruction) { return computeImplicitPointsToSetAtGet( node, instruction.getDeclaredField(), instruction.getRef(), instruction.isStatic()); } public OrdinalSet<InstanceKey> computeImplicitPointsToSetAtGet( CGNode node, FieldReference field, int refVn, boolean isStatic) { IField f = getCallGraph().getClassHierarchy().resolveField(field); if (f == null) { return OrdinalSet.empty(); } if (isStatic) { PointerKey fKey = pointerKeys.getPointerKeyForStaticField(f); return getPointsToSet(fKey); } else { PointerKey ref = pointerKeys.getPointerKeyForLocal(node, refVn); MutableSparseIntSet S = MutableSparseIntSet.makeEmpty(); OrdinalSet<InstanceKey> refs = getPointsToSet(ref); for (InstanceKey ik : refs) { PointerKey fkey = pointerKeys.getPointerKeyForInstanceField(ik, f); if (fkey != null) { OrdinalSet<InstanceKey> pointees = getPointsToSet(fkey); IntSet set = pointees.getBackingSet(); if (set != null) { S.addAll(set); } } } return new OrdinalSet<>(S, instanceKeys); } } private OrdinalSet<InstanceKey> computeImplicitPointsToSetAtCatch( CGNode node, SSAGetCaughtExceptionInstruction instruction) { IR ir = node.getIR(); List<ProgramCounter> peis = SSAPropagationCallGraphBuilder.getIncomingPEIs(ir, ir.getBasicBlockForCatch(instruction)); Set<IClass> caughtTypes = SSAPropagationCallGraphBuilder.getCaughtExceptionTypes(instruction, ir); MutableSparseIntSet S = MutableSparseIntSet.makeEmpty(); // add the instances from each incoming pei ... for (ProgramCounter peiLoc : peis) { SSAInstruction pei = ir.getPEI(peiLoc); PointerKey e = null; // first deal with exception variables from calls and throws. if (pei instanceof SSAAbstractInvokeInstruction) { SSAAbstractInvokeInstruction s = (SSAAbstractInvokeInstruction) pei; e = pointerKeys.getPointerKeyForLocal(node, s.getException()); } else if (pei instanceof SSAThrowInstruction) { SSAThrowInstruction s = (SSAThrowInstruction) pei; e = pointerKeys.getPointerKeyForLocal(node, s.getException()); } if (e != null) { OrdinalSet<InstanceKey> ep = getPointsToSet(e); for (InstanceKey ik : ep) { if (PropagationCallGraphBuilder.catches( caughtTypes, ik.getConcreteType(), getCallGraph().getClassHierarchy())) { S.add(instanceKeys.getMappedIndex(ik)); } } } // Account for those exceptions for which we do not actually have a // points-to set for // the pei, but just instance keys Collection<TypeReference> types = pei.getExceptionTypes(); if (types != null) { for (TypeReference type : types) { if (type != null) { InstanceKey ik = SSAPropagationCallGraphBuilder.getInstanceKeyForPEI( node, peiLoc, type, iKeyFactory); ConcreteTypeKey ck = (ConcreteTypeKey) ik; IClass klass = ck.getType(); if (PropagationCallGraphBuilder.catches( caughtTypes, klass, getCallGraph().getClassHierarchy())) { S.add( instanceKeys.getMappedIndex( SSAPropagationCallGraphBuilder.getInstanceKeyForPEI( node, peiLoc, type, iKeyFactory))); } } } } } return new OrdinalSet<>(S, instanceKeys); } private OrdinalSet<InstanceKey> computeImplicitPointsToSetAtCheckCast( CGNode node, SSACheckCastInstruction instruction) { PointerKey rhs = pointerKeys.getPointerKeyForLocal(node, instruction.getVal()); OrdinalSet<InstanceKey> rhsSet = getPointsToSet(rhs); MutableSparseIntSet S = MutableSparseIntSet.makeEmpty(); for (TypeReference t : instruction.getDeclaredResultTypes()) { IClass klass = getCallGraph().getClassHierarchy().lookupClass(t); if (klass == null) { // could not find the type. conservatively assume Object return rhsSet; } else { if (klass.isInterface()) { for (InstanceKey ik : rhsSet) { if (getCallGraph() .getClassHierarchy() .implementsInterface(ik.getConcreteType(), klass)) { S.add(getInstanceKeyMapping().getMappedIndex(ik)); } } } else { for (InstanceKey ik : rhsSet) { if (getCallGraph().getClassHierarchy().isSubclassOf(ik.getConcreteType(), klass)) { S.add(getInstanceKeyMapping().getMappedIndex(ik)); } } } } } return new OrdinalSet<>(S, instanceKeys); } private OrdinalSet<InstanceKey> computeImplicitPointsToSetAtCall( LocalPointerKey lpk, CGNode node, SSAInvokeInstruction call) { int exc = call.getException(); if (lpk.getValueNumber() == exc) { return computeImplicitExceptionsForCall(node, call); } else { Assertions.UNREACHABLE("time to implement me."); return null; } } private OrdinalSet<InstanceKey> toOrdinalSet(InstanceKey[] ik) { MutableSparseIntSet s = MutableSparseIntSet.makeEmpty(); for (InstanceKey element : ik) { int index = instanceKeys.getMappedIndex(element); if (index != -1) { s.add(index); } else { assert index != -1 : "instance " + element + " not mapped!"; } } return new OrdinalSet<>(s, instanceKeys); } /** @return the points-to set for the exceptional return values from a particular call site */ private OrdinalSet<InstanceKey> computeImplicitExceptionsForCall( CGNode node, SSAInvokeInstruction call) { MutableSparseIntSet S = MutableSparseIntSet.makeEmpty(); for (CGNode target : getCallGraph().getPossibleTargets(node, call.getCallSite())) { PointerKey retVal = pointerKeys.getPointerKeyForExceptionalReturnValue(target); IntSet set = getPointsToSet(retVal).getBackingSet(); if (set != null) { S.addAll(set); } } return new OrdinalSet<>(S, instanceKeys); } /** @see com.ibm.wala.ipa.callgraph.propagation.PointerAnalysis#getHeapModel() */ @Override public HeapModel getHeapModel() { return H; } protected class HModel implements HeapModel { @Override public Iterator<PointerKey> iteratePointerKeys() { return pointsToMap.iterateKeys(); } @Override public InstanceKey getInstanceKeyForAllocation(CGNode node, NewSiteReference allocation) { return iKeyFactory.getInstanceKeyForAllocation(node, allocation); } @Override public InstanceKey getInstanceKeyForMultiNewArray( CGNode node, NewSiteReference allocation, int dim) { return iKeyFactory.getInstanceKeyForMultiNewArray(node, allocation, dim); } @Override public <T> InstanceKey getInstanceKeyForConstant(TypeReference type, T S) { return iKeyFactory.getInstanceKeyForConstant(type, S); } @Override public InstanceKey getInstanceKeyForPEI( CGNode node, ProgramCounter peiLoc, TypeReference type) { return iKeyFactory.getInstanceKeyForPEI(node, peiLoc, type); } @Override public InstanceKey getInstanceKeyForMetadataObject(Object obj, TypeReference objType) { return iKeyFactory.getInstanceKeyForMetadataObject(obj, objType); } /** * @see * com.ibm.wala.ipa.callgraph.propagation.PointerKeyFactory#getPointerKeyForLocal(com.ibm.wala.ipa.callgraph.CGNode, * int) */ @Override public PointerKey getPointerKeyForLocal(CGNode node, int valueNumber) { return pointerKeys.getPointerKeyForLocal(node, valueNumber); } @Override public FilteredPointerKey getFilteredPointerKeyForLocal( CGNode node, int valueNumber, FilteredPointerKey.TypeFilter filter) { return pointerKeys.getFilteredPointerKeyForLocal(node, valueNumber, filter); } /** * @see * com.ibm.wala.ipa.callgraph.propagation.PointerKeyFactory#getPointerKeyForReturnValue(com.ibm.wala.ipa.callgraph.CGNode) */ @Override public PointerKey getPointerKeyForReturnValue(CGNode node) { return pointerKeys.getPointerKeyForReturnValue(node); } /* * @see * com.ibm.wala.ipa.callgraph.propagation.PointerKeyFactory#getPointerKeyForExceptionalReturnValue(com.ibm.detox.ipa.callgraph * .CGNode) */ @Override public PointerKey getPointerKeyForExceptionalReturnValue(CGNode node) { return pointerKeys.getPointerKeyForExceptionalReturnValue(node); } /* * @see * com.ibm.wala.ipa.callgraph.propagation.PointerKeyFactory#getPointerKeyForStaticField(com.ibm.wala.classLoader.FieldReference) */ @Override public PointerKey getPointerKeyForStaticField(IField f) { return pointerKeys.getPointerKeyForStaticField(f); } /* * @see * com.ibm.wala.ipa.callgraph.propagation.PointerKeyFactory#getPointerKeyForInstance(com.ibm.wala.ipa.callgraph.propagation. * InstanceKey, com.ibm.wala.classLoader.FieldReference) */ @Override public PointerKey getPointerKeyForInstanceField(InstanceKey I, IField field) { assert field != null; return pointerKeys.getPointerKeyForInstanceField(I, field); } /* * @see * com.ibm.wala.ipa.callgraph.propagation.PointerKeyFactory#getPointerKeyForArrayContents(com.ibm.wala.ipa.callgraph.propagation * .InstanceKey) */ @Override public PointerKey getPointerKeyForArrayContents(InstanceKey I) { return pointerKeys.getPointerKeyForArrayContents(I); } @Override public IClassHierarchy getClassHierarchy() { return getCallGraph().getClassHierarchy(); } } /** @see com.ibm.wala.ipa.callgraph.propagation.PointerAnalysis#getPointerKeys() */ @Override public Iterable<PointerKey> getPointerKeys() { return Iterator2Iterable.make(pointsToMap.iterateKeys()); } @Override public IClassHierarchy getClassHierarchy() { return builder.getClassHierarchy(); } }
20,747
35.020833
132
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/ipa/callgraph/propagation/PointerKey.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.ipa.callgraph.propagation; /** * A PointerKey instance serves as the representative for an equivalence class of pointers. (or more * generally ...locations, if we allow primitives). * * <p>For example, a PointerKey for 0-CFA might be - a &lt;CGNode,int&gt; pair, where the int * represents an SSA value number. This PointerKey would represent all values of the pointer of a * particular local variable. - a &lt;FieldReference&gt;, representing the set of instances of a * given field in the heap, or of a particular static field. * * <p>A PointerKey for 0-1-CFA, with 1-level of InstanceVar context in the Grove et al. terminology, * would instead of FieldReference, use a - &lt;InstanceKey, FieldReference&gt; pair */ public interface PointerKey {}
1,158
43.576923
100
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/ipa/callgraph/propagation/PointerKeyComparator.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.ipa.callgraph.propagation; import com.ibm.wala.classLoader.ArrayClass; import com.ibm.wala.classLoader.IClass; import com.ibm.wala.classLoader.IField; import com.ibm.wala.ipa.callgraph.propagation.cfa.ExceptionReturnValueKey; import com.ibm.wala.ipa.cha.IClassHierarchy; import com.ibm.wala.types.TypeReference; import com.ibm.wala.util.debug.Assertions; import java.util.Comparator; public class PointerKeyComparator implements Comparator<PointerKey> { private final IClassHierarchy cha; public PointerKeyComparator(IClassHierarchy cha) { if (cha == null) { throw new IllegalArgumentException("null cha"); } this.cha = cha; } protected int comparePrimitives(TypeReference r1, TypeReference r2) { int h1 = r1.hashCode(); int h2 = r2.hashCode(); if (h1 != h2) return h1 - h2; else { assert r1 == r2; return 0; } } protected int compareConcreteTypes(IClass k1, IClass k2) { int n1 = cha.getNumber(k1); int n2 = cha.getNumber(k2); if (n1 != n2) return n1 - n2; else { int s1 = k1.hashCode(); int s2 = k2.hashCode(); assert k1 == k2 || s1 != s2; return s1 - s2; } } protected int compareInstanceKeys(InstanceKey k1, InstanceKey k2) { return compareConcreteTypes(k1.getConcreteType(), k2.getConcreteType()); } protected int compareFields(IField if1, IField if2) { int f1 = if1.hashCode(); int f2 = if2.hashCode(); if (f1 != f2) return f1 - f2; else { assert if1 == if2; return 0; } } private static int compareLocalKey(LocalPointerKey key1, Object key2) { if (key2 instanceof LocalPointerKey) { int l1 = key1.getValueNumber(); int l2 = ((LocalPointerKey) key2).getValueNumber(); if (l1 != l2) return l1 - l2; else { int n1 = key1.getNode().getGraphNodeId(); int n2 = ((LocalPointerKey) key2).getNode().getGraphNodeId(); if (n1 != n2) return n1 - n2; else { assert key1.equals(key2); return 0; } } } else return -1; } private static int compareReturnValueKey(ReturnValueKey key1, Object key2) { if (key2 instanceof ReturnValueKey) { int n1 = key1.getNode().getGraphNodeId(); int n2 = ((ReturnValueKey) key2).getNode().getGraphNodeId(); if (n1 != n2) return n1 - n2; else { assert key1.equals(key2); return 0; } } else return -1; } private static int compareExceptionKey(ExceptionReturnValueKey key1, Object key2) { if (key2 instanceof ExceptionReturnValueKey) { int n1 = key1.getNode().getGraphNodeId(); int n2 = ((ExceptionReturnValueKey) key2).getNode().getGraphNodeId(); if (n1 != n2) return n1 - n2; else { assert key1.equals(key2); return 0; } } else return -1; } private int compareFieldKey(InstanceFieldKey key1, Object key2) { if (key2 instanceof InstanceFieldKey) { int r1 = compareInstanceKeys(key1.getInstanceKey(), ((InstanceFieldKey) key2).getInstanceKey()); if (r1 != 0) return r1; else { return compareFields(key1.getField(), ((InstanceFieldKey) key2).getField()); } } else return -1; } private int compareStaticKey(StaticFieldKey key1, Object key2) { if (key2 instanceof StaticFieldKey) { int n1 = cha.getNumber(key1.getField().getDeclaringClass()); int n2 = cha.getNumber(((StaticFieldKey) key2).getField().getDeclaringClass()); if (n1 != n2) return n1 - n2; else { return compareFields(key1.getField(), ((StaticFieldKey) key2).getField()); } } else return -1; } private int compareArrayKey(ArrayContentsKey key1, Object key2) { if (key2 instanceof ArrayContentsKey) { ArrayClass k1 = (ArrayClass) key1.getInstanceKey().getConcreteType(); ArrayClass k2 = (ArrayClass) ((ArrayContentsKey) key2).getInstanceKey().getConcreteType(); int d1 = k1.getDimensionality(); int d2 = k2.getDimensionality(); if (d1 != d2) { return d1 - d2; } else if (k1.getInnermostElementClass() == null) { if (k2.getInnermostElementClass() == null) return comparePrimitives( k1.getReference().getInnermostElementType(), k2.getReference().getInnermostElementType()); else return -1; } else if (k2.getInnermostElementClass() == null) { return 1; } else { return compareConcreteTypes(k1.getInnermostElementClass(), k2.getInnermostElementClass()); } } else return -1; } @Override public int compare(PointerKey key1, PointerKey key2) { if (key1 == key2) return 0; else if (key1 instanceof LocalPointerKey) { return compareLocalKey((LocalPointerKey) key1, key2); } else if (key2 instanceof LocalPointerKey) { return -1 * compareLocalKey((LocalPointerKey) key2, key1); } // at this point, neither key is local else if (key1 instanceof ExceptionReturnValueKey) { return compareExceptionKey((ExceptionReturnValueKey) key1, key2); } else if (key2 instanceof ExceptionReturnValueKey) { return -1 * compareExceptionKey((ExceptionReturnValueKey) key2, key1); } // at this point, neither key is local or expretval else if (key1 instanceof ReturnValueKey) { return compareReturnValueKey((ReturnValueKey) key1, key2); } else if (key2 instanceof ReturnValueKey) { return -1 * compareReturnValueKey((ReturnValueKey) key2, key1); } // at this point, neither key is local or retval, expretval else if (key1 instanceof InstanceFieldKey) { return compareFieldKey((InstanceFieldKey) key1, key2); } else if (key2 instanceof InstanceFieldKey) { return -1 * compareFieldKey((InstanceFieldKey) key2, key1); } // at this point, neither key is local or retval, expretval, field else if (key1 instanceof StaticFieldKey) { return compareStaticKey((StaticFieldKey) key1, key2); } else if (key2 instanceof StaticFieldKey) { return -1 * compareStaticKey((StaticFieldKey) key2, key1); } // at this point, neither key is local or retval, expretval, field, static else if (key1 instanceof ArrayContentsKey) { return compareArrayKey((ArrayContentsKey) key1, key2); } else if (key2 instanceof ArrayContentsKey) { return -1 * compareArrayKey((ArrayContentsKey) key2, key1); } else { return compareOtherKeys(key1, key2); } } protected int compareOtherKeys(Object key1, Object key2) { System.err.println("Cannot compare " + key1 + " and " + key2); Assertions.UNREACHABLE(); return 0; } @Override public boolean equals(Object o) { return (o instanceof PointerKeyComparator) && ((PointerKeyComparator) o).cha.equals(cha); } @Override public int hashCode() { return cha.hashCode(); } }
7,283
32.56682
98
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/ipa/callgraph/propagation/PointerKeyFactory.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.ipa.callgraph.propagation; import com.ibm.wala.classLoader.IField; import com.ibm.wala.ipa.callgraph.CGNode; /** An object that abstracts how to model pointers in the heap. */ public interface PointerKeyFactory { /** * @return the PointerKey that acts as a representative for the class of pointers that includes * the local variable identified by the value number parameter. */ PointerKey getPointerKeyForLocal(CGNode node, int valueNumber); /** * @return the PointerKey that acts as a representative for the class of pointers that includes * the local variable identified by the value number parameter. */ FilteredPointerKey getFilteredPointerKeyForLocal( CGNode node, int valueNumber, FilteredPointerKey.TypeFilter filter); /** * @return the PointerKey that acts as a representative for the class of pointers that includes * the return value for a node */ PointerKey getPointerKeyForReturnValue(CGNode node); /** * @return the PointerKey that acts as a representative for the class of pointers that includes * the exceptional return value */ PointerKey getPointerKeyForExceptionalReturnValue(CGNode node); /** * @return the PointerKey that acts as a representative for the class of pointers that includes * the contents of the static field */ PointerKey getPointerKeyForStaticField(IField f); /** * @return the PointerKey that acts as a representation for the class of pointers that includes * the given instance field. */ PointerKey getPointerKeyForInstanceField(InstanceKey I, IField field); /** * TODO: expand this API to differentiate between different array indices * * @param I an InstanceKey representing an abstract array * @return the PointerKey that acts as a representation for the class of pointers that includes * the given array contents. */ PointerKey getPointerKeyForArrayContents(InstanceKey I); }
2,355
35.8125
97
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/ipa/callgraph/propagation/PointsToMap.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.ipa.callgraph.propagation; import com.ibm.wala.util.collections.FilterIterator; import com.ibm.wala.util.collections.IVector; import com.ibm.wala.util.collections.Iterator2Iterable; import com.ibm.wala.util.collections.SimpleVector; import com.ibm.wala.util.debug.Assertions; import com.ibm.wala.util.intset.BitVector; import com.ibm.wala.util.intset.IntIterator; import com.ibm.wala.util.intset.IntSet; import com.ibm.wala.util.intset.IntegerUnionFind; import com.ibm.wala.util.intset.MutableMapping; import java.util.Iterator; /** An object that tracks the mapping between pointer keys and points-to set variables */ public class PointsToMap { /** An object that manages the numbering of pointer keys */ private final MutableMapping<PointerKey> pointerKeys = MutableMapping.make(); /** * pointsToSets[i] says something about the representation of the points-to set for the ith {@link * PointerKey}, as determined by the pointerKeys mapping. pointsToSets[i] can be one of the * following: * * <ul> * <li>a PointsToSetVariable * <li>IMPLICIT * <li>UNIFIED * </ul> */ private final IVector<Object> pointsToSets = new SimpleVector<>(); private final IntegerUnionFind uf = new IntegerUnionFind(); /** A hack: used to represent points-to-sets that are represented implicitly */ static final Object IMPLICIT = new Object() { @Override public String toString() { return "IMPLICIT points-to set"; } }; /** A hack: used to represent points-to-sets that are unified with another */ static final Object UNIFIED = new Object() { @Override public String toString() { return "UNIFIED points-to set"; } }; /** * Numbers of pointer keys (non locals) that are roots of transitive closure. A "root" is a * points-to-set whose contents do not result from flow from other points-to-sets; these * points-to-sets are the primordial assignments from which the transitive closure flows. */ private final BitVector transitiveRoots = new BitVector(); /** @return iterator of all PointerKeys tracked */ public Iterator<PointerKey> iterateKeys() { return pointerKeys.iterator(); } /** If p is unified, returns the representative for p. */ public PointsToSetVariable getPointsToSet(PointerKey p) { if (p == null) { throw new IllegalArgumentException("null p"); } if (isImplicit(p)) { throw new IllegalArgumentException( "unexpected: shouldn't ask a PointsToMap for an implicit points-to-set: " + p); } int i = pointerKeys.getMappedIndex(p); if (i == -1) { return null; } int repI = uf.find(i); PointsToSetVariable result = (PointsToSetVariable) pointsToSets.get(repI); if (result != null && p instanceof FilteredPointerKey && !(result.getPointerKey() instanceof FilteredPointerKey)) { upgradeToFilter(result, ((FilteredPointerKey) p).getTypeFilter()); } return result; } /** @return the {@link PointsToSetVariable} recorded for a particular id */ public PointsToSetVariable getPointsToSet(int id) { int repI = uf.find(id); return (PointsToSetVariable) pointsToSets.get(repI); } /** record that a particular points-to-set is represented implicitly */ public void recordImplicit(PointerKey key) { if (key == null) { throw new IllegalArgumentException("null key"); } int i = findOrCreateIndex(key); pointsToSets.set(i, IMPLICIT); } public void put(PointerKey key, PointsToSetVariable v) { int i = findOrCreateIndex(key); pointsToSets.set(i, v); } private int findOrCreateIndex(PointerKey key) { int result = pointerKeys.getMappedIndex(key); if (result == -1) { result = pointerKeys.add(key); } return result; } /** record that a particular points-to-set has been unioned with another */ public void recordUnified(PointerKey key) { if (key == null) { throw new IllegalArgumentException("null key"); } int i = findOrCreateIndex(key); pointsToSets.set(i, UNIFIED); } /** * record points-to-sets that are "roots" of the transitive closure. These points-to-sets can't be * thrown away for a pre-transitive solver. A "root" is a points-to-set whose contents do not * result from flow from other points-to-sets; there points-to-sets are the primordial assignments * from which the transitive closure flows. */ public void recordTransitiveRoot(PointerKey key) { if (key == null) { throw new IllegalArgumentException("null key"); } int i = findOrCreateIndex(key); transitiveRoots.set(i); } /** * A "root" is a points-to-set whose contents do not result from flow from other points-to-sets; * there points-to-sets are the primordial assignments from which the transitive closure flows. */ boolean isTransitiveRoot(PointerKey key) { int i = findOrCreateIndex(key); return transitiveRoots.get(i); } public boolean isUnified(PointerKey p) { if (p == null) { throw new IllegalArgumentException("null p"); } int i = findOrCreateIndex(p); return pointsToSets.get(i) == UNIFIED; } public boolean isImplicit(PointerKey p) { int i = getIndex(p); return i != -1 && pointsToSets.get(i) == IMPLICIT; } protected int getNumberOfPointerKeys() { return pointerKeys.getSize(); } /** Wipe out the cached transitive closure information */ public void revertToPreTransitive() { for (PointerKey key : Iterator2Iterable.make(iterateKeys())) { if (!isTransitiveRoot(key) && !isImplicit(key) && !isUnified(key)) { PointsToSetVariable v = getPointsToSet(key); v.removeAll(); } } } /** @return {@link Iterator}&lt;{@link PointerKey}&gt; */ public Iterator<PointerKey> getTransitiveRoots() { return new FilterIterator<>(iterateKeys(), this::isTransitiveRoot); } /** * Unify the points-to-sets for the variables identified by the set s * * @param s numbers of points-to-set variables * @throws IllegalArgumentException if s is null */ public void unify(IntSet s) throws IllegalArgumentException { if (s == null) { throw new IllegalArgumentException("s is null"); } if (s.size() <= 1) { throw new IllegalArgumentException("Can't unify set of size " + s.size()); } IntIterator it = s.intIterator(); int i = it.next(); while (it.hasNext()) { unify(i, it.next()); } } /** Unify the points-to-sets for the variables with numbers i and j */ public void unify(int i, int j) { int repI = uf.find(i); int repJ = uf.find(j); if (repI != repJ) { PointsToSetVariable pi = (PointsToSetVariable) pointsToSets.get(repI); PointsToSetVariable pj = (PointsToSetVariable) pointsToSets.get(repJ); if (pi == null) { throw new IllegalArgumentException("No PointsToSetVariable for i: " + i); } if (pj == null) { throw new IllegalArgumentException("No PointsToSetVariable for j: " + j); } uf.union(repI, repJ); int rep = uf.find(repI); PointsToSetVariable p = (PointsToSetVariable) pointsToSets.get(rep); if (pi.getValue() != null) { p.addAll(pi.getValue()); } if (pj.getValue() != null) { p.addAll(pj.getValue()); } if (p != pi) { recordUnified(pi.getPointerKey()); upgradeTypeFilter(pi, p); } if (p != pj) { recordUnified(pj.getPointerKey()); upgradeTypeFilter(pj, p); } if (isTransitiveRoot(pi.getPointerKey()) || isTransitiveRoot(pj.getPointerKey())) { recordTransitiveRoot(p.getPointerKey()); } } } private void upgradeTypeFilter(PointsToSetVariable src, PointsToSetVariable dest) { if (src.getPointerKey() instanceof FilteredPointerKey) { FilteredPointerKey fpk = (FilteredPointerKey) src.getPointerKey(); if (dest.getPointerKey() instanceof FilteredPointerKey) { FilteredPointerKey fp = (FilteredPointerKey) dest.getPointerKey(); if (!fp.getTypeFilter().equals(fpk.getTypeFilter())) { Assertions.UNREACHABLE("src " + fpk.getTypeFilter() + " dest " + fp.getTypeFilter()); } } else { upgradeToFilter(dest, fpk.getTypeFilter()); } } } private void upgradeToFilter(PointsToSetVariable p, FilteredPointerKey.TypeFilter typeFilter) { if (p.getPointerKey() instanceof LocalPointerKey) { LocalPointerKey lpk = (LocalPointerKey) p.getPointerKey(); LocalPointerKeyWithFilter f = new LocalPointerKeyWithFilter(lpk.getNode(), lpk.getValueNumber(), typeFilter); p.setPointerKey(f); pointerKeys.replace(lpk, f); } else if (p.getPointerKey() instanceof ReturnValueKey) { ReturnValueKey r = (ReturnValueKey) p.getPointerKey(); ReturnValueKeyWithFilter f = new ReturnValueKeyWithFilter(r.getNode(), typeFilter); p.setPointerKey(f); pointerKeys.replace(r, f); } else { Assertions.UNREACHABLE(p.getPointerKey().getClass().toString()); } } /** @return the unique integer that identifies this pointer key */ public int getIndex(PointerKey p) { return pointerKeys.getMappedIndex(p); } public int getRepresentative(int i) { return uf.find(i); } }
9,770
33.045296
100
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/ipa/callgraph/propagation/PointsToSetVariable.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.ipa.callgraph.propagation; import com.ibm.wala.analysis.typeInference.TypeInference; import com.ibm.wala.classLoader.IClass; import com.ibm.wala.fixpoint.IntSetVariable; import com.ibm.wala.ipa.callgraph.CGNode; import com.ibm.wala.ipa.cha.IClassHierarchy; import com.ibm.wala.ssa.IR; import com.ibm.wala.types.TypeReference; import com.ibm.wala.util.debug.Assertions; import com.ibm.wala.util.intset.IntSet; import com.ibm.wala.util.intset.MutableMapping; import com.ibm.wala.util.intset.MutableSparseIntSet; /** Representation of a points-to set during an andersen-style analysis. */ public class PointsToSetVariable extends IntSetVariable<PointsToSetVariable> { /** if set, emits a warning whenever a points-to set grows bigger than {@link #SIZE_THRESHOLD} */ public static final boolean CRY_ABOUT_BIG_POINTSTO_SETS = false; public static final int SIZE_THRESHOLD = 100; /** * if set, check that all instance keys in a points-to set are consistent with the type of the * corresponding pointer key */ public static final boolean PARANOID = false; /** Print names of types of instance keys */ public static final boolean VERBOSE_PRINT = false; /** * used only for paranoid checking. a bit ugly, but avoids adding an instance field just for * debugging */ public static MutableMapping<InstanceKey> instanceKeys = null; private PointerKey pointerKey; public PointsToSetVariable(PointerKey key) { super(); if (key == null) { throw new IllegalArgumentException("null key"); } this.pointerKey = key; } public PointerKey getPointerKey() { return pointerKey; } @Override public boolean equals(Object obj) { if (obj instanceof PointsToSetVariable) { return pointerKey.equals(((PointsToSetVariable) obj).pointerKey); } else { return false; } } private boolean cried = false; @SuppressWarnings("unused") private void cryIfTooBig() { if (CRY_ABOUT_BIG_POINTSTO_SETS && !cried && super.size() > SIZE_THRESHOLD) { cried = true; System.err.println("too big: " + pointerKey + ": " + size()); } } @Override public boolean add(int b) { if (PARANOID) { MutableSparseIntSet m = MutableSparseIntSet.createMutableSparseIntSet(1); m.add(b); checkTypes(m); } final boolean result = super.add(b); cryIfTooBig(); return result; } @Override public boolean addAll(IntSet B) { if (PARANOID) { checkTypes(B); } boolean v = super.addAll(B); cryIfTooBig(); return v; } /** check that the types of all instance keys are assignable to declared type of pointer key */ private void checkTypes(IntSet b) { assert PARANOID; if (b == null) return; if (!(pointerKey instanceof LocalPointerKey)) { return; } final LocalPointerKey lpk = (LocalPointerKey) pointerKey; CGNode node = lpk.getNode(); final IClassHierarchy cha = node.getClassHierarchy(); final IR ir = node.getIR(); if (ir == null) return; TypeInference ti = TypeInference.make(ir, false); final IClass type = ti.getType(lpk.getValueNumber()).getType(); if (type == null) return; // don't perform checking for exception variables if (cha.isAssignableFrom(cha.lookupClass(TypeReference.JavaLangThrowable), type)) { return; } b.foreach( x -> { InstanceKey ik = instanceKeys.getMappedObject(x); IClass concreteType = ik.getConcreteType(); if (!cha.isAssignableFrom(type, concreteType)) { System.err.println("BOOM"); System.err.println(ir); System.err.println(lpk + " type " + type); System.err.println(ik + " type " + concreteType); Assertions.UNREACHABLE(); } }); } @Override public boolean addAll(PointsToSetVariable other) { if (PARANOID) { checkTypes(other.getValue()); } // TODO Auto-generated method stub boolean v = super.addAll(other); cryIfTooBig(); return v; } /** * Use this with extreme care, to add filters to this variable.. * * @param pointerKey The pointerKey to set. */ public void setPointerKey(PointerKey pointerKey) { // check that we haven't modified the hash code!!! this is crucial assert this.pointerKey.hashCode() == pointerKey.hashCode(); this.pointerKey = pointerKey; } @Override public String toString() { if (VERBOSE_PRINT) { StringBuilder x = new StringBuilder(pointerKey.toString()).append(" :"); getValue().foreach(i -> x.append(" ").append(instanceKeys.getMappedObject(i))); return x.toString(); } else { return pointerKey.toString() + ':' + super.toString(); } } }
5,144
29.625
99
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/ipa/callgraph/propagation/PropagationCallGraphBuilder.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.ipa.callgraph.propagation; import com.ibm.wala.analysis.reflection.IllegalArgumentExceptionContext; import com.ibm.wala.classLoader.CallSiteReference; import com.ibm.wala.classLoader.IClass; import com.ibm.wala.classLoader.IField; import com.ibm.wala.classLoader.IMethod; import com.ibm.wala.classLoader.Language; import com.ibm.wala.classLoader.NewSiteReference; import com.ibm.wala.classLoader.SyntheticClass; import com.ibm.wala.core.util.CancelRuntimeException; import com.ibm.wala.core.util.warnings.Warning; import com.ibm.wala.core.util.warnings.Warnings; import com.ibm.wala.fixpoint.UnaryOperator; 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.CallGraphBuilderCancelException; import com.ibm.wala.ipa.callgraph.Context; 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.AbstractRootMethod; import com.ibm.wala.ipa.callgraph.impl.ExplicitCallGraph; import com.ibm.wala.ipa.callgraph.propagation.rta.RTAContextInterpreter; import com.ibm.wala.ipa.cha.IClassHierarchy; import com.ibm.wala.ssa.SSAAbstractInvokeInstruction; import com.ibm.wala.types.TypeReference; import com.ibm.wala.util.CancelException; import com.ibm.wala.util.MonitorUtil.IProgressMonitor; import com.ibm.wala.util.collections.HashSetFactory; import com.ibm.wala.util.debug.Assertions; import com.ibm.wala.util.intset.IntSet; import com.ibm.wala.util.intset.IntSetAction; import com.ibm.wala.util.intset.IntSetUtil; import com.ibm.wala.util.intset.MutableIntSet; import java.util.Iterator; import java.util.List; import java.util.Set; /** * This abstract base class provides the general algorithm for a call graph builder that relies on * propagation through an iterative dataflow solver * * <p>TODO: This implementation currently keeps all points to sets live ... even those for local * variables that do not span interprocedural boundaries. This may be too space-inefficient .. we * can consider recomputing local sets on demand. */ public abstract class PropagationCallGraphBuilder implements CallGraphBuilder<InstanceKey> { private static final boolean DEBUG_ALL = false; static final boolean DEBUG_ASSIGN = DEBUG_ALL | false; private static final boolean DEBUG_ARRAY_LOAD = DEBUG_ALL | false; private static final boolean DEBUG_ARRAY_STORE = DEBUG_ALL | false; private static final boolean DEBUG_FILTER = DEBUG_ALL | false; protected static final boolean DEBUG_GENERAL = DEBUG_ALL | false; private static final boolean DEBUG_GET = DEBUG_ALL | false; private static final boolean DEBUG_PUT = DEBUG_ALL | false; private static final boolean DEBUG_ENTRYPOINTS = DEBUG_ALL | false; /** Meta-data regarding how pointers are modeled */ protected PointerKeyFactory pointerKeyFactory; /** The object that represents the java.lang.Object class */ private final IClass JAVA_LANG_OBJECT; /** Governing class hierarchy */ public final IClassHierarchy cha; /** Special rules for bypassing Java calls */ protected final AnalysisOptions options; /** Cache of IRs and things */ private final IAnalysisCacheView analysisCache; /** Set of nodes that have already been traversed for constraints */ private final Set<CGNode> alreadyVisited = HashSetFactory.make(); /** * At any given time, the set of nodes that have been discovered but not yet processed for * constraints */ private Set<CGNode> discoveredNodes = HashSetFactory.make(); /** Set of calls (CallSiteReferences) that are created by entrypoints */ protected final Set<CallSiteReference> entrypointCallSites = HashSetFactory.make(); /** The system of constraints used to build this graph */ protected PropagationSystem system; public PropagationSystem getSystem() { return system; } /** Algorithm used to solve the system of constraints */ private IPointsToSolver solver; /** The call graph under construction */ protected final ExplicitCallGraph callGraph; /** Singleton operator for assignments */ public static final AssignOperator assignOperator = new AssignOperator(); /** singleton operator for filter */ public final FilterOperator filterOperator = new FilterOperator(); /** singleton operator for inverse filter */ protected final InverseFilterOperator inverseFilterOperator = new InverseFilterOperator(); /** An object which interprets methods in context */ private SSAContextInterpreter contextInterpreter; /** A context selector which may use information derived from the propagation-based dataflow. */ protected ContextSelector contextSelector; /** An object that abstracts how to model instances in the heap. */ protected InstanceKeyFactory instanceKeyFactory; /** * Algorithmic choice: should the GetfieldOperator and PutfieldOperator cache its previous history * to reduce work? */ private final boolean rememberGetPutHistory = true; /** * @param options governing call graph construction options * @param pointerKeyFactory factory which embodies pointer abstraction policy */ protected PropagationCallGraphBuilder( IMethod abstractRootMethod, AnalysisOptions options, IAnalysisCacheView cache, PointerKeyFactory pointerKeyFactory) { if (abstractRootMethod == null) { throw new IllegalArgumentException("cha is null"); } if (options == null) { throw new IllegalArgumentException("options is null"); } assert cache != null; this.cha = abstractRootMethod.getClassHierarchy(); this.options = options; this.analysisCache = cache; // we need pointer keys to handle reflection assert pointerKeyFactory != null; this.pointerKeyFactory = pointerKeyFactory; callGraph = createEmptyCallGraph(abstractRootMethod, options); try { callGraph.init(); } catch (CancelException e) { if (DEBUG_GENERAL) { System.err.println( "Could not initialize the call graph due to node number constraints: " + e.getMessage()); } } callGraph.setInterpreter(contextInterpreter); JAVA_LANG_OBJECT = cha.lookupClass(TypeReference.JavaLangObject); } protected ExplicitCallGraph createEmptyCallGraph( IMethod abstractRootMethod, AnalysisOptions options) { return new ExplicitCallGraph(abstractRootMethod, options, getAnalysisCache()); } /** @return true iff the klass represents java.lang.Object */ protected boolean isJavaLangObject(IClass klass) { return klass.getReference().equals(TypeReference.JavaLangObject); } public CallGraph makeCallGraph(AnalysisOptions options) throws IllegalArgumentException, CancelException { return makeCallGraph(options, null); } @Override public CallGraph makeCallGraph(AnalysisOptions options, IProgressMonitor monitor) throws IllegalArgumentException, CallGraphBuilderCancelException { if (options == null) { throw new IllegalArgumentException("options is null"); } system = makeSystem(options); if (DEBUG_GENERAL) { System.err.println("Enter makeCallGraph!"); } if (DEBUG_GENERAL) { System.err.println("Initialized call graph"); } system.setMinEquationsForTopSort(options.getMinEquationsForTopSort()); system.setTopologicalGrowthFactor(options.getTopologicalGrowthFactor()); system.setMaxEvalBetweenTopo(options.getMaxEvalBetweenTopo()); discoveredNodes = HashSetFactory.make(); discoveredNodes.add(callGraph.getFakeRootNode()); // Set up the initially reachable methods and classes for (Entrypoint E : options.getEntrypoints()) { if (DEBUG_ENTRYPOINTS) { System.err.println("Entrypoint: " + E); } SSAAbstractInvokeInstruction call = E.addCall((AbstractRootMethod) callGraph.getFakeRootNode().getMethod()); if (call == null) { Warnings.add(EntrypointResolutionWarning.create(E)); } else { entrypointCallSites.add(call.getCallSite()); } } /* * BEGIN Custom change: throw exception on empty entry points. This is a severe issue that * should not go undetected! */ if (entrypointCallSites.isEmpty()) { throw new IllegalStateException( "Could not create a entrypoint callsites: " + Warnings.asString()); } /* * END Custom change: throw exception on empty entry points. This is a severe issue that should * not go undetected! */ customInit(); solver = makeSolver(); try { solver.solve(monitor); } catch (CancelException | CancelRuntimeException e) { CallGraphBuilderCancelException c = CallGraphBuilderCancelException.createCallGraphBuilderCancelException( e, callGraph, system.extractPointerAnalysis(this)); throw c; } return callGraph; } protected PropagationSystem makeSystem(@SuppressWarnings("unused") AnalysisOptions options) { return new PropagationSystem(callGraph, pointerKeyFactory, instanceKeyFactory); } protected abstract IPointsToSolver makeSolver(); /** A warning for when we fail to resolve a call to an entrypoint */ private static class EntrypointResolutionWarning extends Warning { final Entrypoint entrypoint; EntrypointResolutionWarning(Entrypoint entrypoint) { super(Warning.SEVERE); this.entrypoint = entrypoint; } @Override public String getMsg() { return getClass().toString() + " : " + entrypoint; } public static EntrypointResolutionWarning create(Entrypoint entrypoint) { return new EntrypointResolutionWarning(entrypoint); } } protected void customInit() {} /** * Add constraints for a node. * * @return true iff any new constraints are added. */ protected abstract boolean addConstraintsFromNode(CGNode n, IProgressMonitor monitor) throws CancelException; /** * Add constraints from newly discovered nodes. Note: the act of adding constraints may discover * new nodes, so this routine is iterative. * * @return true iff any new constraints are added. */ protected boolean addConstraintsFromNewNodes(IProgressMonitor monitor) throws CancelException { boolean result = false; while (!discoveredNodes.isEmpty()) { Iterator<CGNode> it = discoveredNodes.iterator(); discoveredNodes = HashSetFactory.make(); while (it.hasNext()) { CGNode n = it.next(); result |= addConstraintsFromNode(n, monitor); } } return result; } /** * @return the PointerKey that acts as a representative for the class of pointers that includes * the local variable identified by the value number parameter. */ public PointerKey getPointerKeyForLocal(CGNode node, int valueNumber) { return pointerKeyFactory.getPointerKeyForLocal(node, valueNumber); } /** * @return the PointerKey that acts as a representative for the class of pointers that includes * the local variable identified by the value number parameter. */ public FilteredPointerKey getFilteredPointerKeyForLocal( CGNode node, int valueNumber, FilteredPointerKey.TypeFilter filter) { assert filter != null; return pointerKeyFactory.getFilteredPointerKeyForLocal(node, valueNumber, filter); } public FilteredPointerKey getFilteredPointerKeyForLocal( CGNode node, int valueNumber, IClass filter) { return getFilteredPointerKeyForLocal( node, valueNumber, new FilteredPointerKey.SingleClassFilter(filter)); } public FilteredPointerKey getFilteredPointerKeyForLocal( CGNode node, int valueNumber, InstanceKey filter) { return getFilteredPointerKeyForLocal( node, valueNumber, new FilteredPointerKey.SingleInstanceFilter(filter)); } /** * @return the PointerKey that acts as a representative for the class of pointers that includes * the return value for a node */ public PointerKey getPointerKeyForReturnValue(CGNode node) { return pointerKeyFactory.getPointerKeyForReturnValue(node); } /** * @return the PointerKey that acts as a representative for the class of pointers that includes * the exceptional return value */ public PointerKey getPointerKeyForExceptionalReturnValue(CGNode node) { return pointerKeyFactory.getPointerKeyForExceptionalReturnValue(node); } /** * @return the PointerKey that acts as a representative for the class of pointers that includes * the contents of the static field */ public PointerKey getPointerKeyForStaticField(IField f) { assert f != null : "null FieldReference"; return pointerKeyFactory.getPointerKeyForStaticField(f); } /** * @return the PointerKey that acts as a representation for the class of pointers that includes * the given instance field. null if there's some problem. * @throws IllegalArgumentException if I is null * @throws IllegalArgumentException if field is null */ public PointerKey getPointerKeyForInstanceField(InstanceKey I, IField field) { if (field == null) { throw new IllegalArgumentException("field is null"); } if (I == null) { throw new IllegalArgumentException("I is null"); } IClass t = field.getDeclaringClass(); IClass C = I.getConcreteType(); if (!(C instanceof SyntheticClass)) { if (!getClassHierarchy().isSubclassOf(C, t)) { return null; } } return pointerKeyFactory.getPointerKeyForInstanceField(I, field); } /** * TODO: expand this API to differentiate between different array indices * * @param I an InstanceKey representing an abstract array * @return the PointerKey that acts as a representation for the class of pointers that includes * the given array contents, or null if none found. * @throws IllegalArgumentException if I is null */ public PointerKey getPointerKeyForArrayContents(InstanceKey I) { if (I == null) { throw new IllegalArgumentException("I is null"); } IClass C = I.getConcreteType(); if (!C.isArrayClass()) { assert false : "illegal arguments: " + I; } return pointerKeyFactory.getPointerKeyForArrayContents(I); } /** * Handle assign of a particular exception instance into an exception variable * * @param exceptionVar points-to set for a variable representing a caught exception * @param catchClasses set of TypeReferences that the exceptionVar may catch * @param e a particular exception instance */ protected void assignInstanceToCatch( PointerKey exceptionVar, Set<IClass> catchClasses, InstanceKey e) { if (catches(catchClasses, e.getConcreteType(), cha)) { system.newConstraint(exceptionVar, e); } } /** * Generate a set of constraints to represent assignment to an exception variable in a catch * clause. Note that we use FilterOperator to filter out types that the exception handler doesn't * catch. * * @param exceptionVar points-to set for a variable representing a caught exception * @param catchClasses set of TypeReferences that the exceptionVar may catch * @param e points-to-set representing a thrown exception that might be caught. */ protected void addAssignmentsForCatchPointerKey( PointerKey exceptionVar, Set<IClass> catchClasses, PointerKey e) { if (DEBUG_GENERAL) { System.err.println("addAssignmentsForCatch: " + catchClasses); } // this is tricky ... we want to filter based on a number of classes ... so we can't // just used a FilteredPointerKey for the exceptionVar. Instead, we create a new // "typed local" for each catch class, and coalesce the results using // assignment for (IClass c : catchClasses) { if (c.getReference().equals(c.getClassLoader().getLanguage().getThrowableType())) { system.newConstraint(exceptionVar, assignOperator, e); } else { FilteredPointerKey typedException = TypedPointerKey.make(exceptionVar, c); system.newConstraint(typedException, filterOperator, e); system.newConstraint(exceptionVar, assignOperator, typedException); } } } /** A warning for when we fail to resolve a call to an entrypoint */ @SuppressWarnings("unused") private static class ExceptionLookupFailure extends Warning { final TypeReference t; ExceptionLookupFailure(TypeReference t) { super(Warning.SEVERE); this.t = t; } @Override public String getMsg() { return getClass().toString() + " : " + t; } public static ExceptionLookupFailure create(TypeReference t) { return new ExceptionLookupFailure(t); } } /** A pointer key that delegates to an untyped variant, but adds a type filter */ public static final class TypedPointerKey implements FilteredPointerKey { private final IClass type; private final PointerKey base; static TypedPointerKey make(PointerKey base, IClass type) { assert type != null; return new TypedPointerKey(base, type); } private TypedPointerKey(PointerKey base, IClass type) { this.type = type; this.base = base; assert type != null; assert !(type instanceof FilteredPointerKey); } @Override public TypeFilter getTypeFilter() { return new SingleClassFilter(type); } @Override public boolean equals(Object obj) { // instanceof is OK because this class is final if (obj instanceof TypedPointerKey) { TypedPointerKey other = (TypedPointerKey) obj; return type.equals(other.type) && base.equals(other.base); } else { return false; } } @Override public int hashCode() { return 67931 * base.hashCode() + type.hashCode(); } @Override public String toString() { return "{ " + base + " type: " + type + '}'; } public PointerKey getBase() { return base; } } /** * @param catchClasses Set of TypeReference * @param klass an Exception Class * @return true iff klass is a subclass of some element of the Set * @throws IllegalArgumentException if catchClasses is null */ public static boolean catches(Set<IClass> catchClasses, IClass klass, IClassHierarchy cha) { if (catchClasses == null) { throw new IllegalArgumentException("catchClasses is null"); } // quick shortcut if (catchClasses.size() == 1) { IClass c = catchClasses.iterator().next(); if (c != null && c.getReference().equals(TypeReference.JavaLangThread)) { return true; } } for (IClass c : catchClasses) { if (c != null && cha.isAssignableFrom(c, klass)) { return true; } } return false; } public static boolean representsNullType(InstanceKey key) throws IllegalArgumentException { if (key == null) { throw new IllegalArgumentException("key == null"); } IClass cls = key.getConcreteType(); Language L = cls.getClassLoader().getLanguage(); return L.isNullType(cls.getReference()); } /** * The FilterOperator is a filtered set-union. i.e. the LHS is `unioned' with the RHS, but * filtered by the set associated with this operator instance. The filter is the set of * InstanceKeys corresponding to the target type of this cast. This is still monotonic. * * <p>LHS U= (RHS n k) * * <p>Unary op: &lt;lhs&gt;:= Cast_k( &lt;rhs&gt;) * * <p>(Again, technically a binary op -- see note for Assign) * * <p>TODO: these need to be canonicalized. */ public class FilterOperator extends UnaryOperator<PointsToSetVariable> implements IPointerOperator { protected FilterOperator() {} @Override public byte evaluate(PointsToSetVariable lhs, PointsToSetVariable rhs) { FilteredPointerKey pk = (FilteredPointerKey) lhs.getPointerKey(); if (DEBUG_FILTER) { String S = "EVAL Filter " + lhs.getPointerKey() + ' ' + rhs.getPointerKey(); S += "\nEVAL " + lhs + ' ' + rhs; System.err.println(S); } if (rhs.size() == 0) { return NOT_CHANGED; } FilteredPointerKey.TypeFilter filter = pk.getTypeFilter(); boolean changed = filter.addFiltered(system, lhs, rhs); if (DEBUG_FILTER) { System.err.println("RESULT " + lhs + (changed ? " (changed)" : "")); } return changed ? CHANGED : NOT_CHANGED; } @Override public boolean isComplex() { return false; } @Override public String toString() { return "Filter "; } @Override public boolean equals(Object obj) { // these objects are canonicalized for the duration of a solve return this == obj; } @Override public int hashCode() { return 88651; } } @Override public IClassHierarchy getClassHierarchy() { return cha; } public AnalysisOptions getOptions() { return options; } public IClass getJavaLangObject() { return JAVA_LANG_OBJECT; } public ExplicitCallGraph getCallGraph() { return callGraph; } /** Subclasses must register the context interpreter before building a call graph. */ public void setContextInterpreter(SSAContextInterpreter interpreter) { contextInterpreter = interpreter; callGraph.setInterpreter(interpreter); } @Override public PointerAnalysis<InstanceKey> getPointerAnalysis() { return system.extractPointerAnalysis(this); } public PropagationSystem getPropagationSystem() { return system; } public PointerKeyFactory getPointerKeyFactory() { return pointerKeyFactory; } /* BEGIN Custom change: setter for pointerkey factory */ public void setPointerKeyFactory(PointerKeyFactory pkFact) { pointerKeyFactory = pkFact; } /* END Custom change: setter for pointerkey factory */ public RTAContextInterpreter getContextInterpreter() { return contextInterpreter; } /** * @param caller the caller node * @param iKey an abstraction of the receiver of the call (or null if not applicable) * @return the CGNode to which this particular call should dispatch. */ protected CGNode getTargetForCall( CGNode caller, CallSiteReference site, IClass recv, InstanceKey iKey[]) { IMethod targetMethod = options.getMethodTargetSelector().getCalleeTarget(caller, site, recv); // this most likely indicates an exclusion at work; the target selector // should have issued a warning if (targetMethod == null || targetMethod.isAbstract()) { return null; } Context targetContext = contextSelector.getCalleeTarget(caller, site, targetMethod, iKey); if (targetContext == null || targetContext.isA(IllegalArgumentExceptionContext.class)) { return null; } try { return getCallGraph().findOrCreateNode(targetMethod, targetContext); } catch (CancelException e) { return null; } } /** @return the context selector for this call graph builder */ public ContextSelector getContextSelector() { return contextSelector; } public void setContextSelector(ContextSelector selector) { contextSelector = selector; } public InstanceKeyFactory getInstanceKeys() { return instanceKeyFactory; } public void setInstanceKeys(InstanceKeyFactory keys) { this.instanceKeyFactory = keys; } /** * @return the InstanceKey that acts as a representative for the class of objects that includes * objects allocated at the given new instruction in the given node */ public InstanceKey getInstanceKeyForAllocation(CGNode node, NewSiteReference allocation) { return instanceKeyFactory.getInstanceKeyForAllocation(node, allocation); } /** * @param dim the dimension of the array whose instance we would like to model. dim == 0 * represents the first dimension, e.g., the [Object; instances in [[Object; e.g., the * [[Object; instances in [[[Object; dim == 1 represents the second dimension, e.g., the * [Object instances in [[[Object; * @return the InstanceKey that acts as a representative for the class of array contents objects * that includes objects allocated at the given new instruction in the given node */ public InstanceKey getInstanceKeyForMultiNewArray( CGNode node, NewSiteReference allocation, int dim) { return instanceKeyFactory.getInstanceKeyForMultiNewArray(node, allocation, dim); } public <T> InstanceKey getInstanceKeyForConstant(TypeReference type, T S) { return instanceKeyFactory.getInstanceKeyForConstant(type, S); } public InstanceKey getInstanceKeyForMetadataObject(Object obj, TypeReference objType) { return instanceKeyFactory.getInstanceKeyForMetadataObject(obj, objType); } public boolean haveAlreadyVisited(CGNode node) { return alreadyVisited.contains(node); } protected void markAlreadyVisited(CGNode node) { alreadyVisited.add(node); } /** record that we've discovered a node */ public void markDiscovered(CGNode node) { discoveredNodes.add(node); } protected void markChanged(CGNode node) { alreadyVisited.remove(node); discoveredNodes.add(node); } protected boolean wasChanged(CGNode node) { return discoveredNodes.contains(node) && !alreadyVisited.contains(node); } /** Binary op: &lt;dummy&gt;:= ArrayLoad( &lt;arrayref&gt;) Side effect: Creates new equations. */ public final class ArrayLoadOperator extends UnarySideEffect implements IPointerOperator { private final MutableIntSet priorInstances = rememberGetPutHistory ? IntSetUtil.make() : null; @Override public String toString() { return "ArrayLoad"; } public ArrayLoadOperator(PointsToSetVariable def) { super(def); system.registerFixedSet(def, this); } @Override public byte evaluate(PointsToSetVariable rhs) { if (DEBUG_ARRAY_LOAD) { PointsToSetVariable def = getFixedSet(); String S = "EVAL ArrayLoad " + rhs.getPointerKey() + ' ' + def.getPointerKey(); System.err.println(S); System.err.println("EVAL ArrayLoad " + def + ' ' + rhs); if (priorInstances != null) { System.err.println( "prior instances: " + priorInstances + ' ' + priorInstances.getClass()); } } if (rhs.size() == 0) { return NOT_CHANGED; } PointsToSetVariable def = getFixedSet(); final PointerKey dVal = def.getPointerKey(); final MutableBoolean sideEffect = new MutableBoolean(); IntSetAction action = i -> { InstanceKey I = system.getInstanceKey(i); if (!I.getConcreteType().isArrayClass()) { return; } TypeReference C = I.getConcreteType().getReference().getArrayElementType(); if (C.isPrimitiveType()) { return; } PointerKey p = getPointerKeyForArrayContents(I); if (p == null) { return; } if (DEBUG_ARRAY_LOAD) { System.err.println("ArrayLoad add assign: " + dVal + ' ' + p); } sideEffect.b |= system.newFieldRead(dVal, assignOperator, p); }; if (priorInstances != null) { rhs.getValue().foreachExcluding(priorInstances, action); priorInstances.addAll(rhs.getValue()); } else { rhs.getValue().foreach(action); } byte sideEffectMask = sideEffect.b ? (byte) SIDE_EFFECT_MASK : 0; return (byte) (NOT_CHANGED | sideEffectMask); } @Override public int hashCode() { return 9871 + super.hashCode(); } @Override public boolean equals(Object o) { return super.equals(o); } @Override protected boolean isLoadOperator() { return true; } @Override public boolean isComplex() { return true; } } /** * Binary op: &lt;dummy&gt;:= ArrayStore( &lt;arrayref&gt;) Side effect: Creates new equations. */ public final class ArrayStoreOperator extends UnarySideEffect implements IPointerOperator { @Override public String toString() { return "ArrayStore"; } public ArrayStoreOperator(PointsToSetVariable val) { super(val); system.registerFixedSet(val, this); } @Override public byte evaluate(PointsToSetVariable rhs) { if (DEBUG_ARRAY_STORE) { PointsToSetVariable val = getFixedSet(); String S = "EVAL ArrayStore " + rhs.getPointerKey() + ' ' + val.getPointerKey(); System.err.println(S); System.err.println("EVAL ArrayStore " + rhs + ' ' + getFixedSet()); } if (rhs.size() == 0) { return NOT_CHANGED; } PointsToSetVariable val = getFixedSet(); PointerKey pVal = val.getPointerKey(); List<InstanceKey> instances = system.getInstances(rhs.getValue()); boolean sideEffect = false; for (InstanceKey I : instances) { if (!I.getConcreteType().isArrayClass()) { continue; } if (I instanceof ZeroLengthArrayInNode) { continue; } TypeReference C = I.getConcreteType().getReference().getArrayElementType(); if (C.isPrimitiveType()) { continue; } IClass contents = getClassHierarchy().lookupClass(C); if (contents == null) { assert false : "null type for " + C + ' ' + I.getConcreteType(); } PointerKey p = getPointerKeyForArrayContents(I); if (DEBUG_ARRAY_STORE) { System.err.println("ArrayStore add filtered-assign: " + p + ' ' + pVal); } // note that the following is idempotent if (isJavaLangObject(contents)) { sideEffect |= system.newFieldWrite(p, assignOperator, pVal); } else { sideEffect |= system.newFieldWrite(p, filterOperator, pVal); } } byte sideEffectMask = sideEffect ? (byte) SIDE_EFFECT_MASK : 0; return (byte) (NOT_CHANGED | sideEffectMask); } @Override public int hashCode() { return 9859 + super.hashCode(); } @Override public boolean isComplex() { return true; } @Override public boolean equals(Object o) { return super.equals(o); } @Override protected boolean isLoadOperator() { return false; } } /** Binary op: &lt;dummy&gt;:= GetField( &lt;ref&gt;) Side effect: Creates new equations. */ public class GetFieldOperator extends UnarySideEffect implements IPointerOperator { private final IField field; protected final MutableIntSet priorInstances = rememberGetPutHistory ? IntSetUtil.make() : null; public GetFieldOperator(IField field, PointsToSetVariable def) { super(def); this.field = field; system.registerFixedSet(def, this); } @Override public String toString() { return "GetField " + getField() + ',' + getFixedSet().getPointerKey(); } @Override public byte evaluate(PointsToSetVariable rhs) { if (DEBUG_GET) { String S = "EVAL GetField " + getField() + ' ' + getFixedSet().getPointerKey() + ' ' + rhs.getPointerKey() + getFixedSet() + ' ' + rhs; System.err.println(S); } PointsToSetVariable ref = rhs; if (ref.size() == 0) { return NOT_CHANGED; } PointsToSetVariable def = getFixedSet(); final PointerKey dVal = def.getPointerKey(); IntSet value = filterInstances(ref.getValue()); if (DEBUG_GET) { System.err.println("filtered value: " + value + ' ' + value.getClass()); if (priorInstances != null) { System.err.println( "prior instances: " + priorInstances + ' ' + priorInstances.getClass()); } } final MutableBoolean sideEffect = new MutableBoolean(); IntSetAction action = i -> { InstanceKey I = system.getInstanceKey(i); if (!representsNullType(I)) { PointerKey p = getPointerKeyForInstanceField(I, getField()); if (p != null) { if (DEBUG_GET) { String S = "Getfield add constraint " + dVal + ' ' + p; System.err.println(S); } sideEffect.b |= system.newFieldRead(dVal, assignOperator, p); } } }; if (priorInstances != null) { value.foreachExcluding(priorInstances, action); priorInstances.addAll(value); } else { value.foreach(action); } byte sideEffectMask = sideEffect.b ? (byte) SIDE_EFFECT_MASK : 0; return (byte) (NOT_CHANGED | sideEffectMask); } /** Subclasses can override as needed */ protected IntSet filterInstances(IntSet value) { return value; } @Override public int hashCode() { return 9857 * getField().hashCode() + getFixedSet().hashCode(); } @Override public boolean equals(Object o) { if (o instanceof GetFieldOperator) { GetFieldOperator other = (GetFieldOperator) o; return getField().equals(other.getField()) && getFixedSet().equals(other.getFixedSet()); } else { return false; } } protected IField getField() { return field; } @Override protected boolean isLoadOperator() { return true; } @Override public boolean isComplex() { return true; } } /** Operator that represents a putfield */ public class PutFieldOperator extends UnarySideEffect implements IPointerOperator { private final IField field; protected final MutableIntSet priorInstances = rememberGetPutHistory ? IntSetUtil.make() : null; @Override public String toString() { return "PutField" + getField(); } public PutFieldOperator(IField field, PointsToSetVariable val) { super(val); this.field = field; system.registerFixedSet(val, this); } @Override public boolean isComplex() { return true; } @Override public byte evaluate(PointsToSetVariable rhs) { if (DEBUG_PUT) { String S = "EVAL PutField " + getField() + ' ' + getFixedSet().getPointerKey() + ' ' + rhs.getPointerKey() + getFixedSet() + ' ' + rhs; System.err.println(S); } if (rhs.size() == 0) { return NOT_CHANGED; } PointsToSetVariable val = getFixedSet(); final PointerKey pVal = val.getPointerKey(); IntSet value = rhs.getValue(); value = filterInstances(value); final UnaryOperator<PointsToSetVariable> assign = getPutAssignmentOperator(); if (assign == null) { Assertions.UNREACHABLE(); } final MutableBoolean sideEffect = new MutableBoolean(); IntSetAction action = i -> { InstanceKey I = system.getInstanceKey(i); if (!representsNullType(I)) { if (DEBUG_PUT) { String S1 = "Putfield consider instance " + I; System.err.println(S1); } PointerKey p = getPointerKeyForInstanceField(I, getField()); if (p != null) { if (DEBUG_PUT) { String S2 = "Putfield add constraint " + p + ' ' + pVal; System.err.println(S2); } sideEffect.b |= system.newFieldWrite(p, assign, pVal); } } }; if (priorInstances != null) { value.foreachExcluding(priorInstances, action); priorInstances.addAll(value); } else { value.foreach(action); } byte sideEffectMask = sideEffect.b ? (byte) SIDE_EFFECT_MASK : 0; return (byte) (NOT_CHANGED | sideEffectMask); } /** Subclasses can override as needed */ protected IntSet filterInstances(IntSet value) { return value; } @Override public int hashCode() { return 9857 * getField().hashCode() + getFixedSet().hashCode(); } @Override public boolean equals(Object o) { if (o != null && o.getClass().equals(getClass())) { PutFieldOperator other = (PutFieldOperator) o; return getField().equals(other.getField()) && getFixedSet().equals(other.getFixedSet()); } else { return false; } } /** * subclasses (e.g. XTA) can override this to enforce a filtered assignment. returns null if * there's a problem. */ public UnaryOperator<PointsToSetVariable> getPutAssignmentOperator() { return assignOperator; } /** @return Returns the field. */ protected IField getField() { return field; } @Override protected boolean isLoadOperator() { return false; } } /** Update the points-to-set for a field to include a particular instance key. */ public final class InstancePutFieldOperator extends UnaryOperator<PointsToSetVariable> implements IPointerOperator { private final IField field; private final InstanceKey instance; private final MutableIntSet priorInstances = rememberGetPutHistory ? IntSetUtil.make() : null; @Override public String toString() { return "InstancePutField" + field; } public InstancePutFieldOperator(IField field, InstanceKey instance) { this.field = field; this.instance = instance; } /** Simply add the instance to each relevant points-to set. */ @Override public byte evaluate(PointsToSetVariable dummyLHS, PointsToSetVariable var) { PointsToSetVariable ref = var; if (ref.size() == 0) { return NOT_CHANGED; } IntSet value = ref.getValue(); final MutableBoolean sideEffect = new MutableBoolean(); IntSetAction action = i -> { InstanceKey I = system.getInstanceKey(i); if (!representsNullType(I)) { PointerKey p = getPointerKeyForInstanceField(I, field); if (p != null) { sideEffect.b |= system.newConstraint(p, instance); } } }; if (priorInstances != null) { value.foreachExcluding(priorInstances, action); priorInstances.addAll(value); } else { value.foreach(action); } byte sideEffectMask = sideEffect.b ? (byte) SIDE_EFFECT_MASK : 0; return (byte) (NOT_CHANGED | sideEffectMask); } @Override public int hashCode() { return field.hashCode() + 9839 * instance.hashCode(); } @Override public boolean equals(Object o) { if (o instanceof InstancePutFieldOperator) { InstancePutFieldOperator other = (InstancePutFieldOperator) o; return field.equals(other.field) && instance.equals(other.instance); } else { return false; } } @Override public boolean isComplex() { return true; } } /** Update the points-to-set for an array contents to include a particular instance key. */ public final class InstanceArrayStoreOperator extends UnaryOperator<PointsToSetVariable> implements IPointerOperator { private final InstanceKey instance; private final MutableIntSet priorInstances = rememberGetPutHistory ? IntSetUtil.make() : null; @Override public String toString() { return "InstanceArrayStore "; } public InstanceArrayStoreOperator(InstanceKey instance) { this.instance = instance; } /** Simply add the instance to each relevant points-to set. */ @Override public byte evaluate(PointsToSetVariable dummyLHS, PointsToSetVariable var) { PointsToSetVariable arrayref = var; if (arrayref.size() == 0) { return NOT_CHANGED; } IntSet value = arrayref.getValue(); final MutableBoolean sideEffect = new MutableBoolean(); IntSetAction action = i -> { InstanceKey I = system.getInstanceKey(i); if (!I.getConcreteType().isArrayClass()) { return; } if (I instanceof ZeroLengthArrayInNode) { return; } TypeReference C = I.getConcreteType().getReference().getArrayElementType(); if (C.isPrimitiveType()) { return; } IClass contents = getClassHierarchy().lookupClass(C); if (contents == null) { assert false : "null type for " + C + ' ' + I.getConcreteType(); } PointerKey p = getPointerKeyForArrayContents(I); if (contents.isInterface()) { if (getClassHierarchy().implementsInterface(instance.getConcreteType(), contents)) { sideEffect.b |= system.newConstraint(p, instance); } } else { if (getClassHierarchy().isSubclassOf(instance.getConcreteType(), contents)) { sideEffect.b |= system.newConstraint(p, instance); } } }; if (priorInstances != null) { value.foreachExcluding(priorInstances, action); priorInstances.addAll(value); } else { value.foreach(action); } byte sideEffectMask = sideEffect.b ? (byte) SIDE_EFFECT_MASK : 0; return (byte) (NOT_CHANGED | sideEffectMask); } @Override public int hashCode() { return 9839 * instance.hashCode(); } @Override public boolean equals(Object o) { if (o instanceof InstanceArrayStoreOperator) { InstanceArrayStoreOperator other = (InstanceArrayStoreOperator) o; return instance.equals(other.instance); } else { return false; } } @Override public boolean isComplex() { return true; } } protected MutableIntSet getMutableInstanceKeysForClass(IClass klass) { return system.cloneInstanceKeysForClass(klass); } protected IntSet getInstanceKeysForClass(IClass klass) { return system.getInstanceKeysForClass(klass); } /** * @param klass a class * @return an int set which represents the subset of S that correspond to subtypes of klass */ @SuppressWarnings("unused") protected IntSet filterForClass(IntSet S, IClass klass) { MutableIntSet filter = null; if (klass.getReference().equals(TypeReference.JavaLangObject)) { return S; } else { filter = getMutableInstanceKeysForClass(klass); boolean debug = false; if (DEBUG_FILTER) { String s = "klass " + klass; System.err.println(s); System.err.println("initial filter " + filter); } filter.intersectWith(S); if (DEBUG_FILTER && debug) { System.err.println("final filter " + filter); } } return filter; } protected class InverseFilterOperator extends FilterOperator { public InverseFilterOperator() { super(); } @Override public String toString() { return "InverseFilter"; } /** @see com.ibm.wala.ipa.callgraph.propagation.IPointerOperator#isComplex() */ @Override public boolean isComplex() { return false; } /* * simply check if rhs contains a malleable. * * @see com.ibm.wala.dataflow.UnaryOperator#evaluate(com.ibm.wala.dataflow.IVariable, com.ibm.wala.dataflow.IVariable) */ @Override public byte evaluate(PointsToSetVariable lhs, PointsToSetVariable rhs) { FilteredPointerKey pk = (FilteredPointerKey) lhs.getPointerKey(); FilteredPointerKey.TypeFilter filter = pk.getTypeFilter(); boolean debug = false; if (DEBUG_FILTER) { String S = "EVAL InverseFilter/" + filter + ' ' + lhs.getPointerKey() + ' ' + rhs.getPointerKey(); S += "\nEVAL " + lhs + ' ' + rhs; System.err.println(S); } if (rhs.size() == 0) { return NOT_CHANGED; } boolean changed = filter.addInverseFiltered(system, lhs, rhs); if (DEBUG_FILTER) { if (debug) { System.err.println("RESULT " + lhs + (changed ? " (changed)" : "")); } } return changed ? CHANGED : NOT_CHANGED; } } protected IPointsToSolver getSolver() { return solver; } /** Add constraints when the interpretation of a node changes (e.g. reflection) */ public void addConstraintsFromChangedNode(CGNode node, IProgressMonitor monitor) throws CancelException { unconditionallyAddConstraintsFromNode(node, monitor); } protected abstract boolean unconditionallyAddConstraintsFromNode( CGNode node, IProgressMonitor monitor) throws CancelException; protected static class MutableBoolean { // a horrendous hack since we don't have closures boolean b = false; } @Override public IAnalysisCacheView getAnalysisCache() { return analysisCache; } }
45,673
31.142153
122
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/ipa/callgraph/propagation/PropagationGraph.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.ipa.callgraph.propagation; import com.ibm.wala.fixedpoint.impl.GeneralStatement; import com.ibm.wala.fixpoint.AbstractOperator; import com.ibm.wala.fixpoint.AbstractStatement; import com.ibm.wala.fixpoint.IFixedPointStatement; import com.ibm.wala.fixpoint.IFixedPointSystem; import com.ibm.wala.fixpoint.IVariable; import com.ibm.wala.fixpoint.UnaryOperator; import com.ibm.wala.fixpoint.UnaryStatement; import com.ibm.wala.util.collections.*; import com.ibm.wala.util.debug.Assertions; import com.ibm.wala.util.debug.UnimplementedError; import com.ibm.wala.util.graph.AbstractNumberedGraph; import com.ibm.wala.util.graph.Graph; import com.ibm.wala.util.graph.INodeWithNumber; import com.ibm.wala.util.graph.NumberedEdgeManager; import com.ibm.wala.util.graph.NumberedGraph; import com.ibm.wala.util.graph.NumberedNodeManager; import com.ibm.wala.util.graph.impl.DelegatingNumberedNodeManager; import com.ibm.wala.util.graph.impl.SparseNumberedEdgeManager; import com.ibm.wala.util.graph.traverse.Topological; import com.ibm.wala.util.heapTrace.HeapTracer; import com.ibm.wala.util.intset.BasicNaturalRelation; import com.ibm.wala.util.intset.IBinaryNaturalRelation; import com.ibm.wala.util.intset.IntIterator; import com.ibm.wala.util.intset.IntPair; import com.ibm.wala.util.intset.IntSet; import java.util.ArrayList; import java.util.Collections; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; /** A dataflow graph implementation specialized for propagation-based pointer analysis */ public class PropagationGraph implements IFixedPointSystem<PointsToSetVariable> { private static final boolean DEBUG = false; private static final boolean VERBOSE = false; /** Track nodes (PointsToSet Variables and AbstractEquations) */ private final NumberedNodeManager<INodeWithNumber> nodeManager = new DelegatingNumberedNodeManager<>(); /** Track edges (equations) that are not represented implicitly */ private final NumberedEdgeManager<INodeWithNumber> edgeManager = new SparseNumberedEdgeManager<>(nodeManager, 2, BasicNaturalRelation.SIMPLE); private final DelegateGraph delegateGraph = new DelegateGraph(); private final HashSet<IFixedPointStatement<PointsToSetVariable>> delegateStatements = HashSetFactory.make(); /** * special representation for implicitly represented unary equations. This is a map from * UnaryOperator -> IBinaryNonNegativeIntRelation. * * <p>for UnaryOperator op, let R be implicitMap.get(op) then (i,j) \in R implies i op j is an * equation in the graph */ private final SmallMap<UnaryOperator<PointsToSetVariable>, IBinaryNaturalRelation> implicitUnaryMap = new SmallMap<>(); /** * The inverse of relations in the implicit map * * <p>for UnaryOperator op, let R be invImplicitMap.get(op) then (i,j) \in R implies j op i is an * equation in the graph */ private final SmallMap<UnaryOperator<PointsToSetVariable>, IBinaryNaturalRelation> invImplicitUnaryMap = new SmallMap<>(); /** Number of implicit unary equations registered */ private int implicitUnaryCount = 0; /** @return a relation in map m corresponding to a key */ private static IBinaryNaturalRelation findOrCreateRelation( Map<UnaryOperator<PointsToSetVariable>, IBinaryNaturalRelation> m, UnaryOperator<PointsToSetVariable> key) { IBinaryNaturalRelation result = m.get(key); if (result == null) { result = makeRelation(key); m.put(key, result); } return result; } /** @return a Relation object to track implicit equations using the operator */ private static IBinaryNaturalRelation makeRelation(AbstractOperator<PointsToSetVariable> op) { byte[] implementation = null; if (op instanceof AssignOperator) { // lots of assignments. implementation = new byte[] { BasicNaturalRelation.SIMPLE_SPACE_STINGY, BasicNaturalRelation.SIMPLE_SPACE_STINGY }; } else { // assume sparse assignments with any other operator. implementation = new byte[] {BasicNaturalRelation.SIMPLE_SPACE_STINGY}; } return new BasicNaturalRelation(implementation, BasicNaturalRelation.SIMPLE); } /** * @author sfink * <p>A graph which tracks explicit equations. * <p>use this with care ... */ private class DelegateGraph extends AbstractNumberedGraph<INodeWithNumber> { private int equationCount = 0; private int varCount = 0; @Override public void addNode(INodeWithNumber o) { Assertions.UNREACHABLE("Don't call me"); } public void addEquation(AbstractStatement<PointsToSetVariable, ?> eq) { assert !containsStatement(eq); equationCount++; super.addNode(eq); } public void addVariable(PointsToSetVariable v) { if (!containsVariable(v)) { varCount++; super.addNode(v); } } /** @see com.ibm.wala.util.graph.AbstractGraph#getNodeManager() */ @Override protected NumberedNodeManager<INodeWithNumber> getNodeManager() { return nodeManager; } /** @see com.ibm.wala.util.graph.AbstractGraph#getEdgeManager() */ @Override protected NumberedEdgeManager<INodeWithNumber> getEdgeManager() { return edgeManager; } protected int getEquationCount() { return equationCount; } protected int getVarCount() { return varCount; } } /** @throws IllegalArgumentException if eq is null */ public void addStatement(GeneralStatement<PointsToSetVariable> eq) { if (eq == null) { throw new IllegalArgumentException("eq is null"); } PointsToSetVariable lhs = eq.getLHS(); delegateGraph.addEquation(eq); delegateStatements.add(eq); if (lhs != null) { delegateGraph.addVariable(lhs); delegateGraph.addEdge(eq, lhs); } for (int i = 0; i < eq.getRHS().length; i++) { PointsToSetVariable v = eq.getRHS()[i]; if (v != null) { delegateGraph.addVariable(v); delegateGraph.addEdge(v, eq); } } } public void addStatement(UnaryStatement<PointsToSetVariable> eq) throws IllegalArgumentException { if (eq == null) { throw new IllegalArgumentException("eq == null"); } if (useImplicitRepresentation(eq)) { addImplicitStatement(eq); } else { PointsToSetVariable lhs = eq.getLHS(); PointsToSetVariable rhs = eq.getRightHandSide(); delegateGraph.addEquation(eq); delegateStatements.add(eq); if (lhs != null) { delegateGraph.addVariable(lhs); delegateGraph.addEdge(eq, lhs); } delegateGraph.addVariable(rhs); delegateGraph.addEdge(rhs, eq); } } /** @return true iff this equation should be represented implicitly in this data structure */ private static boolean useImplicitRepresentation(IFixedPointStatement<PointsToSetVariable> s) { AbstractStatement<?, ?> eq = (AbstractStatement<?, ?>) s; AbstractOperator<?> op = eq.getOperator(); return (op instanceof AssignOperator || op instanceof PropagationCallGraphBuilder.FilterOperator); } public void removeVariable(PointsToSetVariable p) { assert getNumberOfStatementsThatDef(p) == 0; assert getNumberOfStatementsThatUse(p) == 0; delegateGraph.removeNode(p); } private void addImplicitStatement(UnaryStatement<PointsToSetVariable> eq) { if (DEBUG) { System.err.println(("addImplicitStatement " + eq)); } delegateGraph.addVariable(eq.getLHS()); delegateGraph.addVariable(eq.getRightHandSide()); int lhs = eq.getLHS().getGraphNodeId(); int rhs = eq.getRightHandSide().getGraphNodeId(); if (DEBUG) { System.err.println(("lhs rhs " + lhs + ' ' + rhs)); } IBinaryNaturalRelation R = findOrCreateRelation(implicitUnaryMap, eq.getOperator()); boolean b = R.add(lhs, rhs); if (b) { implicitUnaryCount++; IBinaryNaturalRelation iR = findOrCreateRelation(invImplicitUnaryMap, eq.getOperator()); iR.add(rhs, lhs); } } private void removeImplicitStatement(UnaryStatement<PointsToSetVariable> eq) { if (DEBUG) { System.err.println(("removeImplicitStatement " + eq)); } int lhs = eq.getLHS().getGraphNodeId(); int rhs = eq.getRightHandSide().getGraphNodeId(); if (DEBUG) { System.err.println(("lhs rhs " + lhs + ' ' + rhs)); } IBinaryNaturalRelation R = findOrCreateRelation(implicitUnaryMap, eq.getOperator()); R.remove(lhs, rhs); IBinaryNaturalRelation iR = findOrCreateRelation(invImplicitUnaryMap, eq.getOperator()); iR.remove(rhs, lhs); implicitUnaryCount--; } @Override public Iterator<AbstractStatement> getStatements() { Iterator<AbstractStatement> it = IteratorUtil.filter(delegateGraph.iterator(), AbstractStatement.class); return new CompoundIterator<>(it, new GlobalImplicitIterator()); } /** Iterator of implicit equations that use a particular variable. */ private final class ImplicitUseIterator implements Iterator<AbstractStatement> { final PointsToSetVariable use; final IntIterator defs; final UnaryOperator<PointsToSetVariable> op; ImplicitUseIterator( UnaryOperator<PointsToSetVariable> op, PointsToSetVariable use, IntSet defs) { this.op = op; this.use = use; this.defs = defs.intIterator(); } @Override public boolean hasNext() { return defs.hasNext(); } @Override public AbstractStatement<?, ?> next() { int l = defs.next(); PointsToSetVariable lhs = (PointsToSetVariable) delegateGraph.getNode(l); UnaryStatement<?> temp = op.makeEquation(lhs, use); if (DEBUG) { System.err.print(("XX Return temp: " + temp)); System.err.println(("lhs rhs " + l + ' ' + use.getGraphNodeId())); } return temp; } @Override public void remove() { // TODO Auto-generated method stub Assertions.UNREACHABLE(); } } /** Iterator of implicit equations that def a particular variable. */ private final class ImplicitDefIterator implements Iterator<AbstractStatement> { final PointsToSetVariable def; final IntIterator uses; final UnaryOperator<PointsToSetVariable> op; ImplicitDefIterator( UnaryOperator<PointsToSetVariable> op, IntSet uses, PointsToSetVariable def) { this.op = op; this.def = def; this.uses = uses.intIterator(); } @Override public boolean hasNext() { return uses.hasNext(); } @Override public AbstractStatement<?, ?> next() { int r = uses.next(); PointsToSetVariable rhs = (PointsToSetVariable) delegateGraph.getNode(r); UnaryStatement<?> temp = op.makeEquation(def, rhs); if (DEBUG) { System.err.print(("YY Return temp: " + temp)); } return temp; } @Override public void remove() { // TODO Auto-generated method stub Assertions.UNREACHABLE(); } } /** Iterator of all implicit equations */ private class GlobalImplicitIterator implements Iterator<AbstractStatement> { private final Iterator<UnaryOperator<PointsToSetVariable>> outerKeyDelegate = implicitUnaryMap.keySet().iterator(); private Iterator<IntPair> innerDelegate; private UnaryOperator<PointsToSetVariable> currentOperator; GlobalImplicitIterator() { advanceOuter(); } /** advance to the next operator */ private void advanceOuter() { innerDelegate = null; while (outerKeyDelegate.hasNext()) { currentOperator = outerKeyDelegate.next(); IBinaryNaturalRelation R = implicitUnaryMap.get(currentOperator); Iterator<IntPair> it = R.iterator(); if (it.hasNext()) { innerDelegate = it; return; } } } @Override public boolean hasNext() { return innerDelegate != null; } @Override public AbstractStatement<?, ?> next() { IntPair p = innerDelegate.next(); int lhs = p.getX(); int rhs = p.getY(); UnaryStatement<?> result = currentOperator.makeEquation( (PointsToSetVariable) delegateGraph.getNode(lhs), (PointsToSetVariable) delegateGraph.getNode(rhs)); if (!innerDelegate.hasNext()) { advanceOuter(); } return result; } @Override public void remove() { // TODO Auto-generated method stub Assertions.UNREACHABLE(); } } @Override public void removeStatement(IFixedPointStatement<PointsToSetVariable> eq) throws IllegalArgumentException { if (eq == null) { throw new IllegalArgumentException("eq == null"); } if (useImplicitRepresentation(eq)) { removeImplicitStatement((UnaryStatement<PointsToSetVariable>) eq); } else { delegateStatements.remove(eq); delegateGraph.removeNodeAndEdges(eq); } } @Override public void reorder() { VariableGraphView graph = new VariableGraphView(); Iterator<PointsToSetVariable> order = Topological.makeTopologicalIter(graph).iterator(); int number = 0; while (order.hasNext()) { IVariable<?> elt = order.next(); if (elt != null) { elt.setOrderNumber(number++); } } } /** * A graph of just the variables in the system. v1 -&gt; v2 iff there exists equation e s.t. e * uses v1 and e defs v2. * * <p>Note that this graph trickily and fragilely reuses the nodeManager from the delegateGraph, * above. This will work ok as long as every variable is inserted in the delegateGraph. */ private class VariableGraphView extends AbstractNumberedGraph<PointsToSetVariable> { /** @see com.ibm.wala.util.graph.Graph#removeNodeAndEdges(java.lang.Object) */ @Override public void removeNodeAndEdges(PointsToSetVariable N) { Assertions.UNREACHABLE(); } /** @see com.ibm.wala.util.graph.NodeManager#iterator() */ @Override public Iterator<PointsToSetVariable> iterator() { return getVariables(); } /** @see com.ibm.wala.util.graph.NodeManager#getNumberOfNodes() */ @Override public int getNumberOfNodes() { return delegateGraph.getVarCount(); } /** @see com.ibm.wala.util.graph.NodeManager#addNode(java.lang.Object) */ @Override public void addNode(PointsToSetVariable n) { assert containsNode(n); } /** @see com.ibm.wala.util.graph.NodeManager#removeNode(java.lang.Object) */ @Override public void removeNode(PointsToSetVariable n) { Assertions.UNREACHABLE(); } /** @see com.ibm.wala.util.graph.NodeManager#containsNode(java.lang.Object) */ @Override public boolean containsNode(PointsToSetVariable N) { return delegateGraph.containsNode(N); } /** @see com.ibm.wala.util.graph.EdgeManager#getPredNodes(java.lang.Object) */ @Override public Iterator<PointsToSetVariable> getPredNodes(PointsToSetVariable v) { final Iterator<AbstractStatement<PointsToSetVariable, ?>> eqs = getStatementsThatDef(v); return new Iterator<>() { Iterator<INodeWithNumber> inner; @Override public boolean hasNext() { return eqs.hasNext() || (inner != null); } @Override public PointsToSetVariable next() { if (inner != null) { PointsToSetVariable result = (PointsToSetVariable) inner.next(); if (!inner.hasNext()) { inner = null; } return result; } else { AbstractStatement<PointsToSetVariable, ?> eq = eqs.next(); if (useImplicitRepresentation(eq)) { return (PointsToSetVariable) ((UnaryStatement<?>) eq).getRightHandSide(); } else { inner = delegateGraph.getPredNodes(eq); return next(); } } } @Override public void remove() { // TODO Auto-generated method stub Assertions.UNREACHABLE(); } }; } /** @see com.ibm.wala.util.graph.EdgeManager#getPredNodeCount(java.lang.Object) */ @Override public int getPredNodeCount(PointsToSetVariable v) { int result = 0; for (AbstractStatement<PointsToSetVariable, ?> eq : Iterator2Iterable.make(getStatementsThatDef(v))) { if (useImplicitRepresentation(eq)) { result++; } else { result += delegateGraph.getPredNodeCount(v); } } return result; } /** @see com.ibm.wala.util.graph.EdgeManager#getSuccNodes(java.lang.Object) */ @Override public Iterator<PointsToSetVariable> getSuccNodes(PointsToSetVariable v) { final Iterator<AbstractStatement> eqs = getStatementsThatUse(v); return new Iterator<>() { PointsToSetVariable nextResult; { advance(); } @Override public boolean hasNext() { return nextResult != null; } @Override public PointsToSetVariable next() { PointsToSetVariable result = nextResult; advance(); return result; } private void advance() { nextResult = null; while (eqs.hasNext() && nextResult == null) { AbstractStatement<?, ?> eq = eqs.next(); nextResult = (PointsToSetVariable) eq.getLHS(); } } @Override public void remove() { // TODO Auto-generated method stub Assertions.UNREACHABLE(); } }; } /** @see com.ibm.wala.util.graph.EdgeManager#getSuccNodeCount(java.lang.Object) */ @Override public int getSuccNodeCount(PointsToSetVariable v) { int result = 0; for (AbstractStatement<?, ?> eq : Iterator2Iterable.make(getStatementsThatUse(v))) { IVariable<?> lhs = eq.getLHS(); if (lhs != null) { result++; } } return result; } /** @see com.ibm.wala.util.graph.EdgeManager#addEdge(java.lang.Object, java.lang.Object) */ @Override public void addEdge(PointsToSetVariable src, PointsToSetVariable dst) { Assertions.UNREACHABLE(); } /** @see com.ibm.wala.util.graph.EdgeManager#removeAllIncidentEdges(java.lang.Object) */ @Override public void removeAllIncidentEdges(PointsToSetVariable node) { Assertions.UNREACHABLE(); } /** @see com.ibm.wala.util.graph.AbstractGraph#getNodeManager() */ @Override @SuppressWarnings("unchecked") protected NumberedNodeManager getNodeManager() { return nodeManager; } /** @see com.ibm.wala.util.graph.AbstractGraph#getEdgeManager() */ @Override @SuppressWarnings("unchecked") protected NumberedEdgeManager getEdgeManager() { return this; } } @Override public Iterator<AbstractStatement> getStatementsThatUse(PointsToSetVariable v) { if (v == null) { throw new IllegalArgumentException("v is null"); } int number = v.getGraphNodeId(); if (number == -1) { return EmptyIterator.instance(); } Iterator<INodeWithNumber> result = delegateGraph.getSuccNodes(v); for (int i = 0; i < invImplicitUnaryMap.size(); i++) { UnaryOperator<PointsToSetVariable> op = invImplicitUnaryMap.getKey(i); IBinaryNaturalRelation R = invImplicitUnaryMap.getValue(i); IntSet s = R.getRelated(number); if (s != null) { result = new CompoundIterator<>(new ImplicitUseIterator(op, v, s), result); } } List<AbstractStatement> list = new ArrayList<>(); while (result.hasNext()) { list.add((AbstractStatement<?, ?>) result.next()); } return list.iterator(); } @Override @SuppressWarnings("unchecked") public Iterator<AbstractStatement<PointsToSetVariable, ?>> getStatementsThatDef( PointsToSetVariable v) { if (v == null) { throw new IllegalArgumentException("v is null"); } int number = v.getGraphNodeId(); if (number == -1) { return EmptyIterator.instance(); } Iterator<INodeWithNumber> result = delegateGraph.getPredNodes(v); for (int i = 0; i < implicitUnaryMap.size(); i++) { UnaryOperator<PointsToSetVariable> op = implicitUnaryMap.getKey(i); IBinaryNaturalRelation R = implicitUnaryMap.getValue(i); IntSet s = R.getRelated(number); if (s != null) { result = new CompoundIterator<>(new ImplicitDefIterator(op, s, v), result); } } List<AbstractStatement<PointsToSetVariable, ?>> list = new ArrayList<>(); while (result.hasNext()) { list.add((AbstractStatement) result.next()); } return list.iterator(); } /** * Note that this implementation consults the implicit relation for each and every operator * cached. This will be inefficient if there are many implicit operators. * * @throws IllegalArgumentException if v is null */ @Override public int getNumberOfStatementsThatUse(PointsToSetVariable v) { if (v == null) { throw new IllegalArgumentException("v is null"); } int number = v.getGraphNodeId(); if (number == -1) { return 0; } int result = delegateGraph.getSuccNodeCount(v); for (IBinaryNaturalRelation R : invImplicitUnaryMap.values()) { IntSet s = R.getRelated(number); if (s != null) { result += s.size(); } } return result; } @Override public int getNumberOfStatementsThatDef(PointsToSetVariable v) { if (v == null) { throw new IllegalArgumentException("v is null"); } int number = v.getGraphNodeId(); if (number == -1) { return 0; } int result = delegateGraph.getPredNodeCount(v); for (IBinaryNaturalRelation R : implicitUnaryMap.values()) { IntSet s = R.getRelated(number); if (s != null) { result += s.size(); } } return result; } @Override public Iterator<PointsToSetVariable> getVariables() { return IteratorUtil.filter(delegateGraph.iterator(), PointsToSetVariable.class); } /** @see com.ibm.wala.util.debug.VerboseAction#performVerboseAction() */ public void performVerboseAction() { if (VERBOSE) { System.err.println(("stats for " + getClass())); System.err.println(("number of variables: " + delegateGraph.getVarCount())); System.err.println(("implicit equations: " + implicitUnaryCount)); System.err.println(("explicit equations: " + delegateGraph.getEquationCount())); System.err.println("implicit map:"); int count = 0; int totalBytes = 0; for (Map.Entry<UnaryOperator<PointsToSetVariable>, IBinaryNaturalRelation> entry : implicitUnaryMap.entrySet()) { count++; Map.Entry<?, IBinaryNaturalRelation> e = entry; IBinaryNaturalRelation R = e.getValue(); System.err.println(("entry " + count)); R.performVerboseAction(); HeapTracer.Result result = HeapTracer.traceHeap(Collections.singleton(R), false); totalBytes += result.getTotalSize(); } System.err.println(("bytes in implicit map: " + totalBytes)); } } @Override public boolean containsStatement(IFixedPointStatement<PointsToSetVariable> eq) throws IllegalArgumentException { if (eq == null) { throw new IllegalArgumentException("eq == null"); } if (useImplicitRepresentation(eq)) { UnaryStatement<PointsToSetVariable> ueq = (UnaryStatement<PointsToSetVariable>) eq; return containsImplicitStatement(ueq); } else { return delegateStatements.contains(eq); } } /** @return true iff the graph already contains this equation */ private boolean containsImplicitStatement(UnaryStatement<PointsToSetVariable> eq) { if (!containsVariable(eq.getLHS())) { return false; } if (!containsVariable(eq.getRightHandSide())) { return false; } int lhs = eq.getLHS().getGraphNodeId(); int rhs = eq.getRightHandSide().getGraphNodeId(); UnaryOperator<?> op = eq.getOperator(); IBinaryNaturalRelation R = implicitUnaryMap.get(op); if (R != null) { return R.contains(lhs, rhs); } else { return false; } } @Override public boolean containsVariable(PointsToSetVariable v) { return delegateGraph.containsNode(v); } @Override public void addStatement(IFixedPointStatement<PointsToSetVariable> statement) throws IllegalArgumentException, UnimplementedError { if (statement == null) { throw new IllegalArgumentException("statement == null"); } if (statement instanceof UnaryStatement) { addStatement((UnaryStatement<PointsToSetVariable>) statement); } else if (statement instanceof GeneralStatement) { addStatement((GeneralStatement<PointsToSetVariable>) statement); } else { Assertions.UNREACHABLE("unexpected: " + statement.getClass()); } } /** * A graph of just the variables in the system. v1 -&gt; v2 iff there exists an assignment * equation e s.t. e uses v1 and e defs v2. */ public NumberedGraph<PointsToSetVariable> getAssignmentGraph() { return new FilteredConstraintGraphView() { @Override boolean isInteresting(AbstractStatement<?, ?> eq) { return eq instanceof AssignEquation; } }; } /** * A graph of just the variables in the system. v1 -&gt; v2 iff there exists an Assingnment or * Filter equation e s.t. e uses v1 and e defs v2. */ public Graph<PointsToSetVariable> getFilterAssignmentGraph() { return new FilteredConstraintGraphView() { @Override boolean isInteresting(AbstractStatement<?, ?> eq) { return eq instanceof AssignEquation || eq.getOperator() instanceof PropagationCallGraphBuilder.FilterOperator; } }; } /** * NOTE: do not use this method unless you really know what you are doing. Functionality is * fragile and may not work in the future. */ public Graph<PointsToSetVariable> getFlowGraphIncludingImplicitConstraints() { return new VariableGraphView(); } /** * A graph of just the variables in the system. v1 -&gt; v2 that are related by def-use with * "interesting" operators */ private abstract class FilteredConstraintGraphView extends AbstractNumberedGraph<PointsToSetVariable> { abstract boolean isInteresting(AbstractStatement<?, ?> eq); /** @see com.ibm.wala.util.graph.Graph#removeNodeAndEdges(java.lang.Object) */ @Override public void removeNodeAndEdges(PointsToSetVariable N) { Assertions.UNREACHABLE(); } /** @see com.ibm.wala.util.graph.NodeManager#iterator() */ @Override public Iterator<PointsToSetVariable> iterator() { return getVariables(); } /** @see com.ibm.wala.util.graph.NodeManager#getNumberOfNodes() */ @Override public int getNumberOfNodes() { return delegateGraph.getVarCount(); } /** @see com.ibm.wala.util.graph.NodeManager#addNode(java.lang.Object) */ @Override public void addNode(PointsToSetVariable n) { Assertions.UNREACHABLE(); } /** @see com.ibm.wala.util.graph.NodeManager#removeNode(java.lang.Object) */ @Override public void removeNode(PointsToSetVariable n) { Assertions.UNREACHABLE(); } /** @see com.ibm.wala.util.graph.NodeManager#containsNode(java.lang.Object) */ @Override public boolean containsNode(PointsToSetVariable N) { Assertions.UNREACHABLE(); return false; } /** @see com.ibm.wala.util.graph.EdgeManager#getPredNodes(java.lang.Object) */ @Override public Iterator<PointsToSetVariable> getPredNodes(PointsToSetVariable v) { final Iterator<AbstractStatement<PointsToSetVariable, ?>> eqs = getStatementsThatDef(v); return new Iterator<>() { PointsToSetVariable nextResult; { advance(); } @Override public boolean hasNext() { return nextResult != null; } @Override public PointsToSetVariable next() { PointsToSetVariable result = nextResult; advance(); return result; } private void advance() { nextResult = null; while (eqs.hasNext() && nextResult == null) { AbstractStatement<?, ?> eq = eqs.next(); if (isInteresting(eq)) { nextResult = (PointsToSetVariable) ((UnaryStatement<?>) eq).getRightHandSide(); } } } @Override public void remove() { Assertions.UNREACHABLE(); } }; } /** @see com.ibm.wala.util.graph.EdgeManager#getPredNodeCount(java.lang.Object) */ @Override public int getPredNodeCount(PointsToSetVariable v) { int result = 0; for (AbstractStatement<?, ?> eq : Iterator2Iterable.make(getStatementsThatDef(v))) { if (isInteresting(eq)) { result++; } } return result; } /** @see com.ibm.wala.util.graph.EdgeManager#getSuccNodes(java.lang.Object) */ @Override public Iterator<PointsToSetVariable> getSuccNodes(PointsToSetVariable v) { final Iterator<AbstractStatement> eqs = getStatementsThatUse(v); return new Iterator<>() { PointsToSetVariable nextResult; { advance(); } @Override public boolean hasNext() { return nextResult != null; } @Override public PointsToSetVariable next() { PointsToSetVariable result = nextResult; advance(); return result; } private void advance() { nextResult = null; while (eqs.hasNext() && nextResult == null) { AbstractStatement<?, ?> eq = eqs.next(); if (isInteresting(eq)) { nextResult = (PointsToSetVariable) ((UnaryStatement<?>) eq).getLHS(); } } } @Override public void remove() { // TODO Auto-generated method stub Assertions.UNREACHABLE(); } }; } /** @see com.ibm.wala.util.graph.EdgeManager#getSuccNodeCount(java.lang.Object) */ @Override public int getSuccNodeCount(PointsToSetVariable v) { int result = 0; for (AbstractStatement<?, ?> eq : Iterator2Iterable.make(getStatementsThatUse(v))) { if (isInteresting(eq)) { result++; } } return result; } /** @see com.ibm.wala.util.graph.EdgeManager#addEdge(java.lang.Object, java.lang.Object) */ @Override public void addEdge(PointsToSetVariable src, PointsToSetVariable dst) { Assertions.UNREACHABLE(); } /** @see com.ibm.wala.util.graph.EdgeManager#removeAllIncidentEdges(java.lang.Object) */ @Override public void removeAllIncidentEdges(PointsToSetVariable node) { Assertions.UNREACHABLE(); } /** @see com.ibm.wala.util.graph.AbstractGraph#getNodeManager() */ @Override @SuppressWarnings("unchecked") protected NumberedNodeManager getNodeManager() { return nodeManager; } /** @see com.ibm.wala.util.graph.AbstractGraph#getEdgeManager() */ @Override protected NumberedEdgeManager<PointsToSetVariable> getEdgeManager() { Assertions.UNREACHABLE(); return null; } } public String spaceReport() { // for (Iterator it = implicitUnaryMap.values().iterator(); it.hasNext(); ) // { // result.append(it.next() + "\n"); // } return "PropagationGraph\nImplicitEdges:" + countImplicitEdges() + '\n'; } private int countImplicitEdges() { return IteratorUtil.count(new GlobalImplicitIterator()); } }
32,138
30.789318
100
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/ipa/callgraph/propagation/PropagationSystem.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.ipa.callgraph.propagation; import com.ibm.wala.classLoader.ArrayClass; import com.ibm.wala.classLoader.IClass; import com.ibm.wala.core.util.ref.ReferenceCleanser; import com.ibm.wala.fixedpoint.impl.DefaultFixedPointSolver; import com.ibm.wala.fixedpoint.impl.Worklist; import com.ibm.wala.fixpoint.AbstractOperator; import com.ibm.wala.fixpoint.AbstractStatement; import com.ibm.wala.fixpoint.IFixedPointSystem; import com.ibm.wala.fixpoint.IVariable; import com.ibm.wala.fixpoint.UnaryOperator; import com.ibm.wala.fixpoint.UnaryStatement; import com.ibm.wala.ipa.callgraph.CallGraph; import com.ibm.wala.ipa.callgraph.propagation.PropagationCallGraphBuilder.FilterOperator; import com.ibm.wala.types.TypeReference; import com.ibm.wala.util.collections.HashMapFactory; import com.ibm.wala.util.collections.HashSetFactory; import com.ibm.wala.util.collections.Iterator2Collection; import com.ibm.wala.util.collections.MapUtil; import com.ibm.wala.util.debug.Assertions; import com.ibm.wala.util.debug.VerboseAction; import com.ibm.wala.util.graph.Graph; import com.ibm.wala.util.graph.NumberedGraph; import com.ibm.wala.util.heapTrace.HeapTracer; import com.ibm.wala.util.intset.IntIterator; import com.ibm.wala.util.intset.IntSet; import com.ibm.wala.util.intset.IntSetUtil; import com.ibm.wala.util.intset.MutableIntSet; import com.ibm.wala.util.intset.MutableMapping; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; /** System of constraints that define propagation for call graph construction */ public class PropagationSystem extends DefaultFixedPointSolver<PointsToSetVariable> { private static final boolean DEBUG = false; private static final boolean DEBUG_MEMORY = false; private static int DEBUG_MEM_COUNTER = 0; private static final int DEBUG_MEM_INTERVAL = 5; /** object that tracks points-to sets */ protected final PointsToMap pointsToMap = new PointsToMap(); /** Implementation of the underlying dataflow graph */ private final PropagationGraph flowGraph = new PropagationGraph(); /** bijection from InstanceKey &lt;=&gt; Integer */ protected final MutableMapping<InstanceKey> instanceKeys = MutableMapping.make(); /** * A mapping from IClass -&gt; MutableSharedBitVectorIntSet The range represents the instance keys * that correspond to a given class. This mapping is used to filter sets based on declared types; * e.g., in cast constraints */ private final Map<IClass, MutableIntSet> class2InstanceKey = HashMapFactory.make(); /** An abstraction of the pointer analysis result */ private PointerAnalysis<InstanceKey> pointerAnalysis; /** Meta-data regarding how pointers are modelled. */ private final PointerKeyFactory pointerKeyFactory; /** Meta-data regarding how instances are modelled. */ private final InstanceKeyFactory instanceKeyFactory; /** * When doing unification, we must also updated the fixed sets in unary side effects. * * <p>This maintains a map from PointsToSetVariable -&gt; Set&lt;UnarySideEffect&gt; */ private final Map<PointsToSetVariable, Set<UnarySideEffect>> fixedSetMap = HashMapFactory.make(); /** Governing call graph; */ protected final CallGraph cg; private int verboseInterval = DEFAULT_VERBOSE_INTERVAL; private int periodicMaintainInterval = DEFAULT_PERIODIC_MAINTENANCE_INTERVAL; @SuppressWarnings("unused") public PropagationSystem( CallGraph cg, PointerKeyFactory pointerKeyFactory, InstanceKeyFactory instanceKeyFactory) { if (cg == null) { throw new IllegalArgumentException("null cg"); } this.cg = cg; this.pointerKeyFactory = pointerKeyFactory; this.instanceKeyFactory = instanceKeyFactory; // when doing paranoid checking of points-to sets, code in PointsToSetVariable needs to know // about the instance key // mapping if (PointsToSetVariable.PARANOID || PointsToSetVariable.VERBOSE_PRINT) { PointsToSetVariable.instanceKeys = instanceKeys; } } /** @return an object which encapsulates the pointer analysis result */ public PointerAnalysis<InstanceKey> makePointerAnalysis(PropagationCallGraphBuilder builder) { return new PointerAnalysisImpl( builder, cg, pointsToMap, instanceKeys, pointerKeyFactory, instanceKeyFactory); } protected void registerFixedSet(PointsToSetVariable p, UnarySideEffect s) { Set<UnarySideEffect> set = MapUtil.findOrCreateSet(fixedSetMap, p); set.add(s); } protected void updateSideEffects(PointsToSetVariable p, PointsToSetVariable rep) { Set<UnarySideEffect> set = fixedSetMap.get(p); if (set != null) { for (UnarySideEffect s : set) { s.replaceFixedSet(rep); } Set<UnarySideEffect> s2 = MapUtil.findOrCreateSet(fixedSetMap, rep); s2.addAll(set); fixedSetMap.remove(p); } } /** * Keep this method private .. this returns the actual backing set for the class, which we do not * want to expose to clients. */ private MutableIntSet findOrCreateSparseSetForClass(IClass klass) { assert klass.getReference() != TypeReference.JavaLangObject; MutableIntSet result = class2InstanceKey.get(klass); if (result == null) { result = IntSetUtil.getDefaultIntSetFactory().make(); class2InstanceKey.put(klass, result); } return result; } /** * @return a set of integers representing the instance keys that correspond to a given class. This * method creates a new set, which the caller may bash at will. */ MutableIntSet cloneInstanceKeysForClass(IClass klass) { assert klass.getReference() != TypeReference.JavaLangObject; MutableIntSet set = class2InstanceKey.get(klass); if (set == null) { return IntSetUtil.getDefaultIntSetFactory().make(); } else { // return a copy. return IntSetUtil.getDefaultIntSetFactory().makeCopy(set); } } /** * @return a set of integers representing the instance keys that correspond to a given class, or * null if there are none. * @throws IllegalArgumentException if klass is null */ public IntSet getInstanceKeysForClass(IClass klass) { if (klass == null) { throw new IllegalArgumentException("klass is null"); } assert klass != klass.getClassHierarchy().getRootClass(); return class2InstanceKey.get(klass); } /** @return the instance key numbered with index i */ public InstanceKey getInstanceKey(int i) { return instanceKeys.getMappedObject(i); } public int getInstanceIndex(InstanceKey ik) { return instanceKeys.getMappedIndex(ik); } /** * TODO: optimize; this may be inefficient; * * @return an List of instance keys corresponding to the integers in a set */ List<InstanceKey> getInstances(IntSet set) { ArrayList<InstanceKey> result = new ArrayList<>(); for (IntIterator it = set.intIterator(); it.hasNext(); ) { int j = it.next(); result.add(getInstanceKey(j)); } return result; } @Override protected void initializeVariables() { // don't have to do anything; all variables initialized // by default to TOP (the empty set); } /** record that a particular points-to-set is represented implicitly. */ public void recordImplicitPointsToSet(PointerKey key) { if (key == null) { throw new IllegalArgumentException("null key"); } if (key instanceof LocalPointerKey) { LocalPointerKey lpk = (LocalPointerKey) key; if (lpk.isParameter()) { System.err.println("------------------ ERROR:"); System.err.println("LocalPointerKey: " + lpk); System.err.println( "Constant? " + lpk.getNode().getIR().getSymbolTable().isConstant(lpk.getValueNumber())); System.err.println(" -- IR:"); System.err.println(lpk.getNode().getIR()); Assertions.UNREACHABLE("How can parameter be implicit?"); } } pointsToMap.recordImplicit(key); } /** * If key is unified, returns the representative * * @return the dataflow variable that tracks the points-to set for key */ public PointsToSetVariable findOrCreatePointsToSet(PointerKey key) { if (key == null) { throw new IllegalArgumentException("null key"); } if (pointsToMap.isImplicit(key)) { System.err.println( "Did not expect to findOrCreatePointsToSet for implicitly represented PointerKey"); System.err.println(key); System.err.println(cg); cg.forEach(n -> System.err.println(n.getIR())); Assertions.UNREACHABLE(); } PointsToSetVariable result = pointsToMap.getPointsToSet(key); if (result == null) { result = new PointsToSetVariable(key); pointsToMap.put(key, result); } else { // check that the filter for this variable remains unique if (!pointsToMap.isUnified(key) && key instanceof FilteredPointerKey) { PointerKey pk = result.getPointerKey(); if (!(pk instanceof FilteredPointerKey)) { // add a filter for all future evaluations. // this is tricky, but the logic is OK .. any constraints that need // the filter will see it ... // CALLERS MUST BE EXTRA CAREFUL WHEN DEALING WITH UNIFICATION! result.setPointerKey(key); pk = key; } FilteredPointerKey fpk = (FilteredPointerKey) pk; assert fpk != null; assert key != null; if (fpk.getTypeFilter() == null) { Assertions.UNREACHABLE("fpk.getTypeFilter() is null"); } if (!fpk.getTypeFilter().equals(((FilteredPointerKey) key).getTypeFilter())) { Assertions.UNREACHABLE( "Cannot use filter " + ((FilteredPointerKey) key).getTypeFilter() + " for " + key + ": previously created different filter " + fpk.getTypeFilter()); } } } return result; } public int findOrCreateIndexForInstanceKey(InstanceKey key) { int result = instanceKeys.getMappedIndex(key); if (result == -1) { result = instanceKeys.add(key); } if (DEBUG) { System.err.println("getIndexForInstanceKey " + key + ' ' + result); } return result; } /** * NB: this is idempotent ... if the given constraint exists, it will not be added to the system; * however, this will be more expensive since it must check if the constraint pre-exits. * * @return true iff the system changes */ public boolean newConstraint( PointerKey lhs, UnaryOperator<PointsToSetVariable> op, PointerKey rhs) { if (lhs == null) { throw new IllegalArgumentException("null lhs"); } if (op == null) { throw new IllegalArgumentException("op null"); } if (rhs == null) { throw new IllegalArgumentException("rhs null"); } if (DEBUG) { System.err.println("Add constraint A: " + lhs + ' ' + op + ' ' + rhs); } PointsToSetVariable L = findOrCreatePointsToSet(lhs); PointsToSetVariable R = findOrCreatePointsToSet(rhs); if (op instanceof FilterOperator) { // we do not want to revert the lhs to pre-transitive form; // we instead want to check in the outer loop of the pre-transitive // solver if the value of L changes. pointsToMap.recordTransitiveRoot(L.getPointerKey()); if (!(L.getPointerKey() instanceof FilteredPointerKey)) { Assertions.UNREACHABLE( "expected filtered lhs " + L.getPointerKey() + ' ' + L.getPointerKey().getClass() + ' ' + lhs + ' ' + lhs.getClass()); } } return newStatement(L, op, R, true, true); } public boolean newConstraint( PointerKey lhs, AbstractOperator<PointsToSetVariable> op, PointerKey rhs) { if (lhs == null) { throw new IllegalArgumentException("lhs null"); } if (op == null) { throw new IllegalArgumentException("op null"); } if (rhs == null) { throw new IllegalArgumentException("rhs null"); } if (DEBUG) { System.err.println("Add constraint A: " + lhs + ' ' + op + ' ' + rhs); } assert !pointsToMap.isUnified(lhs); assert !pointsToMap.isUnified(rhs); PointsToSetVariable L = findOrCreatePointsToSet(lhs); PointsToSetVariable R = findOrCreatePointsToSet(rhs); return newStatement(L, op, new PointsToSetVariable[] {R}, true, true); } public boolean newConstraint( PointerKey lhs, AbstractOperator<PointsToSetVariable> op, PointerKey rhs1, PointerKey rhs2) { if (lhs == null) { throw new IllegalArgumentException("null lhs"); } if (op == null) { throw new IllegalArgumentException("null op"); } if (rhs1 == null) { throw new IllegalArgumentException("null rhs1"); } if (rhs2 == null) { throw new IllegalArgumentException("null rhs2"); } if (DEBUG) { System.err.println("Add constraint A: " + lhs + ' ' + op + ' ' + rhs1 + ", " + rhs2); } assert !pointsToMap.isUnified(lhs); assert !pointsToMap.isUnified(rhs1); assert !pointsToMap.isUnified(rhs2); PointsToSetVariable L = findOrCreatePointsToSet(lhs); PointsToSetVariable R1 = findOrCreatePointsToSet(rhs1); PointsToSetVariable R2 = findOrCreatePointsToSet(rhs2); return newStatement(L, op, R1, R2, true, true); } /** @return true iff the system changes */ public boolean newFieldWrite( PointerKey lhs, UnaryOperator<PointsToSetVariable> op, PointerKey rhs) { return newConstraint(lhs, op, rhs); } /** @return true iff the system changes */ public boolean newFieldRead( PointerKey lhs, UnaryOperator<PointsToSetVariable> op, PointerKey rhs) { return newConstraint(lhs, op, rhs); } /** @return true iff the system changes */ public boolean newConstraint(PointerKey lhs, InstanceKey value) { if (DEBUG) { System.err.println("Add constraint B: " + lhs + " U= " + value); } pointsToMap.recordTransitiveRoot(lhs); // we don't actually add a constraint. // instead, we immediately add the value to the points-to set. // This works since the solver is monotonic with TOP = {} PointsToSetVariable L = findOrCreatePointsToSet(lhs); int index = findOrCreateIndexForInstanceKey(value); if (!L.add(index)) { // a no-op return false; } else { // also register that we have an instanceKey for the klass assert value.getConcreteType() != null; if (!value.getConcreteType().getReference().equals(TypeReference.JavaLangObject)) { registerInstanceOfClass(value.getConcreteType(), index); } // we'd better update the worklist appropriately // if graphNodeId == -1, then there are no equations that use this // variable. if (L.getGraphNodeId() > -1) { changedVariable(L); } return true; } } /** Record that we have a new instanceKey for a given declared type. */ private void registerInstanceOfClass(IClass klass, int index) { if (DEBUG) { System.err.println("registerInstanceOfClass " + klass + ' ' + index); } assert !klass.getReference().equals(TypeReference.JavaLangObject); IClass T = klass; registerInstanceWithAllSuperclasses(index, T); registerInstanceWithAllInterfaces(klass, index); if (klass.isArrayClass()) { ArrayClass aClass = (ArrayClass) klass; int dim = aClass.getDimensionality(); registerMultiDimArraysForArrayOfObjectTypes(dim, index, aClass); IClass elementClass = aClass.getInnermostElementClass(); if (elementClass != null) { registerArrayInstanceWithAllSuperclassesOfElement(index, elementClass, dim); registerArrayInstanceWithAllInterfacesOfElement(index, elementClass, dim); } } } private int registerMultiDimArraysForArrayOfObjectTypes(int dim, int index, ArrayClass aClass) { for (int i = 1; i < dim; i++) { TypeReference jlo = makeArray(TypeReference.JavaLangObject, i); IClass jloClass = null; jloClass = aClass.getClassLoader().lookupClass(jlo.getName()); MutableIntSet set = findOrCreateSparseSetForClass(jloClass); set.add(index); } return dim; } private void registerArrayInstanceWithAllInterfacesOfElement( int index, IClass elementClass, int dim) { Collection<IClass> ifaces = elementClass.getAllImplementedInterfaces(); for (IClass I : ifaces) { TypeReference iArrayRef = makeArray(I.getReference(), dim); IClass iArrayClass = I.getClassLoader().lookupClass(iArrayRef.getName()); MutableIntSet set = findOrCreateSparseSetForClass(iArrayClass); set.add(index); if (DEBUG) { System.err.println("dense filter for interface " + iArrayClass + ' ' + set); } } } private static TypeReference makeArray(TypeReference element, int dim) { TypeReference iArrayRef = element; for (int i = 0; i < dim; i++) { iArrayRef = TypeReference.findOrCreateArrayOf(iArrayRef); } return iArrayRef; } private void registerArrayInstanceWithAllSuperclassesOfElement( int index, IClass elementClass, int dim) { IClass T; // register the array with each supertype of the element class T = elementClass.getSuperclass(); while (T != null) { TypeReference tArrayRef = makeArray(T.getReference(), dim); IClass tArrayClass = T.getClassLoader().lookupClass(tArrayRef.getName()); MutableIntSet set = findOrCreateSparseSetForClass(tArrayClass); set.add(index); if (DEBUG) { System.err.println("dense filter for class " + tArrayClass + ' ' + set); } T = T.getSuperclass(); } } private void registerInstanceWithAllInterfaces(IClass klass, int index) { Collection<IClass> ifaces = klass.getAllImplementedInterfaces(); for (IClass I : ifaces) { MutableIntSet set = findOrCreateSparseSetForClass(I); set.add(index); if (DEBUG) { System.err.println("dense filter for interface " + I + ' ' + set); } } } private void registerInstanceWithAllSuperclasses(int index, IClass T) { while (T != null && !T.getReference().equals(TypeReference.JavaLangObject)) { MutableIntSet set = findOrCreateSparseSetForClass(T); set.add(index); if (DEBUG) { System.err.println("dense filter for class " + T + ' ' + set); } T = T.getSuperclass(); } } public void newSideEffect(UnaryOperator<PointsToSetVariable> op, PointerKey arg0) { if (arg0 == null) { throw new IllegalArgumentException("null arg0"); } if (DEBUG) { System.err.println("add constraint D: " + op + ' ' + arg0); } assert !pointsToMap.isUnified(arg0); PointsToSetVariable v1 = findOrCreatePointsToSet(arg0); newStatement(null, op, v1, true, true); } public void newSideEffect(AbstractOperator<PointsToSetVariable> op, PointerKey[] arg0) { if (arg0 == null) { throw new IllegalArgumentException("null arg0"); } if (DEBUG) { System.err.println("add constraint D: " + op + ' ' + Arrays.toString(arg0)); } PointsToSetVariable[] vs = new PointsToSetVariable[arg0.length]; for (int i = 0; i < arg0.length; i++) { assert !pointsToMap.isUnified(arg0[i]); vs[i] = findOrCreatePointsToSet(arg0[i]); } newStatement(null, op, vs, true, true); } public void newSideEffect( AbstractOperator<PointsToSetVariable> op, PointerKey arg0, PointerKey arg1) { if (DEBUG) { System.err.println("add constraint D: " + op + ' ' + arg0); } assert !pointsToMap.isUnified(arg0); assert !pointsToMap.isUnified(arg1); PointsToSetVariable v1 = findOrCreatePointsToSet(arg0); PointsToSetVariable v2 = findOrCreatePointsToSet(arg1); newStatement(null, op, v1, v2, true, true); } @Override protected void initializeWorkList() { addAllStatementsToWorkList(); } /** @return an object that encapsulates the pointer analysis results */ public PointerAnalysis<InstanceKey> extractPointerAnalysis(PropagationCallGraphBuilder builder) { if (pointerAnalysis == null) { pointerAnalysis = makePointerAnalysis(builder); } return pointerAnalysis; } @Override public void performVerboseAction() { super.performVerboseAction(); if (DEBUG_MEMORY) { DEBUG_MEM_COUNTER++; if (DEBUG_MEM_COUNTER % DEBUG_MEM_INTERVAL == 0) { DEBUG_MEM_COUNTER = 0; ReferenceCleanser.clearSoftCaches(); System.err.println(flowGraph.spaceReport()); System.err.println("Analyze leaks.."); HeapTracer.traceHeap(Collections.singleton(this), true); System.err.println("done analyzing leaks"); } } if (getFixedPointSystem() instanceof VerboseAction) { ((VerboseAction) getFixedPointSystem()).performVerboseAction(); } if (!workList.isEmpty()) { AbstractStatement s = workList.takeStatement(); System.err.println(printRHSInstances(s)); workList.insertStatement(s); System.err.println("CGNodes: " + cg.getNumberOfNodes()); } } private String printRHSInstances(AbstractStatement s) { if (s instanceof UnaryStatement) { UnaryStatement<?> u = (UnaryStatement<?>) s; PointsToSetVariable rhs = (PointsToSetVariable) u.getRightHandSide(); IntSet value = rhs.getValue(); final int[] topFive = new int[5]; value.foreach( x -> { //noinspection SuspiciousSystemArraycopy System.arraycopy(topFive, 1, topFive, 0, 4); topFive[4] = x; }); StringBuilder result = new StringBuilder(); for (int i = 0; i < 5; i++) { int p = topFive[i]; if (p != 0) { InstanceKey ik = getInstanceKey(p); result.append(p).append(" ").append(ik).append('\n'); } } return result.toString(); } else { return s.getClass().toString(); } } @Override public IFixedPointSystem<PointsToSetVariable> getFixedPointSystem() { return flowGraph; } /** @see com.ibm.wala.ipa.callgraph.propagation.HeapModel#iteratePointerKeys() */ public Iterator<PointerKey> iteratePointerKeys() { return pointsToMap.iterateKeys(); } /** warning: this is _real_ slow; don't use it anywhere performance critical */ public int getNumberOfPointerKeys() { return pointsToMap.getNumberOfPointerKeys(); } /** Use with care. */ Worklist getWorklist() { return workList; } public Iterator<AbstractStatement> getStatementsThatUse(PointsToSetVariable v) { return flowGraph.getStatementsThatUse(v); } public Iterator<AbstractStatement<PointsToSetVariable, ?>> getStatementsThatDef( PointsToSetVariable v) { return flowGraph.getStatementsThatDef(v); } public NumberedGraph<PointsToSetVariable> getAssignmentGraph() { return flowGraph.getAssignmentGraph(); } public Graph<PointsToSetVariable> getFilterAsssignmentGraph() { return flowGraph.getFilterAssignmentGraph(); } /** * NOTE: do not use this method unless you really know what you are doing. Functionality is * fragile and may not work in the future. */ public Graph<PointsToSetVariable> getFlowGraphIncludingImplicitConstraints() { return flowGraph.getFlowGraphIncludingImplicitConstraints(); } /** */ public void revertToPreTransitive() { pointsToMap.revertToPreTransitive(); } public Iterator<PointerKey> getTransitiveRoots() { return pointsToMap.getTransitiveRoots(); } public boolean isTransitiveRoot(PointerKey key) { return pointsToMap.isTransitiveRoot(key); } @Override protected void periodicMaintenance() { super.periodicMaintenance(); ReferenceCleanser.clearSoftCaches(); } @Override public int getVerboseInterval() { return verboseInterval; } /** @param verboseInterval The verboseInterval to set. */ public void setVerboseInterval(int verboseInterval) { this.verboseInterval = verboseInterval; } @Override public int getPeriodicMaintainInterval() { return periodicMaintainInterval; } public void setPeriodicMaintainInterval(int periodicMaintainInteval) { this.periodicMaintainInterval = periodicMaintainInteval; } /** * Unify the points-to-sets for the variables identified by the set s * * @param s numbers of points-to-set variables * @throws IllegalArgumentException if s is null */ public void unify(IntSet s) { if (s == null) { throw new IllegalArgumentException("s is null"); } // cache the variables represented HashSet<PointsToSetVariable> cache = HashSetFactory.make(s.size()); for (IntIterator it = s.intIterator(); it.hasNext(); ) { int i = it.next(); cache.add(pointsToMap.getPointsToSet(i)); } // unify the variables pointsToMap.unify(s); int rep = pointsToMap.getRepresentative(s.intIterator().next()); // clean up the equations updateEquationsForUnification(cache, rep); // special logic to clean up side effects updateSideEffectsForUnification(cache, rep); } /** * Update side effect after unification * * @param s set of PointsToSetVariables that have been unified * @param rep number of the representative variable for the unified set. */ private void updateSideEffectsForUnification(HashSet<PointsToSetVariable> s, int rep) { PointsToSetVariable pRef = pointsToMap.getPointsToSet(rep); for (PointsToSetVariable p : s) { updateSideEffects(p, pRef); } } /** * Update equation def/uses after unification * * @param s set of PointsToSetVariables that have been unified * @param rep number of the representative variable for the unified set. */ @SuppressWarnings("unchecked") private void updateEquationsForUnification(HashSet<PointsToSetVariable> s, int rep) { PointsToSetVariable pRef = pointsToMap.getPointsToSet(rep); for (PointsToSetVariable p : s) { if (p != pRef) { // pRef is the representative for p. // be careful: cache the defs before mucking with the underlying system for (AbstractStatement as : Iterator2Collection.toSet(getStatementsThatDef(p))) { if (as instanceof AssignEquation) { AssignEquation assign = (AssignEquation) as; PointsToSetVariable rhs = assign.getRightHandSide(); int rhsRep = pointsToMap.getRepresentative(pointsToMap.getIndex(rhs.getPointerKey())); if (rhsRep == rep) { flowGraph.removeStatement(as); } else { replaceLHS(pRef, p, as); } } else { replaceLHS(pRef, p, as); } } // be careful: cache the defs before mucking with the underlying system for (AbstractStatement as : Iterator2Collection.toSet(getStatementsThatUse(p))) { if (as instanceof AssignEquation) { AssignEquation assign = (AssignEquation) as; PointsToSetVariable lhs = assign.getLHS(); int lhsRep = pointsToMap.getRepresentative(pointsToMap.getIndex(lhs.getPointerKey())); if (lhsRep == rep) { flowGraph.removeStatement(as); } else { replaceRHS(pRef, p, as); } } else { replaceRHS(pRef, p, as); } } if (flowGraph.getNumberOfStatementsThatDef(p) == 0 && flowGraph.getNumberOfStatementsThatUse(p) == 0) { flowGraph.removeVariable(p); } } } } /** * replace all occurrences of p on the rhs of a statement with pRef * * @param as a statement that uses p in it's right-hand side */ private void replaceRHS( PointsToSetVariable pRef, PointsToSetVariable p, AbstractStatement<PointsToSetVariable, AbstractOperator<PointsToSetVariable>> as) { if (as instanceof UnaryStatement) { assert ((UnaryStatement) as).getRightHandSide() == p; newStatement( as.getLHS(), (UnaryOperator<PointsToSetVariable>) as.getOperator(), pRef, false, false); } else { IVariable<?>[] rhs = as.getRHS(); PointsToSetVariable[] newRHS = new PointsToSetVariable[rhs.length]; for (int i = 0; i < rhs.length; i++) { if (rhs[i].equals(p)) { newRHS[i] = pRef; } else { newRHS[i] = (PointsToSetVariable) rhs[i]; } } newStatement(as.getLHS(), as.getOperator(), newRHS, false, false); } flowGraph.removeStatement(as); } /** * replace all occurences of p on the lhs of a statement with pRef * * @param as a statement that defs p */ private void replaceLHS( PointsToSetVariable pRef, PointsToSetVariable p, AbstractStatement<PointsToSetVariable, AbstractOperator<PointsToSetVariable>> as) { assert as.getLHS() == p; if (as instanceof UnaryStatement) { newStatement( pRef, (UnaryOperator<PointsToSetVariable>) as.getOperator(), (PointsToSetVariable) ((UnaryStatement) as).getRightHandSide(), false, false); } else { newStatement(pRef, as.getOperator(), as.getRHS(), false, false); } flowGraph.removeStatement(as); } public boolean isUnified(PointerKey result) { return pointsToMap.isUnified(result); } public boolean isImplicit(PointerKey result) { return pointsToMap.isImplicit(result); } public int getNumber(PointerKey p) { return pointsToMap.getIndex(p); } @Override protected PointsToSetVariable[] makeStmtRHS(int size) { return new PointsToSetVariable[size]; } }
30,301
33.356009
100
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/ipa/callgraph/propagation/ReceiverInstanceContext.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.ipa.callgraph.propagation; import com.ibm.wala.ipa.callgraph.Context; import com.ibm.wala.ipa.callgraph.ContextItem; import com.ibm.wala.ipa.callgraph.ContextKey; /** This is a context which is customized for the {@link InstanceKey} of the receiver. */ public class ReceiverInstanceContext implements Context { private final InstanceKey ik; /** @param I the instance key that represents the receiver */ public ReceiverInstanceContext(InstanceKey I) { if (I == null) { throw new IllegalArgumentException("null I"); } this.ik = I; } @Override public ContextItem get(ContextKey name) { if (name == ContextKey.RECEIVER) return ik; else if (name == ContextKey.PARAMETERS[0]) return new FilteredPointerKey.SingleInstanceFilter(ik); else { return null; } } @Override public String toString() { return "ReceiverInstanceContext<" + ik + '>'; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((ik == null) ? 0 : ik.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; final ReceiverInstanceContext other = (ReceiverInstanceContext) obj; if (ik == null) { if (other.ik != null) return false; } else if (!ik.equals(other.ik)) return false; return true; } public InstanceKey getReceiver() { return ik; } }
1,921
26.855072
89
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/ipa/callgraph/propagation/ReceiverTypeContextSelector.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.ipa.callgraph.propagation; import com.ibm.wala.analysis.reflection.JavaTypeContext; import com.ibm.wala.analysis.typeInference.PointType; import com.ibm.wala.classLoader.CallSiteReference; import com.ibm.wala.classLoader.IMethod; import com.ibm.wala.ipa.callgraph.CGNode; import com.ibm.wala.ipa.callgraph.Context; import com.ibm.wala.ipa.callgraph.ContextSelector; import com.ibm.wala.ipa.callgraph.impl.Everywhere; import com.ibm.wala.util.intset.EmptyIntSet; import com.ibm.wala.util.intset.IntSet; import com.ibm.wala.util.intset.IntSetUtil; /** This context selector selects a context based on the concrete type of the receiver. */ public class ReceiverTypeContextSelector implements ContextSelector { public ReceiverTypeContextSelector() {} @Override public Context getCalleeTarget( CGNode caller, CallSiteReference site, IMethod callee, InstanceKey[] receiver) { if (site.isStatic()) { return Everywhere.EVERYWHERE; } else { if (receiver == null) { throw new IllegalArgumentException("receiver is null"); } PointType P = new PointType(receiver[0].getConcreteType()); return new JavaTypeContext(P); } } private static final IntSet receiver = IntSetUtil.make(new int[] {0}); @Override public IntSet getRelevantParameters(CGNode caller, CallSiteReference site) { if (site.isStatic()) { return EmptyIntSet.instance; } else { return receiver; } } }
1,849
32.636364
90
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/ipa/callgraph/propagation/ReflectionHandler.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.ipa.callgraph.propagation; import com.ibm.wala.classLoader.IClass; import com.ibm.wala.classLoader.SyntheticMethod; import com.ibm.wala.ipa.callgraph.CGNode; import com.ibm.wala.ipa.callgraph.propagation.rta.RTAContextInterpreter; import com.ibm.wala.ipa.cha.IClassHierarchy; import com.ibm.wala.ipa.slicer.NormalReturnCallee; import com.ibm.wala.ipa.slicer.NormalStatement; 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.Statement; import com.ibm.wala.ipa.slicer.Statement.Kind; import com.ibm.wala.ssa.SSACheckCastInstruction; import com.ibm.wala.types.TypeReference; import com.ibm.wala.util.CancelException; import com.ibm.wala.util.MonitorUtil.IProgressMonitor; import com.ibm.wala.util.collections.FilterIterator; import com.ibm.wala.util.collections.HashSetFactory; import com.ibm.wala.util.collections.Iterator2Collection; import java.util.Collection; import java.util.HashSet; import java.util.Set; import java.util.function.Predicate; /** * A helper class which can modify a {@link PropagationCallGraphBuilder} to deal with reflective * factory methods. */ public class ReflectionHandler { private static final boolean VERBOSE = false; private final PropagationCallGraphBuilder builder; public ReflectionHandler(PropagationCallGraphBuilder builder) { this.builder = builder; } /** * update the pointer analysis solver based on flow of reflective factory results to checkcasts * * @return true if anything has changed */ protected boolean updateForReflection(IProgressMonitor monitor) throws IllegalArgumentException, CancelException { Collection<Statement> returnStatements = computeFactoryReturnStatements(); Set<CGNode> changedNodes = HashSetFactory.make(); for (Statement st : returnStatements) { if (VERBOSE) { System.err.println("Slice " + st); } Collection<Statement> slice = Slicer.computeForwardSlice( st, builder.callGraph, null, DataDependenceOptions.REFLECTION, ControlDependenceOptions.NONE); if (VERBOSE) { for (Statement x : slice) { System.err.println(" " + x); } } Predicate<Statement> f = s -> { if (s.getKind() == Kind.NORMAL) { return ((NormalStatement) s).getInstruction() instanceof SSACheckCastInstruction; } else { return false; } }; Collection<Statement> casts = Iterator2Collection.toSet(new FilterIterator<>(slice.iterator(), f)); changedNodes.addAll( modifyFactoryInterpreter( st, casts, builder.getContextInterpreter(), builder.getClassHierarchy())); } for (CGNode cgNode : changedNodes) { builder.addConstraintsFromChangedNode(cgNode, monitor); } return changedNodes.size() > 0; } private Collection<Statement> computeFactoryReturnStatements() { // todo: clean up logic with inheritance, delegation. HashSet<Statement> result = HashSetFactory.make(); for (CGNode n : builder.getCallGraph()) { if (n.getMethod() instanceof SyntheticMethod) { SyntheticMethod m = (SyntheticMethod) n.getMethod(); if (m.isFactoryMethod()) { result.add(new NormalReturnCallee(n)); } } } return result; } /** * modify the contextInterpreter to account for new interpretations of factory methods. * * @return set of nodes whose interpretation has changed. */ private static Set<CGNode> modifyFactoryInterpreter( Statement returnStatement, Collection<Statement> casts, RTAContextInterpreter contextInterpreter, IClassHierarchy cha) { HashSet<CGNode> result = HashSetFactory.make(); for (Statement st : casts) { SSACheckCastInstruction c = (SSACheckCastInstruction) ((NormalStatement) st).getInstruction(); for (TypeReference type : c.getDeclaredResultTypes()) { IClass klass = cha.lookupClass(type); if (klass != null) { if (contextInterpreter.recordFactoryType(returnStatement.getNode(), klass)) { result.add(returnStatement.getNode()); } } } } return result; } }
4,789
33.963504
100
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/ipa/callgraph/propagation/ReturnValueKey.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.ipa.callgraph.propagation; import com.ibm.wala.ipa.callgraph.CGNode; /** A key which represents the return value for a node. */ public class ReturnValueKey extends NodeKey { public ReturnValueKey(CGNode node) { super(node); } @Override public String toString() { return "[Ret-V:" + getNode() + ']'; } @Override public boolean equals(Object obj) { return (obj instanceof ReturnValueKey) && super.internalEquals(obj); } @Override public int hashCode() { return 1283 * super.internalHashCode(); } }
935
25
72
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/ipa/callgraph/propagation/ReturnValueKeyWithFilter.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.ipa.callgraph.propagation; import com.ibm.wala.ipa.callgraph.CGNode; /** * a helper class which can modify a PropagationCallGraphBuilder to deal with reflective factory * methods. */ public class ReturnValueKeyWithFilter extends ReturnValueKey implements FilteredPointerKey { private final TypeFilter typeFilter; public ReturnValueKeyWithFilter(CGNode node, TypeFilter typeFilter) { super(node); if (typeFilter == null) { throw new IllegalArgumentException("null typeFilter"); } this.typeFilter = typeFilter; } @Override public TypeFilter getTypeFilter() { return typeFilter; } }
1,022
27.416667
96
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/ipa/callgraph/propagation/SSAContextInterpreter.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.ipa.callgraph.propagation; import com.ibm.wala.cfg.ControlFlowGraph; import com.ibm.wala.ipa.callgraph.CGNode; import com.ibm.wala.ipa.callgraph.propagation.rta.RTAContextInterpreter; import com.ibm.wala.ssa.DefUse; import com.ibm.wala.ssa.IR; import com.ibm.wala.ssa.IRView; import com.ibm.wala.ssa.ISSABasicBlock; import com.ibm.wala.ssa.SSAInstruction; /** An object that provides an interface to local method information needed for CFA. */ public interface SSAContextInterpreter extends RTAContextInterpreter { /** @return the IR that models the method context, or null if it's an unmodelled native method */ IR getIR(CGNode node); IRView getIRView(CGNode node); /** * @return DefUse for the IR that models the method context, or null if it's an unmodelled native * method */ DefUse getDU(CGNode node); /** @return the number of the statements in the IR, or -1 if it's an unmodelled native method. */ int getNumberOfStatements(CGNode node); ControlFlowGraph<SSAInstruction, ISSABasicBlock> getCFG(CGNode n); }
1,446
34.292683
99
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/ipa/callgraph/propagation/SSAPropagationCallGraphBuilder.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.ipa.callgraph.propagation; import com.ibm.wala.analysis.reflection.CloneInterpreter; import com.ibm.wala.cfg.ControlFlowGraph; import com.ibm.wala.cfg.IBasicBlock; import com.ibm.wala.classLoader.ArrayClass; import com.ibm.wala.classLoader.CallSiteReference; import com.ibm.wala.classLoader.IClass; import com.ibm.wala.classLoader.IField; import com.ibm.wala.classLoader.IMethod; import com.ibm.wala.classLoader.NewSiteReference; import com.ibm.wala.classLoader.ProgramCounter; import com.ibm.wala.core.util.ref.ReferenceCleanser; import com.ibm.wala.core.util.warnings.Warning; import com.ibm.wala.core.util.warnings.Warnings; import com.ibm.wala.fixpoint.AbstractOperator; import com.ibm.wala.fixpoint.IVariable; import com.ibm.wala.ipa.callgraph.AnalysisOptions; import com.ibm.wala.ipa.callgraph.CGNode; import com.ibm.wala.ipa.callgraph.ContextKey; 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.AbstractRootMethod; import com.ibm.wala.ipa.callgraph.impl.DefaultEntrypoint; import com.ibm.wala.ipa.callgraph.impl.ExplicitCallGraph; import com.ibm.wala.ipa.cha.IClassHierarchy; import com.ibm.wala.shrike.shrikeBT.ConditionalBranchInstruction; import com.ibm.wala.shrike.shrikeBT.IInvokeInstruction; import com.ibm.wala.ssa.DefUse; import com.ibm.wala.ssa.IRView; import com.ibm.wala.ssa.ISSABasicBlock; import com.ibm.wala.ssa.SSAAbstractInvokeInstruction; import com.ibm.wala.ssa.SSAAbstractThrowInstruction; import com.ibm.wala.ssa.SSAArrayLoadInstruction; import com.ibm.wala.ssa.SSAArrayStoreInstruction; import com.ibm.wala.ssa.SSACFG; import com.ibm.wala.ssa.SSACFG.BasicBlock; import com.ibm.wala.ssa.SSACFG.ExceptionHandlerBasicBlock; import com.ibm.wala.ssa.SSACheckCastInstruction; import com.ibm.wala.ssa.SSAConditionalBranchInstruction; import com.ibm.wala.ssa.SSAGetCaughtExceptionInstruction; import com.ibm.wala.ssa.SSAGetInstruction; import com.ibm.wala.ssa.SSAInstanceofInstruction; import com.ibm.wala.ssa.SSAInstruction; import com.ibm.wala.ssa.SSAInvokeInstruction; import com.ibm.wala.ssa.SSALoadMetadataInstruction; import com.ibm.wala.ssa.SSANewInstruction; import com.ibm.wala.ssa.SSAPhiInstruction; import com.ibm.wala.ssa.SSAPiInstruction; import com.ibm.wala.ssa.SSAPutInstruction; import com.ibm.wala.ssa.SSAReturnInstruction; import com.ibm.wala.ssa.SSAThrowInstruction; import com.ibm.wala.ssa.SymbolTable; 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.util.CancelException; import com.ibm.wala.util.MonitorUtil; import com.ibm.wala.util.MonitorUtil.IProgressMonitor; import com.ibm.wala.util.collections.HashSetFactory; import com.ibm.wala.util.collections.Iterator2Iterable; import com.ibm.wala.util.debug.Assertions; import com.ibm.wala.util.debug.UnimplementedError; import com.ibm.wala.util.intset.IntIterator; import com.ibm.wala.util.intset.IntSet; import com.ibm.wala.util.intset.IntSetAction; import com.ibm.wala.util.intset.IntSetUtil; import com.ibm.wala.util.intset.MutableIntSet; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Set; import java.util.function.Consumer; /** * This abstract base class provides the general algorithm for a call graph builder that relies on * propagation through an iterative dataflow solver, and constraints generated by statements in SSA * form. * * <p>TODO: This implementation currently keeps all points to sets live ... even those for local * variables that do not span interprocedural boundaries. This may be too space-inefficient .. we * can consider recomputing local sets on demand. */ public abstract class SSAPropagationCallGraphBuilder extends PropagationCallGraphBuilder implements HeapModel { private static final boolean DEBUG = false; private static final boolean DEBUG_MULTINEWARRAY = DEBUG | false; /** Should we periodically clear out soft reference caches in an attempt to help the GC? */ public static final boolean PERIODIC_WIPE_SOFT_CACHES = true; /** Interval which defines the period to clear soft reference caches */ public static final int WIPE_SOFT_CACHE_INTERVAL = 2500; /** Counter for wiping soft caches */ private static int wipeCount = 0; // /** use type inference to avoid unnecessary filter constraints? */ // private final static boolean OPTIMIZE_WITH_TYPE_INFERENCE = true; /** * An optimization: if we can locally determine the final solution for a points-to set, then don't * actually create the points-to set, but instead short circuit by propagating the final solution * to all such uses. * * <p>String constants are ALWAYS considered invariant, regardless of the value of this flag. * * <p>However, if this flag is set, then the solver is more aggressive identifying invariants. * * <p>Doesn't play well with pre-transitive solver; turning off for now. */ private static final boolean SHORT_CIRCUIT_INVARIANT_SETS = true; /** * An optimization: if we can locally determine that a particular pointer p has exactly one use, * then we don't actually create the points-to-set for p, but instead short-circuit by propagating * the final solution to the unique use. * * <p>Doesn't play well with pre-transitive solver; turning off for now. */ protected static final boolean SHORT_CIRCUIT_SINGLE_USES = false; /** Should we change calls to clone() to assignments? */ private final boolean clone2Assign = false; /** Cache for efficiency */ private static final Selector cloneSelector = CloneInterpreter.CLONE.getSelector(); /** set of class whose clinits have already been processed */ private final Set<IClass> clinitVisited = HashSetFactory.make(); private final Set<IClass> finalizeVisited = HashSetFactory.make(); public IProgressMonitor monitor; protected SSAPropagationCallGraphBuilder( IMethod abstractRootMethod, AnalysisOptions options, IAnalysisCacheView cache, PointerKeyFactory pointerKeyFactory) { super(abstractRootMethod, options, cache, pointerKeyFactory); // this.usePreTransitiveSolver = options.usePreTransitiveSolver(); } public SSAContextInterpreter getCFAContextInterpreter() { return (SSAContextInterpreter) getContextInterpreter(); } /** * @return the instance key that represents the exception of type _type_ thrown by a particular * PEI. * @throws IllegalArgumentException if ikFactory is null */ public static InstanceKey getInstanceKeyForPEI( CGNode node, ProgramCounter x, TypeReference type, InstanceKeyFactory ikFactory) { if (ikFactory == null) { throw new IllegalArgumentException("ikFactory is null"); } return ikFactory.getInstanceKeyForPEI(node, x, type); } /** * Visit all instructions in a node, and add dataflow constraints induced by each statement in the * SSA form. */ @Override protected boolean addConstraintsFromNode(CGNode node, IProgressMonitor monitor) throws CancelException { this.monitor = monitor; if (haveAlreadyVisited(node)) { return false; } else { markAlreadyVisited(node); } return unconditionallyAddConstraintsFromNode(node, monitor); } @Override protected boolean unconditionallyAddConstraintsFromNode(CGNode node, IProgressMonitor monitor) throws CancelException { this.monitor = monitor; if (PERIODIC_WIPE_SOFT_CACHES) { wipeCount++; if (wipeCount >= WIPE_SOFT_CACHE_INTERVAL) { wipeCount = 0; ReferenceCleanser.clearSoftCaches(); } } if (DEBUG) { System.err.println("\n\nAdd constraints from node " + node); } IRView ir = getCFAContextInterpreter().getIRView(node); if (DEBUG) { if (ir == null) { System.err.println("\n No statements\n"); } else { try { System.err.println(ir); } catch (Error e) { e.printStackTrace(); } } } if (ir == null) { return false; } addNodeInstructionConstraints(node, monitor); addNodeValueConstraints(node, monitor); DefUse du = getCFAContextInterpreter().getDU(node); addNodePassthruExceptionConstraints(node, ir, du); // conservatively assume something changed return true; } /** @return a visitor to examine instructions in the ir */ protected ConstraintVisitor makeVisitor(CGNode node) { return new ConstraintVisitor(this, node); } /** Add pointer flow constraints based on instructions in a given node */ protected void addNodeInstructionConstraints(CGNode node, IProgressMonitor monitor) throws CancelException { this.monitor = monitor; ConstraintVisitor v = makeVisitor(node); IRView ir = v.ir; for (ISSABasicBlock sbb : Iterator2Iterable.make(ir.getBlocks())) { BasicBlock b = (BasicBlock) sbb; addBlockInstructionConstraints(node, ir, b, v, monitor); if (wasChanged(node)) { return; } } } /** Hook for subclasses to add pointer flow constraints based on values in a given node */ @SuppressWarnings("unused") protected void addNodeValueConstraints(CGNode node, IProgressMonitor monitor) throws CancelException {} /** Add constraints for a particular basic block. */ protected void addBlockInstructionConstraints( CGNode node, IRView ir, BasicBlock b, ConstraintVisitor v, IProgressMonitor monitor) throws CancelException { this.monitor = monitor; v.setBasicBlock(b); // visit each instruction in the basic block. for (SSAInstruction s : b) { MonitorUtil.throwExceptionIfCanceled(monitor); if (s != null) { s.visit(v); if (wasChanged(node)) { return; } } } addPhiConstraints(node, ir.getControlFlowGraph(), b, v); } private void addPhiConstraints( CGNode node, ControlFlowGraph<SSAInstruction, ISSABasicBlock> controlFlowGraph, BasicBlock b, ConstraintVisitor v) { // visit each phi instruction in each successor block for (ISSABasicBlock isb : Iterator2Iterable.make(controlFlowGraph.getSuccNodes(b))) { BasicBlock sb = (BasicBlock) isb; if (!sb.hasPhi()) { continue; } int n = 0; for (IBasicBlock<?> back : Iterator2Iterable.make(controlFlowGraph.getPredNodes(sb))) { if (back == b) { break; } ++n; } assert n < controlFlowGraph.getPredNodeCount(sb); for (SSAInstruction inst : Iterator2Iterable.make(sb.iteratePhis())) { SSAPhiInstruction phi = (SSAPhiInstruction) inst; if (phi == null) { continue; } PointerKey def = getPointerKeyForLocal(node, phi.getDef()); if (hasNoInterestingUses(node, phi.getDef(), v.du)) { system.recordImplicitPointsToSet(def); } else { // the following test restricts the constraints to reachable // paths, according to verification constraints if (phi.getUse(n) > 0) { PointerKey use = getPointerKeyForLocal(node, phi.getUse(n)); if (contentsAreInvariant(v.symbolTable, v.du, phi.getUse(n))) { system.recordImplicitPointsToSet(use); InstanceKey[] ik = getInvariantContents(v.symbolTable, v.du, node, phi.getUse(n), this); for (InstanceKey element : ik) { system.newConstraint(def, element); } } else { system.newConstraint(def, assignOperator, use); } } } } } } /** * Add constraints to represent the flow of exceptions to the exceptional return value for this * node */ protected void addNodePassthruExceptionConstraints(CGNode node, IRView ir, DefUse du) { // add constraints relating to thrown exceptions that reach the exit block. List<ProgramCounter> peis = getIncomingPEIs(ir, ir.getExitBlock()); PointerKey exception = getPointerKeyForExceptionalReturnValue(node); TypeReference throwableType = node.getMethod().getDeclaringClass().getClassLoader().getLanguage().getThrowableType(); IClass c = node.getClassHierarchy().lookupClass(throwableType); addExceptionDefConstraints(ir, du, node, peis, exception, Collections.singleton(c)); } /** * Generate constraints which assign exception values into an exception pointer * * @param node governing node * @param peis list of PEI instructions * @param exceptionVar PointerKey representing a pointer to an exception value * @param catchClasses the types "caught" by the exceptionVar */ @SuppressWarnings("unused") private void addExceptionDefConstraints( IRView ir, DefUse du, CGNode node, List<ProgramCounter> peis, PointerKey exceptionVar, Set<IClass> catchClasses) { if (DEBUG) { System.err.println("Add exception def constraints for node " + node); } for (ProgramCounter peiLoc : peis) { if (DEBUG) { System.err.println("peiLoc: " + peiLoc); } SSAInstruction pei = ir.getPEI(peiLoc); if (DEBUG) { System.err.println("Add exceptions from pei " + pei); } if (pei instanceof SSAAbstractInvokeInstruction) { SSAAbstractInvokeInstruction s = (SSAAbstractInvokeInstruction) pei; PointerKey e = getPointerKeyForLocal(node, s.getException()); if (!SHORT_CIRCUIT_SINGLE_USES || !hasUniqueCatchBlock(s, ir)) { addAssignmentsForCatchPointerKey(exceptionVar, catchClasses, e); } // else { // System.err.println("SKIPPING ASSIGNMENTS TO " + exceptionVar + " FROM " + // e); // } } else if (pei instanceof SSAAbstractThrowInstruction) { SSAAbstractThrowInstruction s = (SSAAbstractThrowInstruction) pei; PointerKey e = getPointerKeyForLocal(node, s.getException()); if (contentsAreInvariant(ir.getSymbolTable(), du, s.getException())) { InstanceKey[] ik = getInvariantContents(ir.getSymbolTable(), du, node, s.getException(), this); for (InstanceKey element : ik) { system.findOrCreateIndexForInstanceKey(element); assignInstanceToCatch(exceptionVar, catchClasses, element); } } else { addAssignmentsForCatchPointerKey(exceptionVar, catchClasses, e); } } // Account for those exceptions for which we do not actually have a // points-to set for // the pei, but just instance keys Collection<TypeReference> types = pei.getExceptionTypes(); if (types != null) { for (TypeReference type : types) { if (type != null) { InstanceKey ik = getInstanceKeyForPEI(node, peiLoc, type, instanceKeyFactory); if (ik == null) { continue; } assert ik instanceof ConcreteTypeKey : "uh oh: need to implement getCaughtException constraints for instance " + ik; ConcreteTypeKey ck = (ConcreteTypeKey) ik; IClass klass = ck.getType(); if (PropagationCallGraphBuilder.catches(catchClasses, klass, cha)) { system.newConstraint( exceptionVar, getInstanceKeyForPEI(node, peiLoc, type, instanceKeyFactory)); } } } } } } /** * @return true iff there's a unique catch block which catches all exceptions thrown by a certain * call site. */ protected static boolean hasUniqueCatchBlock(SSAAbstractInvokeInstruction call, IRView ir) { ISSABasicBlock[] bb = ir.getBasicBlocksForCall(call.getCallSite()); if (bb.length == 1) { Iterator<ISSABasicBlock> it = ir.getControlFlowGraph().getExceptionalSuccessors(bb[0]).iterator(); // check that there's exactly one element in the iterator if (it.hasNext()) { ISSABasicBlock sb = it.next(); return (!it.hasNext() && (sb.isExitBlock() || ((sb instanceof ExceptionHandlerBasicBlock) && ((ExceptionHandlerBasicBlock) sb).getCatchInstruction() != null))); } } return false; } /** * precondition: hasUniqueCatchBlock(call,node,cg) * * @return the unique pointer key which catches the exceptions thrown by a call * @throws IllegalArgumentException if ir == null * @throws IllegalArgumentException if call == null */ public PointerKey getUniqueCatchKey(SSAAbstractInvokeInstruction call, IRView ir, CGNode node) throws IllegalArgumentException, IllegalArgumentException { if (call == null) { throw new IllegalArgumentException("call == null"); } if (ir == null) { throw new IllegalArgumentException("ir == null"); } ISSABasicBlock[] bb = ir.getBasicBlocksForCall(call.getCallSite()); assert bb.length == 1; SSACFG.BasicBlock cb = (BasicBlock) ir.getControlFlowGraph().getExceptionalSuccessors(bb[0]).iterator().next(); if (cb.isExitBlock()) { return getPointerKeyForExceptionalReturnValue(node); } else { SSACFG.ExceptionHandlerBasicBlock ehbb = (ExceptionHandlerBasicBlock) cb; SSAGetCaughtExceptionInstruction ci = ehbb.getCatchInstruction(); return getPointerKeyForLocal(node, ci.getDef()); } } /** * @return a List of Instructions that may transfer control to bb via an exceptional edge * @throws IllegalArgumentException if ir is null */ public static List<ProgramCounter> getIncomingPEIs(IRView ir, ISSABasicBlock bb) { if (ir == null) { throw new IllegalArgumentException("ir is null"); } if (DEBUG) { System.err.println("getIncomingPEIs " + bb); } ControlFlowGraph<SSAInstruction, ISSABasicBlock> g = ir.getControlFlowGraph(); List<ProgramCounter> result = new ArrayList<>(g.getPredNodeCount(bb)); for (ISSABasicBlock sbb : Iterator2Iterable.make(g.getPredNodes(bb))) { BasicBlock pred = (BasicBlock) sbb; if (DEBUG) { System.err.println("pred: " + pred); } if (pred.isEntryBlock()) continue; int index = pred.getLastInstructionIndex(); SSAInstruction pei = ir.getInstructions()[index]; // Note: pei might be null if pred is unreachable. // TODO: consider pruning CFG for unreachable blocks. if (pei != null && pei.isPEI()) { if (DEBUG) { System.err.println( "PEI: " + pei + " index " + index + " PC " + g.getProgramCounter(index)); } result.add(new ProgramCounter(g.getProgramCounter(index))); } } return result; } private class CrossProductRec { private final InstanceKey[][] invariants; private final Consumer<InstanceKey[]> f; private final SSAAbstractInvokeInstruction call; private final CGNode caller; private final int[] params; private final CallSiteReference site; private final InstanceKey[] keys; private CrossProductRec( InstanceKey[][] invariants, SSAAbstractInvokeInstruction call, CGNode caller, Consumer<InstanceKey[]> f) { this.invariants = invariants; this.f = f; this.call = call; this.caller = caller; this.site = call.getCallSite(); MutableIntSet indices = IntSetUtil.makeMutableCopy(getRelevantParameters(caller, site)); getRelevantParameters(caller, site) .foreach( (i) -> { if (i >= call.getNumberOfUses()) { indices.remove(i); } }); this.params = IntSetUtil.toArray(indices); this.keys = new InstanceKey[params.length]; } protected void rec(final int pi, final int rhsi) { if (pi == params.length) { f.accept(keys); } else { final int p = params[pi]; InstanceKey[] ik = invariants != null ? invariants[p] : null; if (ik != null) { for (InstanceKey element : ik) { system.findOrCreateIndexForInstanceKey(element); keys[pi] = element; rec(pi + 1, rhsi); } } else { IntSet s = getParamObjects(pi, rhsi); if (s != null && !s.isEmpty()) { s.foreach( x -> { keys[pi] = system.getInstanceKey(x); rec(pi + 1, rhsi + 1); }); } /*else { if (!site.isDispatch() || p != 0) { keys[pi] = null; rec(pi + 1, rhsi + 1); } } */ } } } protected IntSet getParamObjects(int paramIndex, @SuppressWarnings("unused") int rhsi) { int paramVn = call.getUse(paramIndex); PointerKey var = getPointerKeyForLocal(caller, paramVn); IntSet s = system.findOrCreatePointsToSet(var).getValue(); return s; } } /** A visitor that generates constraints based on statements in SSA form. */ protected static class ConstraintVisitor extends SSAInstruction.Visitor { /** * The governing call graph builder. This field is used instead of an inner class in order to * allow more flexible reuse of this visitor in subclasses */ protected final SSAPropagationCallGraphBuilder builder; /** The node whose statements we are currently traversing */ protected final CGNode node; /** The governing call graph. */ private final ExplicitCallGraph callGraph; /** The governing IR */ protected final IRView ir; /** The governing propagation system, into which constraints are added */ protected final PropagationSystem system; /** The basic block currently being processed */ protected ISSABasicBlock basicBlock; /** Governing symbol table */ protected final SymbolTable symbolTable; /** Def-use information */ protected final DefUse du; public ConstraintVisitor(SSAPropagationCallGraphBuilder builder, CGNode node) { this.builder = builder; this.node = node; this.callGraph = builder.getCallGraph(); this.system = builder.getPropagationSystem(); SSAContextInterpreter interp = builder.getCFAContextInterpreter(); this.ir = interp.getIRView(node); this.symbolTable = this.ir.getSymbolTable(); this.du = interp.getDU(node); assert symbolTable != null; } protected SSAPropagationCallGraphBuilder getBuilder() { return builder; } protected AnalysisOptions getOptions() { return builder.options; } protected IAnalysisCacheView getAnalysisCache() { return builder.getAnalysisCache(); } public PointerKey getPointerKeyForLocal(int valueNumber) { return getBuilder().getPointerKeyForLocal(node, valueNumber); } public FilteredPointerKey getFilteredPointerKeyForLocal( int valueNumber, FilteredPointerKey.TypeFilter filter) { return getBuilder().getFilteredPointerKeyForLocal(node, valueNumber, filter); } public PointerKey getPointerKeyForReturnValue() { return getBuilder().getPointerKeyForReturnValue(node); } public PointerKey getPointerKeyForExceptionalReturnValue() { return getBuilder().getPointerKeyForExceptionalReturnValue(node); } public PointerKey getPointerKeyForStaticField(IField f) { return getBuilder().getPointerKeyForStaticField(f); } public PointerKey getPointerKeyForInstanceField(InstanceKey I, IField f) { return getBuilder().getPointerKeyForInstanceField(I, f); } public PointerKey getPointerKeyForArrayContents(InstanceKey I) { return getBuilder().getPointerKeyForArrayContents(I); } public InstanceKey getInstanceKeyForAllocation(NewSiteReference allocation) { return getBuilder().getInstanceKeyForAllocation(node, allocation); } public InstanceKey getInstanceKeyForMultiNewArray(NewSiteReference allocation, int dim) { return getBuilder().getInstanceKeyForMultiNewArray(node, allocation, dim); } public <T> InstanceKey getInstanceKeyForConstant(T S) { TypeReference type = node.getMethod().getDeclaringClass().getClassLoader().getLanguage().getConstantType(S); return getBuilder().getInstanceKeyForConstant(type, S); } public InstanceKey getInstanceKeyForPEI(ProgramCounter instr, TypeReference type) { return getBuilder().getInstanceKeyForPEI(node, instr, type); } public InstanceKey getInstanceKeyForClassObject(Object obj, TypeReference type) { return getBuilder().getInstanceKeyForMetadataObject(obj, type); } public CGNode getTargetForCall( CGNode caller, CallSiteReference site, IClass recv, InstanceKey iKey[]) { return getBuilder().getTargetForCall(caller, site, recv, iKey); } protected boolean contentsAreInvariant(SymbolTable symbolTable, DefUse du, int valueNumber) { return getBuilder().contentsAreInvariant(symbolTable, du, valueNumber); } protected boolean contentsAreInvariant(SymbolTable symbolTable, DefUse du, int valueNumber[]) { return getBuilder().contentsAreInvariant(symbolTable, du, valueNumber); } protected InstanceKey[] getInvariantContents(int valueNumber) { return getInvariantContents(ir.getSymbolTable(), du, node, valueNumber); } protected InstanceKey[] getInvariantContents( SymbolTable symbolTable, DefUse du, CGNode node, int valueNumber) { return getBuilder().getInvariantContents(symbolTable, du, node, valueNumber, getBuilder()); } protected IClassHierarchy getClassHierarchy() { return getBuilder().getClassHierarchy(); } protected boolean hasNoInterestingUses(int vn) { return getBuilder().hasNoInterestingUses(node, vn, du); } protected boolean isRootType(IClass klass) { return SSAPropagationCallGraphBuilder.isRootType(klass); } @Override public void visitArrayLoad(SSAArrayLoadInstruction instruction) { // skip arrays of primitive type if (instruction.typeIsPrimitive()) { return; } doVisitArrayLoad(instruction.getDef(), instruction.getArrayRef()); } protected void doVisitArrayLoad(int def, int arrayRef) { PointerKey result = getPointerKeyForLocal(def); PointerKey arrayRefPtrKey = getPointerKeyForLocal(arrayRef); if (hasNoInterestingUses(def)) { system.recordImplicitPointsToSet(result); } else { if (contentsAreInvariant(symbolTable, du, arrayRef)) { system.recordImplicitPointsToSet(arrayRefPtrKey); InstanceKey[] ik = getInvariantContents(arrayRef); for (InstanceKey instanceKey : ik) { if (!representsNullType(instanceKey)) { system.findOrCreateIndexForInstanceKey(instanceKey); PointerKey p = getPointerKeyForArrayContents(instanceKey); if (p == null) { } else { system.newConstraint(result, assignOperator, p); } } } } else { assert !system.isUnified(result); assert !system.isUnified(arrayRefPtrKey); system.newSideEffect( getBuilder().new ArrayLoadOperator(system.findOrCreatePointsToSet(result)), arrayRefPtrKey); } } } /** * @see * com.ibm.wala.ssa.SSAInstruction.Visitor#visitArrayStore(com.ibm.wala.ssa.SSAArrayStoreInstruction) */ public void doVisitArrayStore(int arrayRef, int value) { // (requires the creation of assign constraints as // the set points-to(a[]) grows.) PointerKey valuePtrKey = getPointerKeyForLocal(value); PointerKey arrayRefPtrKey = getPointerKeyForLocal(arrayRef); // if (!supportFullPointerFlowGraph && // contentsAreInvariant(instruction.getArrayRef())) { if (contentsAreInvariant(symbolTable, du, arrayRef)) { system.recordImplicitPointsToSet(arrayRefPtrKey); InstanceKey[] ik = getInvariantContents(arrayRef); for (InstanceKey instanceKey : ik) { if (!representsNullType(instanceKey) && !(instanceKey instanceof ZeroLengthArrayInNode)) { system.findOrCreateIndexForInstanceKey(instanceKey); PointerKey p = getPointerKeyForArrayContents(instanceKey); IClass contents = ((ArrayClass) instanceKey.getConcreteType()).getElementClass(); if (p == null) { } else { if (contentsAreInvariant(symbolTable, du, value)) { system.recordImplicitPointsToSet(valuePtrKey); InstanceKey[] vk = getInvariantContents(value); for (InstanceKey element : vk) { system.findOrCreateIndexForInstanceKey(element); if (element.getConcreteType() != null) { if (getClassHierarchy().isAssignableFrom(contents, element.getConcreteType())) { system.newConstraint(p, element); } } } } else { if (isRootType(contents)) { system.newConstraint(p, assignOperator, valuePtrKey); } else { system.newConstraint(p, getBuilder().filterOperator, valuePtrKey); } } } } } } else { if (contentsAreInvariant(symbolTable, du, value)) { system.recordImplicitPointsToSet(valuePtrKey); InstanceKey[] ik = getInvariantContents(value); for (InstanceKey element : ik) { system.findOrCreateIndexForInstanceKey(element); assert !system.isUnified(arrayRefPtrKey); system.newSideEffect( getBuilder().new InstanceArrayStoreOperator(element), arrayRefPtrKey); } } else { system.newSideEffect( getBuilder().new ArrayStoreOperator(system.findOrCreatePointsToSet(valuePtrKey)), arrayRefPtrKey); } } } @Override public void visitArrayStore(SSAArrayStoreInstruction instruction) { // skip arrays of primitive type if (instruction.typeIsPrimitive()) { return; } doVisitArrayStore(instruction.getArrayRef(), instruction.getValue()); } @Override public void visitCheckCast(SSACheckCastInstruction instruction) { boolean isRoot = false; Set<IClass> types = HashSetFactory.make(); for (TypeReference t : instruction.getDeclaredResultTypes()) { IClass cls = getClassHierarchy().lookupClass(t); if (cls == null) { Warnings.add(CheckcastFailure.create(t)); return; } else { if (isRootType(cls)) { isRoot = true; } types.add(cls); } } PointerKey result = getFilteredPointerKeyForLocal( instruction.getResult(), new FilteredPointerKey.MultipleClassesFilter(types.toArray(new IClass[0]))); PointerKey value = getPointerKeyForLocal(instruction.getVal()); if (hasNoInterestingUses(instruction.getDef())) { system.recordImplicitPointsToSet(result); } else { if (contentsAreInvariant(symbolTable, du, instruction.getVal())) { system.recordImplicitPointsToSet(value); InstanceKey[] ik = getInvariantContents(instruction.getVal()); for (TypeReference t : instruction.getDeclaredResultTypes()) { IClass cls = getClassHierarchy().lookupClass(t); if (cls.isInterface()) { for (InstanceKey element : ik) { system.findOrCreateIndexForInstanceKey(element); if (getClassHierarchy().implementsInterface(element.getConcreteType(), cls)) { system.newConstraint(result, element); } } } else { for (InstanceKey element : ik) { system.findOrCreateIndexForInstanceKey(element); if (getClassHierarchy().isSubclassOf(element.getConcreteType(), cls)) { system.newConstraint(result, element); } } } } } else { if (isRoot) { system.newConstraint(result, assignOperator, value); } else { system.newConstraint(result, getBuilder().filterOperator, value); } } } } @Override public void visitReturn(SSAReturnInstruction instruction) { // skip returns of primitive type if (instruction.returnsPrimitiveType() || instruction.returnsVoid()) { return; } if (DEBUG) { System.err.println("visitReturn: " + instruction); } PointerKey returnValue = getPointerKeyForReturnValue(); PointerKey result = getPointerKeyForLocal(instruction.getResult()); if (contentsAreInvariant(symbolTable, du, instruction.getResult())) { system.recordImplicitPointsToSet(result); InstanceKey[] ik = getInvariantContents(instruction.getResult()); for (InstanceKey element : ik) { if (DEBUG) { System.err.println("invariant contents: " + returnValue + ' ' + element); } system.newConstraint(returnValue, element); } } else { system.newConstraint(returnValue, assignOperator, result); } } @Override public void visitGet(SSAGetInstruction instruction) { visitGetInternal( instruction.getDef(), instruction.getRef(), instruction.isStatic(), instruction.getDeclaredField()); } protected void visitGetInternal(int lval, int ref, boolean isStatic, FieldReference field) { if (DEBUG) { System.err.println("visitGet " + field); } PointerKey def = getPointerKeyForLocal(lval); assert def != null; IField f = getClassHierarchy().resolveField(field); if (f == null && callGraph .getFakeRootNode() .getMethod() .getDeclaringClass() .getReference() .equals(field.getDeclaringClass())) { f = callGraph.getFakeRootNode().getMethod().getDeclaringClass().getField(field.getName()); } if (f == null) { return; } if (isStatic) { IClass klass = getClassHierarchy().lookupClass(field.getDeclaringClass()); if (klass == null) { } else { // side effect of getstatic: may call class initializer if (DEBUG) { System.err.println("getstatic call class init " + klass); } processClassInitializer(klass); } } // skip getfields of primitive type (optimisation) if (field.getFieldType().isPrimitiveType()) { return; } if (hasNoInterestingUses(lval)) { system.recordImplicitPointsToSet(def); } else { if (isStatic) { PointerKey fKey = getPointerKeyForStaticField(f); system.newConstraint(def, assignOperator, fKey); } else { PointerKey refKey = getPointerKeyForLocal(ref); // if (!supportFullPointerFlowGraph && // contentsAreInvariant(ref)) { if (contentsAreInvariant(symbolTable, du, ref)) { system.recordImplicitPointsToSet(refKey); InstanceKey[] ik = getInvariantContents(ref); for (InstanceKey instanceKey : ik) { if (!representsNullType(instanceKey)) { system.findOrCreateIndexForInstanceKey(instanceKey); PointerKey p = getPointerKeyForInstanceField(instanceKey, f); if (p != null) { system.newConstraint(def, assignOperator, p); } } } } else { system.newSideEffect( getBuilder().new GetFieldOperator(f, system.findOrCreatePointsToSet(def)), refKey); } } } } @Override public void visitPut(SSAPutInstruction instruction) { visitPutInternal( instruction.getVal(), instruction.getRef(), instruction.isStatic(), instruction.getDeclaredField()); } public void visitPutInternal(int rval, int ref, boolean isStatic, FieldReference field) { if (DEBUG) { System.err.println("visitPut " + field); } // skip putfields of primitive type if (field.getFieldType().isPrimitiveType()) { return; } IField f = getClassHierarchy().resolveField(field); if (f == null) { if (DEBUG) { System.err.println("Could not resolve field " + field); } Warnings.add(FieldResolutionFailure.create(field)); return; } assert f.getFieldTypeReference().getName().equals(field.getFieldType().getName()) : "name clash of two fields with the same name but different type: " + f.getReference() + " <=> " + field; assert isStatic || !symbolTable.isStringConstant(ref) : "put to string constant shouldn't be allowed?"; if (isStatic) { processPutStatic(rval, field, f); } else { processPutField(rval, ref, f); } } public void processPutField(int rval, int ref, IField f) { assert !f.getFieldTypeReference().isPrimitiveType(); PointerKey refKey = getPointerKeyForLocal(ref); PointerKey rvalKey = getPointerKeyForLocal(rval); // if (!supportFullPointerFlowGraph && // contentsAreInvariant(rval)) { if (contentsAreInvariant(symbolTable, du, rval)) { system.recordImplicitPointsToSet(rvalKey); InstanceKey[] ik = getInvariantContents(rval); if (contentsAreInvariant(symbolTable, du, ref)) { system.recordImplicitPointsToSet(refKey); InstanceKey[] refk = getInvariantContents(ref); for (InstanceKey instanceKey : refk) { if (!representsNullType(instanceKey)) { system.findOrCreateIndexForInstanceKey(instanceKey); PointerKey p = getPointerKeyForInstanceField(instanceKey, f); for (InstanceKey element : ik) { system.newConstraint(p, element); } } } } else { for (InstanceKey element : ik) { system.findOrCreateIndexForInstanceKey(element); system.newSideEffect(getBuilder().new InstancePutFieldOperator(f, element), refKey); } } } else { if (contentsAreInvariant(symbolTable, du, ref)) { system.recordImplicitPointsToSet(refKey); InstanceKey[] refk = getInvariantContents(ref); for (InstanceKey instanceKey : refk) { if (!representsNullType(instanceKey)) { system.findOrCreateIndexForInstanceKey(instanceKey); PointerKey p = getPointerKeyForInstanceField(instanceKey, f); system.newConstraint(p, assignOperator, rvalKey); } } } else { if (DEBUG) { System.err.println("adding side effect " + f); } system.newSideEffect( getBuilder().new PutFieldOperator(f, system.findOrCreatePointsToSet(rvalKey)), refKey); } } } protected void processPutStatic(int rval, FieldReference field, IField f) { PointerKey fKey = getPointerKeyForStaticField(f); PointerKey rvalKey = getPointerKeyForLocal(rval); // if (!supportFullPointerFlowGraph && // contentsAreInvariant(rval)) { if (contentsAreInvariant(symbolTable, du, rval)) { system.recordImplicitPointsToSet(rvalKey); InstanceKey[] ik = getInvariantContents(rval); for (InstanceKey element : ik) { system.newConstraint(fKey, element); } } else { system.newConstraint(fKey, assignOperator, rvalKey); } if (DEBUG) { System.err.println("visitPut class init " + field.getDeclaringClass() + ' ' + field); } // side effect of putstatic: may call class initializer IClass klass = getClassHierarchy().lookupClass(field.getDeclaringClass()); if (klass == null) { Warnings.add(FieldResolutionFailure.create(field)); } else { processClassInitializer(klass); } } @Override public void visitInvoke(SSAInvokeInstruction instruction) { visitInvokeInternal(instruction, new DefaultInvariantComputer()); } protected void visitInvokeInternal( final SSAAbstractInvokeInstruction instruction, InvariantComputer invs) { if (DEBUG) { System.err.println("visitInvoke: " + instruction); } PointerKey uniqueCatch = null; if (hasUniqueCatchBlock(instruction, ir)) { uniqueCatch = getBuilder().getUniqueCatchKey(instruction, ir, node); } InstanceKey[][] invariantParameters = invs.computeInvariantParameters(instruction); IntSet params = getBuilder().getContextSelector().getRelevantParameters(node, instruction.getCallSite()); if (!instruction.getCallSite().isStatic() && !params.contains(0) && (invariantParameters == null || invariantParameters[0] == null)) { params = IntSetUtil.makeMutableCopy(params); ((MutableIntSet) params).add(0); } if (invariantParameters != null) { for (int i = 0; i < invariantParameters.length; i++) { if (invariantParameters[i] != null) { params = IntSetUtil.makeMutableCopy(params); ((MutableIntSet) params).remove(i); } } } if (!params.isEmpty() && params.max() >= instruction.getNumberOfUses()) { MutableIntSet trimmedParams = IntSetUtil.makeMutableCopy(params); params.foreach( (i) -> { if (i >= instruction.getNumberOfUses()) trimmedParams.remove(i); }); params = trimmedParams; } if (params.isEmpty()) { for (CGNode n : getBuilder().getTargetsForCall(node, instruction, invariantParameters)) { getBuilder().processResolvedCall(node, instruction, n, invariantParameters, uniqueCatch); if (DEBUG) { System.err.println("visitInvoke class init " + n); } // side effect of invoke: may call class initializer processClassInitializer(n.getMethod().getDeclaringClass()); } } else { // Add a side effect that will fire when we determine a value // for a dispatch parameter. This side effect will create a new node // and new constraints based on the new callee context. final int vns[] = new int[params.size()]; params.foreach( new IntSetAction() { private int i = 0; @Override public void act(int x) { vns[i++] = instruction.getUse(x); } }); if (contentsAreInvariant(symbolTable, du, vns)) { for (CGNode n : getBuilder().getTargetsForCall(node, instruction, invariantParameters)) { getBuilder() .processResolvedCall(node, instruction, n, invariantParameters, uniqueCatch); // side effect of invoke: may call class initializer processClassInitializer(n.getMethod().getDeclaringClass()); } } else { if (DEBUG) { System.err.println("Add side effect, dispatch to " + instruction + " for " + params); } final List<PointerKey> pks = new ArrayList<>(params.size()); params.foreach( x -> { if (!contentsAreInvariant(symbolTable, du, instruction.getUse(x))) { pks.add(getBuilder().getPointerKeyForLocal(node, instruction.getUse(x))); } }); DispatchOperator dispatchOperator = getBuilder() .new DispatchOperator(instruction, node, invariantParameters, uniqueCatch, params); system.newSideEffect(dispatchOperator, pks.toArray(new PointerKey[0])); } } } @Override public void visitNew(SSANewInstruction instruction) { InstanceKey iKey = getInstanceKeyForAllocation(instruction.getNewSite()); if (iKey == null) { // something went wrong. I hope someone raised a warning. return; } PointerKey def = getPointerKeyForLocal(instruction.getDef()); IClass klass = iKey.getConcreteType(); if (DEBUG) { System.err.println( "visitNew: " + instruction + " i:" + iKey + ' ' + system.findOrCreateIndexForInstanceKey(iKey)); } if (klass == null) { if (DEBUG) { System.err.println("Resolution failure: " + instruction); } return; } if (!contentsAreInvariant(symbolTable, du, instruction.getDef())) { system.newConstraint(def, iKey); } else { system.findOrCreateIndexForInstanceKey(iKey); system.recordImplicitPointsToSet(def); } // side effect of new: may call class initializer if (DEBUG) { System.err.println("visitNew call clinit: " + klass); } processClassInitializer(klass); processFinalizeMethod(klass); // add instance keys and pointer keys for array contents int dim = 0; InstanceKey lastInstance = iKey; while (klass != null && klass.isArrayClass()) { klass = ((ArrayClass) klass).getElementClass(); // klass == null means it's a primitive if (klass != null && klass.isArrayClass()) { if (instruction.getNumberOfUses() <= (dim + 1)) { break; } int sv = instruction.getUse(dim + 1); if (ir.getSymbolTable().isIntegerConstant(sv)) { Integer c = (Integer) ir.getSymbolTable().getConstantValue(sv); if (c == 0) { break; } } InstanceKey ik = getInstanceKeyForMultiNewArray(instruction.getNewSite(), dim); PointerKey pk = getPointerKeyForArrayContents(lastInstance); if (DEBUG_MULTINEWARRAY) { System.err.println("multinewarray constraint: "); System.err.println(" pk: " + pk); System.err.println( " ik: " + system.findOrCreateIndexForInstanceKey(ik) + " concrete type " + ik.getConcreteType() + " is " + ik); System.err.println(" klass:" + klass); } system.newConstraint(pk, ik); lastInstance = ik; dim++; } } } @Override public void visitThrow(SSAThrowInstruction instruction) { // don't do anything: we handle exceptional edges // in a separate pass } @Override public void visitGetCaughtException(SSAGetCaughtExceptionInstruction instruction) { List<ProgramCounter> peis = getIncomingPEIs(ir, getBasicBlock()); PointerKey def = getPointerKeyForLocal(instruction.getDef()); // SJF: we don't optimize based on dead catch blocks yet ... it's a little // tricky due interaction with the SINGLE_USE optimization which directly // shoves exceptional return values from calls into exception vars. // it may not be worth doing this. // if (hasNoInterestingUses(instruction.getDef(), du)) { // solver.recordImplicitPointsToSet(def); // } else { Set<IClass> types = getCaughtExceptionTypes(instruction, ir); getBuilder().addExceptionDefConstraints(ir, du, node, peis, def, types); // } } /** TODO: What is this doing? Document me! */ private int booleanConstantTest(SSAConditionalBranchInstruction c, int v) { int result = 0; // right for OPR_eq if ((symbolTable.isZeroOrFalse(c.getUse(0)) && c.getUse(1) == v) || (symbolTable.isZeroOrFalse(c.getUse(1)) && c.getUse(0) == v)) { result = -1; } else if ((symbolTable.isOneOrTrue(c.getUse(0)) && c.getUse(1) == v) || (symbolTable.isOneOrTrue(c.getUse(1)) && c.getUse(0) == v)) { result = 1; } if (c.getOperator() == ConditionalBranchInstruction.Operator.NE) { result = -result; } return result; } private int nullConstantTest(SSAConditionalBranchInstruction c, int v) { if ((symbolTable.isNullConstant(c.getUse(0)) && c.getUse(1) == v) || (symbolTable.isNullConstant(c.getUse(1)) && c.getUse(0) == v)) { if (c.getOperator() == ConditionalBranchInstruction.Operator.EQ) { return 1; } else { return -1; } } else { return 0; } } @Override public void visitPhi(SSAPhiInstruction instruction) { if (ir.getMethod() instanceof AbstractRootMethod) { PointerKey dst = getPointerKeyForLocal(instruction.getDef()); if (hasNoInterestingUses(instruction.getDef())) { system.recordImplicitPointsToSet(dst); } else { for (int i = 0; i < instruction.getNumberOfUses(); i++) { PointerKey use = getPointerKeyForLocal(instruction.getUse(i)); if (contentsAreInvariant(symbolTable, du, instruction.getUse(i))) { system.recordImplicitPointsToSet(use); InstanceKey[] ik = getInvariantContents(instruction.getUse(i)); for (InstanceKey element : ik) { system.newConstraint(dst, element); } } else { system.newConstraint(dst, assignOperator, use); } } } } } @Override public void visitPi(SSAPiInstruction instruction) { int dir; if (hasNoInterestingUses(instruction.getDef())) { PointerKey dst = getPointerKeyForLocal(instruction.getDef()); system.recordImplicitPointsToSet(dst); } else { ControlFlowGraph<SSAInstruction, ISSABasicBlock> cfg = ir.getControlFlowGraph(); int val = instruction.getVal(); if (com.ibm.wala.cfg.Util.endsWithConditionalBranch(cfg, getBasicBlock()) && cfg.getSuccNodeCount(getBasicBlock()) == 2) { SSAConditionalBranchInstruction cond = (SSAConditionalBranchInstruction) com.ibm.wala.cfg.Util.getLastInstruction(cfg, getBasicBlock()); SSAInstruction cause = instruction.getCause(); BasicBlock target = (BasicBlock) cfg.getNode(instruction.getSuccessor()); if ((cause instanceof SSAInstanceofInstruction)) { int direction = booleanConstantTest(cond, cause.getDef()); if (direction != 0) { TypeReference type = ((SSAInstanceofInstruction) cause).getCheckedType(); IClass cls = getClassHierarchy().lookupClass(type); if (cls == null) { PointerKey dst = getPointerKeyForLocal(instruction.getDef()); addPiAssignment(dst, val); } else { PointerKey dst = getFilteredPointerKeyForLocal( instruction.getDef(), new FilteredPointerKey.SingleClassFilter(cls)); // if true, only allow objects assignable to cls. otherwise, only allow objects // *not* assignable to cls boolean useFilter = (target == com.ibm.wala.cfg.Util.getTakenSuccessor(cfg, getBasicBlock()) && direction == 1) || (target == com.ibm.wala.cfg.Util.getNotTakenSuccessor(cfg, getBasicBlock()) && direction == -1); PointerKey src = getPointerKeyForLocal(val); if (contentsAreInvariant(symbolTable, du, val)) { system.recordImplicitPointsToSet(src); InstanceKey[] ik = getInvariantContents(val); for (InstanceKey element : ik) { boolean assignable = getClassHierarchy().isAssignableFrom(cls, element.getConcreteType()); if ((assignable && useFilter) || (!assignable && !useFilter)) { system.newConstraint(dst, element); } } } else { FilterOperator op = useFilter ? getBuilder().filterOperator : getBuilder().inverseFilterOperator; system.newConstraint(dst, op, src); } } } } else if ((dir = nullConstantTest(cond, val)) != 0) { if ((target == com.ibm.wala.cfg.Util.getTakenSuccessor(cfg, getBasicBlock()) && dir == -1) || (target == com.ibm.wala.cfg.Util.getNotTakenSuccessor(cfg, getBasicBlock()) && dir == 1)) { PointerKey dst = getPointerKeyForLocal(instruction.getDef()); addPiAssignment(dst, val); } } else { PointerKey dst = getPointerKeyForLocal(instruction.getDef()); addPiAssignment(dst, val); } } else { PointerKey dst = getPointerKeyForLocal(instruction.getDef()); addPiAssignment(dst, val); } } } /** * Add a constraint to the system indicating that the contents of local src flows to dst, with * no special type filter. */ private void addPiAssignment(PointerKey dst, int src) { PointerKey srcKey = getPointerKeyForLocal(src); if (contentsAreInvariant(symbolTable, du, src)) { system.recordImplicitPointsToSet(srcKey); InstanceKey[] ik = getInvariantContents(src); for (InstanceKey element : ik) { system.newConstraint(dst, element); } } else { system.newConstraint(dst, assignOperator, srcKey); } } public ISSABasicBlock getBasicBlock() { return basicBlock; } /** The calling loop must call this in each iteration! */ public void setBasicBlock(ISSABasicBlock block) { basicBlock = block; } protected interface InvariantComputer { InstanceKey[][] computeInvariantParameters(SSAAbstractInvokeInstruction call); } public class DefaultInvariantComputer implements InvariantComputer { /** * Side effect: records invariant parameters as implicit points-to-sets. * * @return if non-null, then result[i] holds the set of instance keys which may be passed as * the ith parameter. (which must be invariant) */ @Override public InstanceKey[][] computeInvariantParameters(SSAAbstractInvokeInstruction call) { InstanceKey[][] constParams = null; for (int i = 0; i < call.getNumberOfUses(); i++) { // not sure how getUse(i) <= 0 .. dead code? // TODO: investigate if (call.getUse(i) > 0) { if (contentsAreInvariant(symbolTable, du, call.getUse(i))) { system.recordImplicitPointsToSet(getPointerKeyForLocal(call.getUse(i))); if (constParams == null) { constParams = new InstanceKey[call.getNumberOfUses()][]; } constParams[i] = getInvariantContents(call.getUse(i)); for (int j = 0; j < constParams[i].length; j++) { system.findOrCreateIndexForInstanceKey(constParams[i][j]); } } } } return constParams; } } @Override public void visitLoadMetadata(SSALoadMetadataInstruction instruction) { PointerKey def = getPointerKeyForLocal(instruction.getDef()); InstanceKey iKey = getInstanceKeyForClassObject(instruction.getToken(), instruction.getType()); if (instruction.getToken() instanceof TypeReference) { IClass klass = getClassHierarchy().lookupClass((TypeReference) instruction.getToken()); if (klass != null) { processClassInitializer(klass); } } if (!contentsAreInvariant(symbolTable, du, instruction.getDef())) { system.newConstraint(def, iKey); } else { system.findOrCreateIndexForInstanceKey(iKey); system.recordImplicitPointsToSet(def); } } private void processFinalizeMethod(final IClass klass) { if (getBuilder().finalizeVisited.add(klass)) { IMethod finalizer = klass.getMethod(MethodReference.finalizeSelector); if (finalizer != null && !finalizer.getDeclaringClass().getReference().equals(TypeReference.JavaLangObject)) { Entrypoint ef = new DefaultEntrypoint(finalizer, getClassHierarchy()) { @Override protected TypeReference[] makeParameterTypes(IMethod method, int i) { if (i == 0) { return new TypeReference[] {klass.getReference()}; } else { return super.makeParameterTypes(method, i); } } }; ef.addCall((AbstractRootMethod) callGraph.getFakeRootNode().getMethod()); getBuilder().markChanged(callGraph.getFakeRootNode()); } } } /** * TODO: lift most of this logic to PropagationCallGraphBuilder * * <p>Add a call to the class initializer from the root method. */ protected void processClassInitializer(IClass klass) { assert klass != null; if (!getBuilder().getOptions().getHandleStaticInit()) { return; } if (getBuilder().clinitVisited.contains(klass)) { return; } getBuilder().clinitVisited.add(klass); if (klass.getClassInitializer() != null) { if (DEBUG) { System.err.println("process class initializer for " + klass); } // add an invocation from the fake root method to the <clinit> MethodReference m = klass.getClassInitializer().getReference(); CallSiteReference site = CallSiteReference.make(1, m, IInvokeInstruction.Dispatch.STATIC); IMethod targetMethod = getOptions() .getMethodTargetSelector() .getCalleeTarget(callGraph.getFakeRootNode(), site, null); if (targetMethod != null) { CGNode target = getTargetForCall(callGraph.getFakeRootNode(), site, null, null); if (target != null && callGraph.getPredNodeCount(target) == 0) { AbstractRootMethod fakeWorldClinitMethod = (AbstractRootMethod) callGraph.getFakeWorldClinitNode().getMethod(); SSAAbstractInvokeInstruction s = fakeWorldClinitMethod.addInvocation(new int[0], site); PointerKey uniqueCatch = getBuilder().getPointerKeyForExceptionalReturnValue(callGraph.getFakeRootNode()); getBuilder() .processResolvedCall( callGraph.getFakeWorldClinitNode(), s, target, null, uniqueCatch); } } } IClass sc = klass.getSuperclass(); if (sc != null) { processClassInitializer(sc); } } } /** * Add constraints for a call site after we have computed a reachable target for the dispatch * * <p>Side effect: add edge to the call graph. * * @param constParams if non-null, then constParams[i] holds the set of instance keys that are * passed as param i, or null if param i is not invariant * @param uniqueCatchKey if non-null, then this is the unique PointerKey that catches all * exceptions from this call site. */ private void processResolvedCall( CGNode caller, SSAAbstractInvokeInstruction instruction, CGNode target, InstanceKey[][] constParams, PointerKey uniqueCatchKey) { if (DEBUG) { System.err.println("processResolvedCall: " + caller + " ," + instruction + " , " + target); } if (DEBUG) { System.err.println("addTarget: " + caller + " ," + instruction + " , " + target); } caller.addTarget(instruction.getCallSite(), target); if (callGraph.getFakeRootNode().equals(caller)) { if (entrypointCallSites.contains(instruction.getCallSite())) { callGraph.registerEntrypoint(target); } } if (!haveAlreadyVisited(target)) { markDiscovered(target); } processCallingConstraints(caller, instruction, target, constParams, uniqueCatchKey); } @SuppressWarnings("unused") protected void processCallingConstraints( CGNode caller, SSAAbstractInvokeInstruction instruction, CGNode target, InstanceKey[][] constParams, PointerKey uniqueCatchKey) { // TODO: i'd like to enable this optimization, but it's a little tricky // to recover the implicit points-to sets with recursion. TODO: don't // be lazy and code the recursive logic to enable this. // if (hasNoInstructions(target)) { // // record points-to sets for formals implicitly .. computed on // // demand. // // TODO: generalize this by using hasNoInterestingUses on parameters. // // however .. have to be careful to cache results in that case ... don't // // want // // to recompute du each time we process a call to Object.<init> ! // for (int i = 0; i < instruction.getNumberOfUses(); i++) { // // we rely on the invariant that the value number for the ith parameter // // is i+1 // final int vn = i + 1; // PointerKey formal = getPointerKeyForLocal(target, vn); // if (target.getMethod().getParameterType(i).isReferenceType()) { // system.recordImplicitPointsToSet(formal); // } // } // } else { // generate contraints from parameter passing int nUses = instruction.getNumberOfPositionalParameters(); int nExpected = target.getMethod().getNumberOfParameters(); /* * int nExpected = target.getMethod().getReference().getNumberOfParameters(); if (!target.getMethod().isStatic() && * !target.getMethod().isClinit()) { nExpected++; } */ if (nUses != nExpected) { // some sort of unverifiable code mismatch. give up. return; } // we're a little sloppy for now ... we don't filter calls to // java.lang.Object. // TODO: we need much more precise filters than cones in order to handle // the various types of dispatch logic. We need a filter that expresses // "the set of types s.t. x.foo resolves to y.foo." for (int i = 0; i < instruction.getNumberOfPositionalParameters(); i++) { if (target.getMethod().getParameterType(i).isReferenceType()) { PointerKey formal = getTargetPointerKey(target, i); if (constParams != null && constParams[i] != null) { InstanceKey[] ik = constParams[i]; for (InstanceKey element : ik) { system.newConstraint(formal, element); } } else { if (instruction.getUse(i) < 0) { Assertions.UNREACHABLE("unexpected " + instruction + " in " + caller); } PointerKey actual = getPointerKeyForLocal(caller, instruction.getUse(i)); if (formal instanceof FilteredPointerKey) { system.newConstraint(formal, filterOperator, actual); } else { system.newConstraint(formal, assignOperator, actual); } } } } // generate contraints from return value. if (instruction.hasDef() && instruction.getDeclaredResultType().isReferenceType()) { PointerKey result = getPointerKeyForLocal(caller, instruction.getDef()); PointerKey ret = getPointerKeyForReturnValue(target); system.newConstraint(result, assignOperator, ret); } // generate constraints from exception return value. PointerKey e = getPointerKeyForLocal(caller, instruction.getException()); PointerKey er = getPointerKeyForExceptionalReturnValue(target); if (SHORT_CIRCUIT_SINGLE_USES && uniqueCatchKey != null) { // e has exactly one use. so, represent e implicitly system.newConstraint(uniqueCatchKey, assignOperator, er); } else { system.newConstraint(e, assignOperator, er); } // } } /** * An operator to fire when we discover a potential new callee for a virtual or interface call * site. * * <p>This operator will create a new callee context and constraints if necessary. */ final class DispatchOperator extends AbstractOperator<PointsToSetVariable> implements IPointerOperator { private final SSAAbstractInvokeInstruction call; private final CGNode node; private final InstanceKey[][] constParams; private final PointerKey uniqueCatch; /** * relevant parameter indices for the registered {@link ContextSelector} * * @see ContextSelector#getRelevantParameters(CGNode, CallSiteReference) */ private final int[] dispatchIndices; /** * The set of instance keys that have already been processed. previousPtrs[i] contains the * processed instance keys for parameter position dispatchIndices[i] */ private final MutableIntSet[] previousPtrs; /** * @param constParams if non-null, then constParams[i] holds the String constant that is passed * as param i, or null if param i is not a String constant */ DispatchOperator( SSAAbstractInvokeInstruction call, CGNode node, InstanceKey[][] constParams, PointerKey uniqueCatch, IntSet dispatchIndices) { this.call = call; this.node = node; this.constParams = constParams; this.uniqueCatch = uniqueCatch; this.dispatchIndices = IntSetUtil.toArray(dispatchIndices); // we better always be interested in the receiver // assert this.dispatchIndices[0] == 0; previousPtrs = new MutableIntSet[dispatchIndices.size()]; Arrays.setAll(previousPtrs, i -> IntSetUtil.getDefaultIntSetFactory().make()); } private byte cpa(final PointsToSetVariable[] rhs) { final MutableBoolean changed = new MutableBoolean(); for (int rhsIndex = 0; rhsIndex < rhs.length; rhsIndex++) { final int y = rhsIndex; IntSet currentObjs = rhs[rhsIndex].getValue(); if (currentObjs != null) { final IntSet oldObjs = previousPtrs[rhsIndex]; currentObjs.foreachExcluding( oldObjs, x -> new CrossProductRec( constParams, call, node, v -> { IClass recv = null; if (call.getCallSite().isDispatch()) { recv = v[0].getConcreteType(); } CGNode target = getTargetForCall(node, call.getCallSite(), recv, v); if (target != null) { changed.b = true; processResolvedCall(node, call, target, constParams, uniqueCatch); if (!haveAlreadyVisited(target)) { markDiscovered(target); } } }) { { rec(0, 0); } @Override protected IntSet getParamObjects(int paramVn, int rhsi) { if (rhsi == y) { return IntSetUtil.make(new int[] {x}); } else { return previousPtrs[rhsi]; } } }); previousPtrs[rhsIndex].addAll(currentObjs); } } byte sideEffectMask = changed.b ? (byte) SIDE_EFFECT_MASK : 0; return (byte) (NOT_CHANGED | sideEffectMask); } /** @see com.ibm.wala.fixpoint.UnaryOperator#evaluate(IVariable, IVariable) */ @Override public byte evaluate(PointsToSetVariable lhs, final PointsToSetVariable[] rhs) { assert dispatchIndices.length >= rhs.length : "bad operator at " + call; return cpa(rhs); /* // did evaluating the dispatch operation add a new possible target // to the call site? final MutableBoolean addedNewTarget = new MutableBoolean(); final MutableIntSet receiverVals; if (constParams != null && constParams[0] != null) { receiverVals = IntSetUtil.make(); for(InstanceKey ik : constParams[0]) { receiverVals.add(system.getInstanceIndex(ik)); } } else { receiverVals = rhs[0].getValue(); } if (receiverVals == null) { // this constraint was put on the work list, probably by // initialization, // even though the right-hand-side is empty. // TODO: be more careful about what goes on the worklist to // avoid this. if (DEBUG) { System.err.println("EVAL dispatch with value null"); } return NOT_CHANGED; } // we handle the parameter positions one by one, rather than enumerating // the cartesian product of possibilities. this disallows // context-sensitivity policies like true CPA, but is necessary for // performance. InstanceKey keys[] = new InstanceKey[constParams == null? dispatchIndices[dispatchIndices.length-1]+1: constParams.length]; // determine whether we're handling a new receiver; used later // to check for redundancy boolean newReceiver = !receiverVals.isSubset(previousPtrs[0]); // keep separate rhsIndex, since it doesn't advance for constant // parameters int rhsIndex = (constParams != null && constParams[0] != null)? 0: 1; // this flag is set to true if we ever call handleAllReceivers() in the // loop below. we need to catch the case where we have a new receiver, but // there are no other dispatch indices with new values boolean propagatedReceivers = false; // we start at index 1 since we need to handle the receiver specially; see // below for (int index = 1; index < dispatchIndices.length; index++) { try { MonitorUtil.throwExceptionIfCanceled(monitor); } catch (CancelException e) { throw new CancelRuntimeException(e); } int paramIndex = dispatchIndices[index]; assert keys[paramIndex] == null; final MutableIntSet prevAtIndex = previousPtrs[index]; if (constParams != null && constParams[paramIndex] != null) { // we have a constant parameter. only need to propagate again if we've never done it before or if we have a new receiver if (newReceiver || prevAtIndex.isEmpty()) { for(int i = 0; i < constParams[paramIndex].length; i++) { keys[paramIndex] = constParams[paramIndex][i]; handleAllReceivers(receiverVals,keys, addedNewTarget); propagatedReceivers = true; int ii = system.instanceKeys.getMappedIndex(constParams[paramIndex][i]); prevAtIndex.add(ii); } } } else { // non-constant parameter PointsToSetVariable v = rhs[rhsIndex]; if (v.getValue() != null) { IntIterator ptrs = v.getValue().intIterator(); while (ptrs.hasNext()) { int ptr = ptrs.next(); if (newReceiver || !prevAtIndex.contains(ptr)) { keys[paramIndex] = system.getInstanceKey(ptr); handleAllReceivers(receiverVals,keys, addedNewTarget); propagatedReceivers = true; prevAtIndex.add(ptr); } } } rhsIndex++; } keys[paramIndex] = null; } if (newReceiver) { if (!propagatedReceivers) { // we have a new receiver value, and it wasn't propagated at all, // so propagate it now handleAllReceivers(receiverVals, keys, addedNewTarget); } // update receiver cache previousPtrs[0].addAll(receiverVals); } byte sideEffectMask = addedNewTarget.b ? (byte) SIDE_EFFECT_MASK : 0; return (byte) (NOT_CHANGED | sideEffectMask); */ } @SuppressWarnings("unused") private void handleAllReceivers( MutableIntSet receiverVals, InstanceKey[] keys, MutableBoolean sideEffect) { assert keys[0] == null; IntIterator receiverIter = receiverVals.intIterator(); while (receiverIter.hasNext()) { final int rcvr = receiverIter.next(); keys[0] = system.getInstanceKey(rcvr); if (clone2Assign) { // for efficiency: assume that only call sites that reference // clone() might dispatch to clone methods if (call.getCallSite().getDeclaredTarget().getSelector().equals(cloneSelector)) { IClass recv = (keys[0] != null) ? keys[0].getConcreteType() : null; IMethod targetMethod = getOptions() .getMethodTargetSelector() .getCalleeTarget(node, call.getCallSite(), recv); if (targetMethod != null && targetMethod.getReference().equals(CloneInterpreter.CLONE)) { // treat this call to clone as an assignment PointerKey result = getPointerKeyForLocal(node, call.getDef()); PointerKey receiver = getPointerKeyForLocal(node, call.getReceiver()); system.newConstraint(result, assignOperator, receiver); return; } } } CGNode target = getTargetForCall(node, call.getCallSite(), keys[0].getConcreteType(), keys); if (target == null) { // This indicates an error; I sure hope getTargetForCall // raised a warning about this! if (DEBUG) { System.err.println("Warning: null target for call " + call); } } else { IntSet targets = getCallGraph().getPossibleTargetNumbers(node, call.getCallSite()); // even if we've seen this target before, if we have constant // parameters, we may need to re-process the call, as the constraints // for the first time we reached this target may not have been fully // general. TODO a more refined check? if (targets != null && targets.contains(target.getGraphNodeId()) && noConstParams()) { // do nothing; we've previously discovered and handled this // receiver for this call site. } else { // process the newly discovered target for this call sideEffect.b = true; processResolvedCall(node, call, target, constParams, uniqueCatch); if (!haveAlreadyVisited(target)) { markDiscovered(target); } } } } keys[0] = null; } private boolean noConstParams() { if (constParams != null) { for (int i = 0; i < constParams.length; i++) { if (constParams[i] != null) { for (int j = 0; j < constParams[i].length; i++) { if (constParams[i][j] != null) { return false; } } } } } return true; } @Override public String toString() { return "Dispatch to " + call + " in node " + node; } @Override public int hashCode() { int h = 1; if (constParams != null) { for (InstanceKey[] cs : constParams) { if (cs != null) { for (InstanceKey c : cs) { if (c != null) { h ^= c.hashCode(); } } } } } return h * node.hashCode() + 90289 * call.hashCode(); } @Override public boolean equals(Object o) { // note that these are not necessarily canonical, since // with synthetic factories we may regenerate constraints // many times. TODO: change processing of synthetic factories // so that we guarantee to insert each dispatch equation // only once ... if this were true we could optimize this // with reference equality // instanceof is OK because this class is final if (o instanceof DispatchOperator) { DispatchOperator other = (DispatchOperator) o; return node.equals(other.node) && call.equals(other.call) && Arrays.deepEquals(constParams, other.constParams); } else { return false; } } @Override public boolean isComplex() { return true; } } protected void iterateCrossProduct( final CGNode caller, final SSAAbstractInvokeInstruction call, final InstanceKey[][] invariants, final Consumer<InstanceKey[]> f) { new CrossProductRec(invariants, call, caller, f).rec(0, 0); } protected Set<CGNode> getTargetsForCall( final CGNode caller, final SSAAbstractInvokeInstruction instruction, InstanceKey[][] invs) { // This method used to take a CallSiteReference as a parameter, rather than // an SSAAbstractInvokeInstruction. This was bad, since it's // possible for multiple invoke instructions with different actual // parameters to be associated with a single CallSiteReference. Changed // to take the invoke instruction as a parameter instead, since invs is // associated with the instruction final CallSiteReference site = instruction.getCallSite(); final Set<CGNode> targets = HashSetFactory.make(); Consumer<InstanceKey[]> f = v -> { IClass recv = null; if (site.isDispatch()) { recv = v[0].getConcreteType(); } CGNode target = getTargetForCall(caller, site, recv, v); if (target != null) { targets.add(target); } }; iterateCrossProduct(caller, instruction, invs, f); return targets; } private IntSet getRelevantParameters(final CGNode caller, final CallSiteReference site) throws UnimplementedError { IntSet params = contextSelector.getRelevantParameters(caller, site); if (!site.isStatic() && !params.contains(0)) { params = IntSetUtil.makeMutableCopy(params); ((MutableIntSet) params).add(0); } return params; } public boolean hasNoInterestingUses(CGNode node, int vn, DefUse du) { if (du == null) { throw new IllegalArgumentException("du is null"); } if (vn <= 0) { throw new IllegalArgumentException("v is invalid: " + vn); } // todo: enhance this by solving a dead-code elimination // problem. InterestingVisitor v = makeInterestingVisitor(node, vn); for (SSAInstruction s : Iterator2Iterable.make(du.getUses(v.vn))) { s.visit(v); if (v.bingo) { return false; } } return true; } protected InterestingVisitor makeInterestingVisitor( @SuppressWarnings("unused") CGNode node, int vn) { return new InterestingVisitor(vn); } /** sets bingo to true when it visits an interesting instruction */ protected static class InterestingVisitor extends SSAInstruction.Visitor { protected final int vn; public InterestingVisitor(int vn) { this.vn = vn; } protected boolean bingo = false; @Override public void visitArrayLoad(SSAArrayLoadInstruction instruction) { if (!instruction.typeIsPrimitive() && instruction.getArrayRef() == vn) { bingo = true; } } @Override public void visitArrayStore(SSAArrayStoreInstruction instruction) { if (!instruction.typeIsPrimitive() && (instruction.getArrayRef() == vn || instruction.getValue() == vn)) { bingo = true; } } @Override public void visitCheckCast(SSACheckCastInstruction instruction) { bingo = true; } @Override public void visitGet(SSAGetInstruction instruction) { FieldReference field = instruction.getDeclaredField(); if (!field.getFieldType().isPrimitiveType()) { bingo = true; } } @Override public void visitGetCaughtException(SSAGetCaughtExceptionInstruction instruction) { bingo = true; } @Override public void visitInvoke(SSAInvokeInstruction instruction) { bingo = true; } @Override public void visitPhi(SSAPhiInstruction instruction) { bingo = true; } @Override public void visitPi(SSAPiInstruction instruction) { bingo = true; } @Override public void visitPut(SSAPutInstruction instruction) { FieldReference field = instruction.getDeclaredField(); if (!field.getFieldType().isPrimitiveType()) { bingo = true; } } @Override public void visitReturn(SSAReturnInstruction instruction) { bingo = true; } @Override public void visitThrow(SSAThrowInstruction instruction) { bingo = true; } } /** * TODO: enhance this logic using type inference * * @return true if we need to filter the receiver type to account for virtual dispatch */ @SuppressWarnings("unused") private boolean needsFilterForReceiver(SSAAbstractInvokeInstruction instruction, CGNode target) { FilteredPointerKey.TypeFilter f = (FilteredPointerKey.TypeFilter) target.getContext().get(ContextKey.PARAMETERS[0]); if (f != null) { // the context selects a particular concrete type for the receiver. // we need to filter, unless the declared receiver type implies the // concrete type (TODO: need to implement this optimization) return true; } // don't need to filter for invokestatic if (instruction.getCallSite().isStatic() || instruction.getCallSite().isSpecial()) { return false; } MethodReference declaredTarget = instruction.getDeclaredTarget(); IMethod resolvedTarget = getClassHierarchy().resolveMethod(declaredTarget); // if resolvedTarget == null, then there's some problem that will be flagged as a warning return true; } private static boolean isRootType(IClass klass) { return klass.getClassHierarchy().isRootClass(klass); } @SuppressWarnings("unused") private static boolean isRootType(FilteredPointerKey.TypeFilter filter) { if (filter instanceof FilteredPointerKey.SingleClassFilter) { return isRootType(((FilteredPointerKey.SingleClassFilter) filter).getConcreteType()); } else { return false; } } /** * TODO: enhance this logic using type inference TODO!!!: enhance filtering to consider concrete * types, not just cones. precondition: needs Filter * * @return an IClass which represents */ public PointerKey getTargetPointerKey(CGNode target, int index) { int vn; if (target.getIR() != null) { vn = target.getIR().getSymbolTable().getParameter(index); } else { vn = index + 1; } FilteredPointerKey.TypeFilter filter = (FilteredPointerKey.TypeFilter) target.getContext().get(ContextKey.PARAMETERS[index]); if (filter != null && !filter.isRootFilter()) { return getFilteredPointerKeyForLocal(target, vn, filter); } else { // the context does not select a particular concrete type for the // receiver, so use the type of the method IClass C; if (index == 0 && !target.getMethod().isStatic()) { C = getReceiverClass(target.getMethod()); } else { C = cha.lookupClass(target.getMethod().getParameterType(index)); } if (C == null || C.getClassHierarchy().getRootClass().equals(C)) { return getPointerKeyForLocal(target, vn); } else { return getFilteredPointerKeyForLocal( target, vn, new FilteredPointerKey.SingleClassFilter(C)); } } } /** @return the receiver class for this method. */ private IClass getReceiverClass(IMethod method) { TypeReference formalType = method.getParameterType(0); IClass C = getClassHierarchy().lookupClass(formalType); if (method.isStatic()) { Assertions.UNREACHABLE("asked for receiver of static method " + method); } if (C == null) { Assertions.UNREACHABLE("no class found for " + formalType + " recv of " + method); } return C; } /** * A value is "invariant" if we can figure out the instances it can ever point to locally, without * resorting to propagation. * * @return true iff the contents of the local with this value number can be deduced locally, * without propagation */ public boolean contentsAreInvariant(SymbolTable symbolTable, DefUse du, int valueNumber) { if (isConstantRef(symbolTable, valueNumber)) { return true; } else if (SHORT_CIRCUIT_INVARIANT_SETS) { SSAInstruction def = du.getDef(valueNumber); if (def instanceof SSANewInstruction) { return true; } else { return false; } } else { return false; } } protected boolean contentsAreInvariant(SymbolTable symbolTable, DefUse du, int valueNumbers[]) { for (int valueNumber : valueNumbers) { if (!contentsAreInvariant(symbolTable, du, valueNumber)) { return false; } } return true; } /** * precondition:contentsAreInvariant(valueNumber) * * @return the complete set of instances that the local with vn=valueNumber may point to. */ public InstanceKey[] getInvariantContents( SymbolTable symbolTable, DefUse du, CGNode node, int valueNumber, HeapModel hm) { return getInvariantContents(symbolTable, du, node, valueNumber, hm, false); } protected InstanceKey[] getInvariantContents( SymbolTable symbolTable, DefUse du, CGNode node, int valueNumber, HeapModel hm, boolean ensureIndexes) { InstanceKey[] result; if (isConstantRef(symbolTable, valueNumber)) { Object x = symbolTable.getConstantValue(valueNumber); if (x instanceof String) { // this is always the case in Java. use strong typing in the call to // getInstanceKeyForConstant. String S = (String) x; TypeReference type = node.getMethod().getDeclaringClass().getClassLoader().getLanguage().getConstantType(S); if (type == null) { return new InstanceKey[0]; } InstanceKey ik = hm.getInstanceKeyForConstant(type, S); if (ik != null) { result = new InstanceKey[] {ik}; } else { result = new InstanceKey[0]; } } else { // some non-built in type (e.g. Integer). give up on strong typing. // language-specific subclasses (e.g. Javascript) should override this method to get strong // typing // with generics if desired. TypeReference type = node.getMethod().getDeclaringClass().getClassLoader().getLanguage().getConstantType(x); if (type == null) { return new InstanceKey[0]; } InstanceKey ik = hm.getInstanceKeyForConstant(type, x); if (ik != null) { result = new InstanceKey[] {ik}; } else { result = new InstanceKey[0]; } } } else { SSANewInstruction def = (SSANewInstruction) du.getDef(valueNumber); InstanceKey iKey = hm.getInstanceKeyForAllocation(node, def.getNewSite()); result = (iKey == null) ? new InstanceKey[0] : new InstanceKey[] {iKey}; } if (ensureIndexes) { for (InstanceKey element : result) { system.findOrCreateIndexForInstanceKey(element); } } return result; } protected boolean isConstantRef(SymbolTable symbolTable, int valueNumber) { if (valueNumber == -1) { return false; } if (symbolTable.isConstant(valueNumber)) { Object v = symbolTable.getConstantValue(valueNumber); return !(v instanceof Number); } else { return false; } } /** * @author sfink * <p>A warning for when we fail to resolve the type for a checkcast */ private static class CheckcastFailure extends Warning { final TypeReference type; CheckcastFailure(TypeReference type) { super(Warning.SEVERE); this.type = type; } @Override public String getMsg() { return getClass().toString() + " : " + type; } public static CheckcastFailure create(TypeReference type) { return new CheckcastFailure(type); } } /** * @author sfink * <p>A warning for when we fail to resolve the type for a field */ private static class FieldResolutionFailure extends Warning { final FieldReference field; FieldResolutionFailure(FieldReference field) { super(Warning.SEVERE); this.field = field; } @Override public String getMsg() { return getClass().toString() + " : " + field; } public static FieldResolutionFailure create(FieldReference field) { return new FieldResolutionFailure(field); } } @Override public Iterator<PointerKey> iteratePointerKeys() { return system.iteratePointerKeys(); } public static Set<IClass> getCaughtExceptionTypes( SSAGetCaughtExceptionInstruction instruction, IRView ir) { if (ir == null) { throw new IllegalArgumentException("ir is null"); } if (instruction == null) { throw new IllegalArgumentException("instruction is null"); } Iterator<TypeReference> exceptionTypes = ((ExceptionHandlerBasicBlock) ir.getControlFlowGraph().getNode(instruction.getBasicBlockNumber())) .getCaughtExceptionTypes(); HashSet<IClass> types = HashSetFactory.make(10); for (TypeReference tr : Iterator2Iterable.make(exceptionTypes)) { IClass c = ir.getMethod().getClassHierarchy().lookupClass(tr); if (c != null) { types.add(c); } } return types; } @Override public InstanceKey getInstanceKeyForPEI(CGNode node, ProgramCounter instr, TypeReference type) { return getInstanceKeyForPEI(node, instr, type, instanceKeyFactory); } @Override protected IPointsToSolver makeSolver() { return new StandardSolver(system, this); // return usePreTransitiveSolver ? (IPointsToSolver) new PreTransitiveSolver(system, this) : new // StandardSolver(system, this); // return true ? (IPointsToSolver)new PreTransitiveSolver(system,this) : new // StandardSolver(system,this); } }
91,465
35.792438
131
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/ipa/callgraph/propagation/SelectiveCPAContext.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.ipa.callgraph.propagation; import com.ibm.wala.ipa.callgraph.Context; import com.ibm.wala.ipa.callgraph.ContextItem; import com.ibm.wala.ipa.callgraph.ContextKey; import com.ibm.wala.util.collections.HashMapFactory; import java.util.Map; /** * A selective Cartesian product context that enforces object sensitivity on some set of parameter * positions. */ public class SelectiveCPAContext implements Context { // base context protected final Context base; // maps parameters to their abstract objects private final Map<ContextKey, InstanceKey> parameterObjs; // cached hash code private final int hashCode; // helper method for constructing the parameterObjs map private static Map<ContextKey, InstanceKey> makeMap(InstanceKey[] x) { Map<ContextKey, InstanceKey> result = HashMapFactory.make(); for (int i = 0; i < x.length; i++) { if (x[i] != null) { result.put(ContextKey.PARAMETERS[i], x[i]); } } return result; } public SelectiveCPAContext(Context base, InstanceKey[] x) { this(base, makeMap(x)); } public SelectiveCPAContext(Context base, Map<ContextKey, InstanceKey> parameterObjs) { this.base = base; this.parameterObjs = parameterObjs; hashCode = base.hashCode() ^ parameterObjs.hashCode(); } @Override public String toString() { return "cpa:" + parameterObjs; } @Override public ContextItem get(ContextKey name) { if (parameterObjs.containsKey(name)) { return new FilteredPointerKey.SingleInstanceFilter(parameterObjs.get(name)); } else { return base.get(name); } } @Override public int hashCode() { return hashCode; } @Override public boolean equals(Object other) { if (this == other) { return true; } return other != null && getClass().equals(other.getClass()) && base.equals(((SelectiveCPAContext) other).base) && parameterObjs.equals(((SelectiveCPAContext) other).parameterObjs); } }
2,385
26.744186
98
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/ipa/callgraph/propagation/SmushedAllocationSiteInNode.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.ipa.callgraph.propagation; import com.ibm.wala.classLoader.IClass; import com.ibm.wala.classLoader.NewSiteReference; import com.ibm.wala.ipa.callgraph.CGNode; import com.ibm.wala.ipa.callgraph.CallGraph; import com.ibm.wala.util.collections.FilterIterator; import com.ibm.wala.util.collections.MapIterator; import com.ibm.wala.util.collections.Pair; import java.util.Iterator; /** * An {@link InstanceKey} which represents the set of all allocation sites of a given type in a * {@link CGNode}. An instance key which represents a unique set for ALL allocation sites of a given * type in a CGNode */ public class SmushedAllocationSiteInNode extends AbstractTypeInNode { public SmushedAllocationSiteInNode(CGNode node, IClass type) { super(node, type); } @Override public boolean equals(Object obj) { // instanceof is OK because this class is final if (obj instanceof SmushedAllocationSiteInNode) { SmushedAllocationSiteInNode other = (SmushedAllocationSiteInNode) obj; return getNode().equals(other.getNode()) && getConcreteType().equals(other.getConcreteType()); } else { return false; } } @Override public int hashCode() { return getNode().hashCode() * 8293 + getConcreteType().hashCode(); } @Override public String toString() { return "SMUSHED " + getNode() + " : " + getConcreteType(); } @Override public Iterator<Pair<CGNode, NewSiteReference>> getCreationSites(CallGraph CG) { return new MapIterator<>( new FilterIterator<>( getNode().iterateNewSites(), o -> o.getDeclaredType().equals(getConcreteType().getReference())), object -> Pair.make(getNode(), object)); } }
2,095
32.806452
100
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/ipa/callgraph/propagation/SmushedAllocationSiteInstanceKeys.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.ipa.callgraph.propagation; import com.ibm.wala.classLoader.ArrayClass; import com.ibm.wala.classLoader.IClass; import com.ibm.wala.classLoader.IMethod; import com.ibm.wala.classLoader.NewSiteReference; import com.ibm.wala.classLoader.ProgramCounter; import com.ibm.wala.ipa.callgraph.AnalysisOptions; import com.ibm.wala.ipa.callgraph.CGNode; import com.ibm.wala.ipa.callgraph.propagation.cfa.ContainerContextSelector; import com.ibm.wala.ipa.cha.IClassHierarchy; import com.ibm.wala.types.TypeReference; /** * This class provides instance keys where for a given type T in a CGNode N, there is one "abstract * allocation site" instance for all T allocations in node N. */ public class SmushedAllocationSiteInstanceKeys implements InstanceKeyFactory { /** Governing call graph construction options */ private final AnalysisOptions options; /** Governing class hierarchy */ private final IClassHierarchy cha; private final ClassBasedInstanceKeys classBased; /** @param options Governing call graph construction options */ public SmushedAllocationSiteInstanceKeys(AnalysisOptions options, IClassHierarchy cha) { this.options = options; this.cha = cha; this.classBased = new ClassBasedInstanceKeys(options, cha); } @Override public InstanceKey getInstanceKeyForAllocation(CGNode node, NewSiteReference allocation) { IClass type = options.getClassTargetSelector().getAllocatedTarget(node, allocation); if (type == null) { return null; } // disallow recursion in contexts. if (node.getContext().isA(ReceiverInstanceContext.class)) { IMethod m = node.getMethod(); CGNode n = ContainerContextSelector.findNodeRecursiveMatchingContext(m, node.getContext()); if (n != null) { return new SmushedAllocationSiteInNode(n, type); } } InstanceKey key = new SmushedAllocationSiteInNode(node, type); return key; } @Override public InstanceKey getInstanceKeyForMultiNewArray( CGNode node, NewSiteReference allocation, int dim) { ArrayClass type = (ArrayClass) options.getClassTargetSelector().getAllocatedTarget(node, allocation); if (type == null) { return null; } InstanceKey key = new MultiNewArrayInNode(node, allocation, type, dim); return key; } @Override public <T> InstanceKey getInstanceKeyForConstant(TypeReference type, T S) { if (options.getUseConstantSpecificKeys()) return new ConstantKey<>(S, cha.lookupClass(type)); else return new ConcreteTypeKey(cha.lookupClass(type)); } @Override public InstanceKey getInstanceKeyForPEI(CGNode node, ProgramCounter pei, TypeReference type) { return classBased.getInstanceKeyForPEI(node, pei, type); } @Override public InstanceKey getInstanceKeyForMetadataObject(Object obj, TypeReference objType) { return classBased.getInstanceKeyForMetadataObject(obj, objType); } }
3,300
33.747368
99
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/ipa/callgraph/propagation/StandardSolver.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.ipa.callgraph.propagation; import com.ibm.wala.util.CancelException; import com.ibm.wala.util.MonitorUtil.IProgressMonitor; /** standard fixed-point iterative solver for pointer analysis */ public class StandardSolver extends AbstractPointsToSolver { private static final boolean DEBUG_PHASES = DEBUG || false; public StandardSolver(PropagationSystem system, PropagationCallGraphBuilder builder) { super(system, builder); } @Override public void solve(IProgressMonitor monitor) throws IllegalArgumentException, CancelException { int i = 0; do { i++; if (DEBUG_PHASES) { System.err.println("Iteration " + i); } getSystem().solve(monitor); if (DEBUG_PHASES) { System.err.println("Solved " + i); } if (getBuilder().getOptions().getMaxNumberOfNodes() > -1) { if (getBuilder().getCallGraph().getNumberOfNodes() >= getBuilder().getOptions().getMaxNumberOfNodes()) { if (DEBUG) { System.err.println("Bail out from call graph limit" + i); } throw CancelException.make("reached call graph size limit"); } } // Add constraints until there are no new discovered nodes if (DEBUG_PHASES) { System.err.println("adding constraints"); } getBuilder().addConstraintsFromNewNodes(monitor); // getBuilder().callGraph.summarizeByPackage(); if (DEBUG_PHASES) { System.err.println("handling reflection"); } if (i <= getBuilder().getOptions().getReflectionOptions().getNumFlowToCastIterations()) { getReflectionHandler().updateForReflection(monitor); } // Handling reflection may have discovered new nodes! if (DEBUG_PHASES) { System.err.println("adding constraints again"); } getBuilder().addConstraintsFromNewNodes(monitor); if (monitor != null) { monitor.worked(i); } // Note that we may have added stuff to the // worklist; so, } while (!getSystem().emptyWorkList()); } }
2,463
31
96
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/ipa/callgraph/propagation/StaticFieldKey.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.ipa.callgraph.propagation; import com.ibm.wala.classLoader.IField; /** An pointer key which represents a unique set for each static field. */ public final class StaticFieldKey extends AbstractPointerKey { private final IField field; public StaticFieldKey(IField field) { if (field == null) { throw new IllegalArgumentException("null field"); } this.field = field; } @Override public boolean equals(Object obj) { // instanceof is OK because this class is final if (obj instanceof StaticFieldKey) { StaticFieldKey other = (StaticFieldKey) obj; return field.equals(other.field); } else { return false; } } @Override public int hashCode() { return 1889 * field.hashCode(); } @Override public String toString() { return "[" + field + ']'; } public IField getField() { return field; } }
1,276
24.039216
74
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/ipa/callgraph/propagation/StringConstantCharArray.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 com.ibm.wala.ipa.callgraph.propagation; import com.ibm.wala.classLoader.IClass; import com.ibm.wala.classLoader.NewSiteReference; import com.ibm.wala.ipa.callgraph.CGNode; import com.ibm.wala.ipa.callgraph.CallGraph; import com.ibm.wala.types.TypeReference; import com.ibm.wala.util.collections.EmptyIterator; import com.ibm.wala.util.collections.Pair; import java.util.Iterator; /** * An {@link InstanceKey} which represents the constant char[] contents of a string constant object. */ public class StringConstantCharArray implements InstanceKey { private final ConstantKey<String> constant; private StringConstantCharArray(ConstantKey<String> constant) { this.constant = constant; } public static StringConstantCharArray make(ConstantKey<String> constant) { if (constant == null) { throw new IllegalArgumentException("null constant"); } return new StringConstantCharArray(constant); } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((constant == null) ? 0 : constant.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; final StringConstantCharArray other = (StringConstantCharArray) obj; if (constant == null) { if (other.constant != null) return false; } else if (!constant.equals(other.constant)) return false; return true; } @Override public IClass getConcreteType() { return constant.getConcreteType().getClassHierarchy().lookupClass(TypeReference.CharArray); } @Override public String toString() { return "StringConstantCharArray:" + constant; } @Override public Iterator<Pair<CGNode, NewSiteReference>> getCreationSites(CallGraph CG) { return EmptyIterator.instance(); } }
2,277
29.373333
100
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/ipa/callgraph/propagation/TargetMethodContextSelector.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.ipa.callgraph.propagation; import com.ibm.wala.classLoader.CallSiteReference; import com.ibm.wala.classLoader.IMethod; import com.ibm.wala.ipa.callgraph.CGNode; import com.ibm.wala.ipa.callgraph.Context; import com.ibm.wala.ipa.callgraph.ContextItem; import com.ibm.wala.ipa.callgraph.ContextKey; import com.ibm.wala.ipa.callgraph.ContextSelector; import com.ibm.wala.types.Selector; import com.ibm.wala.util.intset.IntSet; import com.ibm.wala.util.intset.IntSetUtil; /** * This context selector selects a context based on whether the receiver type dispatches to a given * method. */ public class TargetMethodContextSelector implements ContextSelector { private final Selector selector; public TargetMethodContextSelector(Selector selector) { this.selector = selector; } @Override public Context getCalleeTarget( CGNode caller, CallSiteReference site, IMethod callee, InstanceKey[] R) { if (R == null || R[0] == null) { throw new IllegalArgumentException("R is null"); } final IMethod M = R[0].getConcreteType().getMethod(selector); class MethodDispatchContext implements Context { @Override public ContextItem get(ContextKey name) { if (name.equals(ContextKey.PARAMETERS[0])) { return new FilteredPointerKey.TargetMethodFilter(M); } else if (name.equals(ContextKey.TARGET)) { return M; } else { return null; } } @Override public String toString() { return "DispatchContext: " + M; } @Override public int hashCode() { return M.hashCode(); } @Override public boolean equals(Object o) { return (o instanceof Context) && ((Context) o).isA(MethodDispatchContext.class) && ((Context) o).get(ContextKey.TARGET).equals(M); } } return new MethodDispatchContext(); } private static final IntSet thisParameter = IntSetUtil.make(new int[] {0}); @Override public IntSet getRelevantParameters(CGNode caller, CallSiteReference site) { return thisParameter; } }
2,506
28.151163
99
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/ipa/callgraph/propagation/UnarySideEffect.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.ipa.callgraph.propagation; import com.ibm.wala.fixpoint.UnaryOperator; /** * A SideEffect is a constraint which carries a points-to-set which is def'fed or used in created * constraints. * * <p>The side effect doesn't actually def or use the fixedSet itself ... rather, the side effect * creates <em>new</em> constraints that def or use the fixed set. * * <p>A "load" operator generates defs of the fixed set. A "store" operator generates uses of the * fixed set. */ public abstract class UnarySideEffect extends UnaryOperator<PointsToSetVariable> { private PointsToSetVariable fixedSet; public UnarySideEffect(PointsToSetVariable fixedSet) { this.fixedSet = fixedSet; } @Override public final byte evaluate(PointsToSetVariable lhs, PointsToSetVariable rhs) { return evaluate(rhs); } public abstract byte evaluate(PointsToSetVariable rhs); /** @return Returns the fixed points-to-set associated with this side effect. */ PointsToSetVariable getFixedSet() { return fixedSet; } @Override public boolean equals(Object o) { if (o == null) { return false; } if (getClass().equals(o.getClass())) { UnarySideEffect other = (UnarySideEffect) o; return fixedSet.equals(other.fixedSet); } else { return false; } } @Override public int hashCode() { return 8059 * fixedSet.hashCode(); } /** * A "load" operator generates defs of the fixed set. A "store" operator generates uses of the * fixed set. */ protected abstract boolean isLoadOperator(); /** Update the fixed points-to-set associated with this side effect. */ public void replaceFixedSet(PointsToSetVariable p) { fixedSet = p; } }
2,107
27.876712
97
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/ipa/callgraph/propagation/ZeroLengthArrayInNode.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 com.ibm.wala.ipa.callgraph.propagation; import com.ibm.wala.classLoader.IClass; import com.ibm.wala.classLoader.NewSiteReference; import com.ibm.wala.ipa.callgraph.CGNode; /** * Represents an array with length zero. Useful for precision since such arrays cannot have * contents. */ public final class ZeroLengthArrayInNode extends AllocationSiteInNode { public ZeroLengthArrayInNode(CGNode node, NewSiteReference allocation, IClass type) { super(node, allocation, type); } @Override public boolean equals(Object obj) { // instanceof is OK because this class is final if (obj instanceof ZeroLengthArrayInNode) { AllocationSiteInNode other = (AllocationSiteInNode) obj; return getNode().equals(other.getNode()) && getSite().equals(other.getSite()); } else { return false; } } @Override public int hashCode() { return getNode().hashCode() * 8647 + getSite().hashCode(); } }
1,313
29.55814
91
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/ipa/callgraph/propagation/cfa/AllocationString.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.ipa.callgraph.propagation.cfa; import com.ibm.wala.ipa.callgraph.ContextItem; import com.ibm.wala.ipa.callgraph.propagation.AllocationSite; import java.util.Arrays; /** * This is a {@link ContextItem} that records n allocation sites, the 0th element represents the * most recently used receiver obj, which is an {@code AllocationSiteInNode} */ public class AllocationString implements ContextItem { private final AllocationSite[] allocationSites; public AllocationString(AllocationSite allocationSite) { if (allocationSite == null) { throw new IllegalArgumentException("null allocationSite"); } allocationSites = new AllocationSite[] {allocationSite}; } public AllocationString(AllocationSite[] allocationSites) { if (allocationSites == null) { throw new IllegalArgumentException("null allocationSites"); } this.allocationSites = allocationSites; } public AllocationSite[] getAllocationSites() { return allocationSites; } public int getLength() { return allocationSites.length; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (!(o instanceof AllocationString)) { return false; } AllocationString that = (AllocationString) o; return Arrays.equals(getAllocationSites(), that.getAllocationSites()); } @Override public int hashCode() { return Arrays.hashCode(getAllocationSites()); } @Override public String toString() { return "AllocationString{" + "allocationSites=" + Arrays.toString(allocationSites) + '}'; } }
1,977
27.666667
96
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/ipa/callgraph/propagation/cfa/AllocationStringContext.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.ipa.callgraph.propagation.cfa; import com.ibm.wala.ipa.callgraph.Context; import com.ibm.wala.ipa.callgraph.ContextItem; import com.ibm.wala.ipa.callgraph.ContextKey; import java.util.Objects; /** This {@link Context} consists of an {@link AllocationString} that records n allocation sites */ public class AllocationStringContext implements Context { private final AllocationString allocationString; public AllocationStringContext(AllocationString allocationString) { this.allocationString = allocationString; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (!(o instanceof AllocationStringContext)) { return false; } AllocationStringContext that = (AllocationStringContext) o; return allocationString.equals(that.allocationString); } @Override public int hashCode() { return Objects.hash(allocationString); } @Override public ContextItem get(ContextKey name) { if (name == nObjContextSelector.ALLOCATION_STRING_KEY) { return allocationString; } return null; } @Override public String toString() { return "AllocationStringContext{" + "allocationString=" + allocationString + '}'; } }
1,617
27.385965
99
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/ipa/callgraph/propagation/cfa/CallString.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 com.ibm.wala.ipa.callgraph.propagation.cfa; import com.ibm.wala.classLoader.CallSiteReference; import com.ibm.wala.classLoader.IMethod; import com.ibm.wala.ipa.callgraph.ContextItem; public class CallString implements ContextItem { private final CallSiteReference sites[]; private final IMethod methods[]; public CallString(CallSiteReference site, IMethod method) { if (site == null) { throw new IllegalArgumentException("null site"); } this.sites = new CallSiteReference[] {site}; this.methods = new IMethod[] {method}; } protected CallString(CallSiteReference site, IMethod method, int length, CallString base) { int sitesLength = Math.min(length, base.sites.length + 1); int methodsLength = Math.min(length, base.methods.length + 1); sites = new CallSiteReference[sitesLength]; sites[0] = site; System.arraycopy(base.sites, 0, sites, 1, Math.min(length - 1, base.sites.length)); methods = new IMethod[methodsLength]; methods[0] = method; System.arraycopy(base.methods, 0, methods, 1, Math.min(length - 1, base.methods.length)); } @Override public String toString() { StringBuilder str = new StringBuilder("["); for (int i = 0; i < sites.length; i++) { str.append(' ') .append(methods[i].getSignature()) .append('@') .append(sites[i].getProgramCounter()); } str.append(" ]"); return str.toString(); } @Override public int hashCode() { int code = 1; for (int i = 0; i < sites.length; i++) { code *= sites[i].hashCode() * methods[i].hashCode(); } return code; } @Override public boolean equals(Object o) { if (o instanceof CallString) { CallString oc = (CallString) o; if (oc.sites.length == sites.length) { for (int i = 0; i < sites.length; i++) { if (!(sites[i].equals(oc.sites[i]) && methods[i].equals(oc.methods[i]))) { return false; } } return true; } } return false; } public CallSiteReference[] getCallSiteRefs() { return this.sites; } public IMethod[] getMethods() { return this.methods; } }
2,553
27.377778
93
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/ipa/callgraph/propagation/cfa/CallStringContext.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 com.ibm.wala.ipa.callgraph.propagation.cfa; import com.ibm.wala.ipa.callgraph.Context; import com.ibm.wala.ipa.callgraph.ContextItem; import com.ibm.wala.ipa.callgraph.ContextKey; public class CallStringContext implements Context { private final CallString cs; public CallStringContext(CallString cs) { if (cs == null) { throw new IllegalArgumentException("null cs"); } this.cs = cs; } @Override public boolean equals(Object o) { return (o instanceof Context) && ((Context) o).isA(CallStringContext.class) && ((Context) o).get(CallStringContextSelector.CALL_STRING).equals(cs); } @Override public int hashCode() { return cs.hashCode(); } @Override public String toString() { return "CallStringContext: " + cs; } @Override public ContextItem get(ContextKey name) { if (CallStringContextSelector.CALL_STRING.equals(name)) { return cs; } else { return null; } } }
1,344
24.377358
79
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/ipa/callgraph/propagation/cfa/CallStringContextSelector.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.ipa.callgraph.propagation.cfa; import com.ibm.wala.classLoader.CallSiteReference; import com.ibm.wala.classLoader.IMethod; import com.ibm.wala.ipa.callgraph.CGNode; import com.ibm.wala.ipa.callgraph.Context; import com.ibm.wala.ipa.callgraph.ContextItem; import com.ibm.wala.ipa.callgraph.ContextKey; import com.ibm.wala.ipa.callgraph.ContextSelector; import com.ibm.wala.ipa.callgraph.impl.Everywhere; import com.ibm.wala.ipa.callgraph.propagation.InstanceKey; import com.ibm.wala.util.intset.IntSet; public abstract class CallStringContextSelector implements ContextSelector { public static final ContextKey CALL_STRING = new ContextKey() { @Override public String toString() { return "CALL_STRING_KEY"; } }; public static final ContextKey BASE = new ContextKey() { @Override public String toString() { return "BASE_KEY"; } }; public static class CallStringContextPair implements Context { private final CallString cs; private final Context base; public CallStringContextPair(CallString cs, Context base) { this.cs = cs; this.base = base; } @Override public boolean equals(Object o) { return o instanceof Context && ((Context) o).isA(CallStringContextPair.class) && ((Context) o).get(CALL_STRING).equals(cs) && ((Context) o).get(BASE).equals(base); } @Override public String toString() { return "CallStringContextPair: " + cs.toString() + ':' + base.toString(); } @Override public int hashCode() { return cs.hashCode() * base.hashCode(); } @Override public ContextItem get(ContextKey name) { if (CALL_STRING.equals(name)) { return cs; } else if (BASE.equals(name)) { return base; } else { return base.get(name); } } public Context getBaseContext() { return base; } public CallString getCallString() { return cs; } @Override public boolean isA(Class<? extends Context> type) { return base.isA(type) || type.isInstance(this); } } protected final ContextSelector base; public CallStringContextSelector(ContextSelector base) { this.base = base; } protected abstract int getLength(CGNode caller, CallSiteReference site, IMethod target); protected CallString getCallString(CGNode caller, CallSiteReference site, IMethod target) { int length = getLength(caller, site, target); if (length > 0) { if (caller.getContext().get(CALL_STRING) != null) { return new CallString( site, caller.getMethod(), length, (CallString) caller.getContext().get(CALL_STRING)); } else { return new CallString(site, caller.getMethod()); } } else { return null; } } @Override public Context getCalleeTarget( CGNode caller, CallSiteReference site, IMethod callee, InstanceKey[] receiver) { Context baseContext = base.getCalleeTarget(caller, site, callee, receiver); CallString cs = getCallString(caller, site, callee); if (cs == null) { return baseContext; } else if (baseContext == Everywhere.EVERYWHERE) { return new CallStringContext(cs); } else { return new CallStringContextPair(cs, baseContext); } } @Override public IntSet getRelevantParameters(CGNode caller, CallSiteReference site) { return base.getRelevantParameters(caller, site); } }
3,898
27.669118
97
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/ipa/callgraph/propagation/cfa/CallerContext.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.ipa.callgraph.propagation.cfa; import com.ibm.wala.ipa.callgraph.CGNode; import com.ibm.wala.ipa.callgraph.Context; import com.ibm.wala.ipa.callgraph.ContextItem; import com.ibm.wala.ipa.callgraph.ContextKey; /** This is a context which is defined by the caller node. */ public class CallerContext implements Context { private final CGNode caller; /** @param caller the node which defines this context. */ public CallerContext(CGNode caller) { if (caller == null) { throw new IllegalArgumentException("null caller"); } this.caller = caller; } @Override public ContextItem get(ContextKey name) { if (name == null) { throw new IllegalArgumentException("name is null"); } if (name.equals(ContextKey.CALLER)) { return caller; } else { return null; } } @Override public boolean equals(Object obj) { if (obj == null) { return false; } if (getClass().equals(obj.getClass())) { CallerContext other = (CallerContext) obj; return caller.equals(other.caller); } else { return false; } } @Override public int hashCode() { return 7841 * caller.hashCode(); } @Override public String toString() { return "Caller: " + caller; } public CGNode getCaller() { return caller; } }
1,712
23.471429
72
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/ipa/callgraph/propagation/cfa/CallerContextPair.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.ipa.callgraph.propagation.cfa; import com.ibm.wala.ipa.callgraph.CGNode; import com.ibm.wala.ipa.callgraph.Context; import com.ibm.wala.ipa.callgraph.ContextItem; import com.ibm.wala.ipa.callgraph.ContextKey; /** * This is a {@link Context} which is defined by a pair consisting of &lt;caller node, base * context&gt;. * * <p>The base context is typically some special case; e.g., a JavaTypeContext used for reflection. */ public class CallerContextPair extends CallerContext { private final Context baseContext; /** @param caller the node which defines this context. */ public CallerContextPair(CGNode caller, Context baseContext) { super(caller); this.baseContext = baseContext; // avoid recursive contexts for now. assert !(baseContext instanceof CallerContextPair); } @Override public ContextItem get(ContextKey name) { if (name == null) { throw new IllegalArgumentException("name is null"); } if (name.equals(ContextKey.CALLER)) { return super.get(name); } else { return baseContext.get(name); } } @Override public boolean equals(Object obj) { if (obj == null) { return false; } if (getClass().equals(obj.getClass())) { CallerContextPair other = (CallerContextPair) obj; return getCaller().equals(other.getCaller()) && baseContext.equals(other.baseContext); } else { return false; } } @Override public int hashCode() { return 8377 * getCaller().hashCode() + baseContext.hashCode(); } @Override public String toString() { return "Caller: " + getCaller() + ",Base:" + baseContext; } }
2,036
27.291667
99
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/ipa/callgraph/propagation/cfa/CallerSiteContext.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.ipa.callgraph.propagation.cfa; import com.ibm.wala.classLoader.CallSiteReference; import com.ibm.wala.ipa.callgraph.CGNode; import com.ibm.wala.ipa.callgraph.ContextItem; import com.ibm.wala.ipa.callgraph.ContextKey; /** A context which is a &lt;CGNode, CallSiteReference&gt; pair. */ public class CallerSiteContext extends CallerContext { private final CallSiteReference callSite; public CallerSiteContext(CGNode caller, CallSiteReference callSite) { super(caller); this.callSite = callSite; } @Override public ContextItem get(ContextKey name) { if (name.equals(ContextKey.CALLSITE)) { return callSite; } else { return super.get(name); } } @Override public boolean equals(Object obj) { if (obj != null && getClass().equals(obj.getClass())) { CallerSiteContext other = (CallerSiteContext) obj; return getCaller().equals(other.getCaller()) && callSite.equals(other.callSite); } else { return false; } } @Override public int hashCode() { return callSite.hashCode() * 19 + super.hashCode(); } @Override public String toString() { return super.toString() + '@' + callSite.getProgramCounter(); } public CallSiteReference getCallSite() { return callSite; } }
1,666
26.327869
86
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/ipa/callgraph/propagation/cfa/CallerSiteContextPair.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.ipa.callgraph.propagation.cfa; import com.ibm.wala.classLoader.CallSiteReference; import com.ibm.wala.ipa.callgraph.CGNode; import com.ibm.wala.ipa.callgraph.Context; import com.ibm.wala.ipa.callgraph.ContextItem; import com.ibm.wala.ipa.callgraph.ContextKey; /** * This is a context which is defined by a pair consisting of &lt;caller node, base context&gt;. * * <p>The base context is typically some special case; e.g., a JavaTypeContext used for reflection. */ public class CallerSiteContextPair extends CallerSiteContext { private final Context baseContext; /** @param caller the node which defines this context. */ public CallerSiteContextPair(CGNode caller, CallSiteReference callSite, Context baseContext) { super(caller, callSite); if (caller == null) { throw new IllegalArgumentException("null caller"); } this.baseContext = baseContext; // avoid recursive contexts for now. assert !(baseContext instanceof CallerContextPair); } @Override public ContextItem get(ContextKey name) { if (name == null) { throw new IllegalArgumentException("name is null"); } if (name.equals(ContextKey.CALLER) || name.equals(ContextKey.CALLSITE)) { return super.get(name); } else { return baseContext.get(name); } } @Override public boolean equals(Object obj) { if (obj == null) { return false; } if (getClass().equals(obj.getClass())) { CallerSiteContextPair other = (CallerSiteContextPair) obj; return getCaller().equals(other.getCaller()) && getCallSite().equals(other.getCallSite()) && baseContext.equals(other.baseContext); } else { return false; } } @Override public int hashCode() { return super.hashCode() + baseContext.hashCode(); } @Override public String toString() { return super.toString() + ",Base:" + baseContext; } }
2,302
29.302632
99
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/ipa/callgraph/propagation/cfa/ContainerContextSelector.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.ipa.callgraph.propagation.cfa; import com.ibm.wala.classLoader.CallSiteReference; import com.ibm.wala.classLoader.IClass; import com.ibm.wala.classLoader.IMethod; import com.ibm.wala.core.util.strings.Atom; import com.ibm.wala.ipa.callgraph.CGNode; import com.ibm.wala.ipa.callgraph.Context; import com.ibm.wala.ipa.callgraph.ContextKey; import com.ibm.wala.ipa.callgraph.ContextSelector; import com.ibm.wala.ipa.callgraph.propagation.AllocationSiteInNode; import com.ibm.wala.ipa.callgraph.propagation.ContainerUtil; import com.ibm.wala.ipa.callgraph.propagation.InstanceKey; import com.ibm.wala.ipa.callgraph.propagation.ReceiverInstanceContext; import com.ibm.wala.ipa.cha.IClassHierarchy; import com.ibm.wala.types.ClassLoaderReference; import com.ibm.wala.types.Descriptor; import com.ibm.wala.types.MethodReference; import com.ibm.wala.types.TypeName; import com.ibm.wala.types.TypeReference; import com.ibm.wala.util.debug.Assertions; import com.ibm.wala.util.intset.EmptyIntSet; import com.ibm.wala.util.intset.IntSet; import com.ibm.wala.util.intset.IntSetUtil; /** * This context selector returns a context customized for the {@link InstanceKey} of the receiver if * * <ul> * <li>receiver is a container, or * <li>was allocated in a node whose context was a {@link ReceiverInstanceContext}, and the type * is interesting according to a delegate {@link ZeroXInstanceKeys} * </ul> * * Additionally, we add one level of call string context to a few well-known static factory methods * from the standard libraries. */ public class ContainerContextSelector implements ContextSelector { private static final boolean DEBUG = false; private static final TypeName SyntheticSystemName = TypeName.string2TypeName("Lcom/ibm/wala/model/java/lang/System"); public static final TypeReference SyntheticSystem = TypeReference.findOrCreate(ClassLoaderReference.Primordial, SyntheticSystemName); public static final TypeReference JavaUtilHashtable = TypeReference.findOrCreate(ClassLoaderReference.Primordial, "Ljava/util/Hashtable"); public static final Atom arraycopyAtom = Atom.findOrCreateUnicodeAtom("arraycopy"); private static final Descriptor arraycopyDesc = Descriptor.findOrCreateUTF8("(Ljava/lang/Object;Ljava/lang/Object;)V"); public static final MethodReference synthArraycopy = MethodReference.findOrCreate(SyntheticSystem, arraycopyAtom, arraycopyDesc); private static final TypeReference Arrays = TypeReference.findOrCreate(ClassLoaderReference.Primordial, "Ljava/util/Arrays"); private static final Atom asList = Atom.findOrCreateUnicodeAtom("asList"); private static final Atom copyOf = Atom.findOrCreateUnicodeAtom("copyOf"); private static final Atom copyOfRange = Atom.findOrCreateUnicodeAtom("copyOfRange"); private static final Atom toString = Atom.findOrCreateUnicodeAtom("toString"); private static final MethodReference StringValueOf = MethodReference.findOrCreate( TypeReference.JavaLangString, "valueOf", "(Ljava/lang/Object;)Ljava/lang/String;"); private static final MethodReference HashtableNewEntry = MethodReference.findOrCreate( JavaUtilHashtable, "newEntry", "(Ljava/lang/Object;Ljava/lang/Object;I)Ljava/util/Hashtable$Entry;"); /** The governing class hierarchy. */ private final IClassHierarchy cha; /** An object that determines object naming policy */ private final ZeroXInstanceKeys delegate; /** * @param cha governing class hierarchy * @param delegate object which determines which classes are "interesting" */ public ContainerContextSelector(IClassHierarchy cha, ZeroXInstanceKeys delegate) { this.cha = cha; this.delegate = delegate; if (delegate == null) { throw new IllegalArgumentException("null delegate"); } } @Override public Context getCalleeTarget( CGNode caller, CallSiteReference site, IMethod callee, InstanceKey[] keys) { if (DEBUG) { System.err.println("ContainerContextSelector: getCalleeTarget " + callee); } InstanceKey receiver = null; if (keys != null && keys.length > 0 && keys[0] != null) { receiver = keys[0]; } if (mayUnderstand(site, callee, receiver)) { if (DEBUG) { System.err.println("May Understand: " + callee + " recv " + receiver); } if (isWellKnownStaticFactory(callee.getReference())) { return new CallerSiteContext(caller, site); } else { if (receiver == null) { Assertions.UNREACHABLE("null receiver for " + site); } return new ReceiverInstanceContext(receiver); } } else { return null; } } /** * Does m represent a static factory method we know about from the standard libraries, that we * usually wish to model with one level of call-string context? */ public static boolean isWellKnownStaticFactory(MethodReference m) { if (isArrayCopyingMethod(m)) { return true; } if (isArrayToStringMethod(m)) { return true; } if (m.equals(StringValueOf)) { return true; } if (m.equals(HashtableNewEntry)) { return true; } return false; } /** Does m represent a library method that copies arrays? */ public static boolean isArrayCopyingMethod(MethodReference m) { if (m == null) { throw new IllegalArgumentException("null m"); } if (m.getDeclaringClass().equals(TypeReference.JavaLangSystem)) { if (m.getName().toString().equals("arraycopy")) { return true; } } if (m.equals(synthArraycopy)) { return true; } if (isArrayCopyMethod(m)) { return true; } return false; } /** * return true iff m represents one of the well-known methods in java.lang.reflect.Arrays that do * some sort of arraycopy */ private static boolean isArrayCopyMethod(MethodReference m) { if (m.getDeclaringClass().equals(Arrays)) { if (m.getName().equals(asList) || m.getName().equals(copyOf) || m.getName().equals(copyOfRange)) { return true; } } return false; } /** * return true iff m represents one of the well-known methods in java.lang.reflect.Arrays that do * toString() on an array */ private static boolean isArrayToStringMethod(MethodReference m) { if (m.getDeclaringClass().equals(Arrays)) { if (m.getName().equals(toString)) { return true; } } return false; } /** * This method walks recursively up the definition of a context C, to see if the chain of contexts * that give rise to C a) includes the method M. or b) includes the method in which the receiver * was allocated * * @return the matching context if found, null otherwise */ public static Context findRecursiveMatchingContext(IMethod M, Context C, InstanceKey receiver) { if (DEBUG) { System.err.println( "findRecursiveMatchingContext for " + M + " in context " + C + " receiver " + receiver); } Context result = findRecursiveMatchingContext(M, C); if (result != null) { return result; } else { if (receiver instanceof AllocationSiteInNode) { AllocationSiteInNode a = (AllocationSiteInNode) receiver; IMethod m = a.getNode().getMethod(); return findRecursiveMatchingContext(m, C); } else { return null; } } } /** * This method walks recursively up the definition of a context C, to see if the chain of contexts * that give rise to C includes the method M. * * <p>If C is a ReceiverInstanceContext, Let N be the node that allocated C.instance. If N.method * == M, return N. Else return findRecursiveMatchingContext(M, N.context) Else return null */ public static CGNode findNodeRecursiveMatchingContext(IMethod m, Context c) { if (DEBUG) { System.err.println("findNodeRecursiveMatchingContext " + m + " in context " + c); } if (c.isA(ReceiverInstanceContext.class)) { InstanceKey receiver = (InstanceKey) c.get(ContextKey.RECEIVER); if (!(receiver instanceof AllocationSiteInNode)) { return null; } AllocationSiteInNode i = (AllocationSiteInNode) receiver; CGNode n = i.getNode(); if (n.getMethod().equals(m)) { return n; } else { return findNodeRecursiveMatchingContext(m, n.getContext()); } } else if (c.isA(CallerContext.class)) { CGNode n = (CGNode) c.get(ContextKey.CALLER); if (n.getMethod().equals(m)) { return n; } else { return findNodeRecursiveMatchingContext(m, n.getContext()); } } else { return null; } } /** * This method walks recursively up the definition of a context C, to see if the chain of contexts * that give rise to C includes the method M. * * <p>If C is a ReceiverInstanceContext, Let N be the node that allocated C.instance. If N.method * == M, return N.context. Else return findRecursiveMatchingContext(M, N.context) Else return null */ public static Context findRecursiveMatchingContext(IMethod M, Context C) { CGNode n = findNodeRecursiveMatchingContext(M, C); return (n == null) ? null : n.getContext(); } public boolean mayUnderstand(CallSiteReference site, IMethod targetMethod, InstanceKey receiver) { if (targetMethod == null) { throw new IllegalArgumentException("targetMethod is null"); } if (isWellKnownStaticFactory(targetMethod.getReference())) { return true; } else { if (site.isStatic()) { return false; } if (receiver == null) { return false; } if (targetMethod.getDeclaringClass().getReference().equals(TypeReference.JavaLangObject)) { // ramp down context: assuming methods on java.lang.Object don't cause pollution // important for containers that invoke reflection return false; } if (isContainer(targetMethod.getDeclaringClass())) { return true; } if (!delegate.isInteresting(receiver.getConcreteType())) { return false; } if (receiver instanceof AllocationSiteInNode) { AllocationSiteInNode I = (AllocationSiteInNode) receiver; CGNode N = I.getNode(); if (N.getContext().isA(ReceiverInstanceContext.class)) { return true; } } return false; } } /** @return true iff C is a container class */ protected boolean isContainer(IClass C) { if (DEBUG) { System.err.println("isContainer? " + C + ' ' + ContainerUtil.isContainer(C)); } return ContainerUtil.isContainer(C); } protected IClassHierarchy getClassHierarchy() { return cha; } private static final IntSet thisParameter = IntSetUtil.make(new int[] {0}); @Override public IntSet getRelevantParameters(CGNode caller, CallSiteReference site) { if (site.isDispatch()) { return thisParameter; } else { return EmptyIntSet.instance; } } }
11,453
33.293413
100
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/ipa/callgraph/propagation/cfa/ContextInsensitiveSSAInterpreter.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.ipa.callgraph.propagation.cfa; import com.ibm.wala.cfg.ControlFlowGraph; import com.ibm.wala.classLoader.IClass; import com.ibm.wala.ipa.callgraph.AnalysisOptions; import com.ibm.wala.ipa.callgraph.CGNode; import com.ibm.wala.ipa.callgraph.IAnalysisCacheView; import com.ibm.wala.ipa.callgraph.impl.Everywhere; import com.ibm.wala.ipa.callgraph.propagation.SSAContextInterpreter; import com.ibm.wala.ipa.callgraph.propagation.rta.ContextInsensitiveRTAInterpreter; import com.ibm.wala.ssa.DefUse; import com.ibm.wala.ssa.IR; import com.ibm.wala.ssa.IRView; import com.ibm.wala.ssa.ISSABasicBlock; import com.ibm.wala.ssa.SSAInstruction; /** Default implementation of SSAContextInterpreter for context-insensitive analysis. */ public class ContextInsensitiveSSAInterpreter extends ContextInsensitiveRTAInterpreter implements SSAContextInterpreter { protected final AnalysisOptions options; public ContextInsensitiveSSAInterpreter(AnalysisOptions options, IAnalysisCacheView cache) { super(cache); this.options = options; } @Override public IR getIR(CGNode node) { if (node == null) { throw new IllegalArgumentException("node is null"); } // Note: since this is context-insensitive, we cache an IR based on the // EVERYWHERE context return getAnalysisCache().getIR(node.getMethod(), Everywhere.EVERYWHERE); } @Override public IRView getIRView(CGNode node) { return getIR(node); } @Override public int getNumberOfStatements(CGNode node) { IR ir = getIR(node); return (ir == null) ? -1 : ir.getInstructions().length; } @Override public boolean recordFactoryType(CGNode node, IClass klass) { return false; } @Override public ControlFlowGraph<SSAInstruction, ISSABasicBlock> getCFG(CGNode N) { IR ir = getIR(N); if (ir == null) { return null; } else { return ir.getControlFlowGraph(); } } @Override public DefUse getDU(CGNode node) { if (node == null) { throw new IllegalArgumentException("node is null"); } // Note: since this is context-insensitive, we cache an IR based on the // EVERYWHERE context return getAnalysisCache() .getDefUse(getAnalysisCache().getIR(node.getMethod(), Everywhere.EVERYWHERE)); } }
2,668
30.4
94
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/ipa/callgraph/propagation/cfa/DefaultPointerKeyFactory.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.ipa.callgraph.propagation.cfa; import com.ibm.wala.classLoader.IField; import com.ibm.wala.ipa.callgraph.CGNode; import com.ibm.wala.ipa.callgraph.propagation.ArrayContentsKey; import com.ibm.wala.ipa.callgraph.propagation.FilteredPointerKey; import com.ibm.wala.ipa.callgraph.propagation.InstanceFieldKey; import com.ibm.wala.ipa.callgraph.propagation.InstanceKey; import com.ibm.wala.ipa.callgraph.propagation.LocalPointerKey; import com.ibm.wala.ipa.callgraph.propagation.LocalPointerKeyWithFilter; import com.ibm.wala.ipa.callgraph.propagation.PointerKey; import com.ibm.wala.ipa.callgraph.propagation.PointerKeyFactory; import com.ibm.wala.ipa.callgraph.propagation.ReturnValueKey; import com.ibm.wala.ipa.callgraph.propagation.StaticFieldKey; /** Default implementation of {@link PointerKeyFactory} */ public class DefaultPointerKeyFactory implements PointerKeyFactory { public DefaultPointerKeyFactory() {} @Override public PointerKey getPointerKeyForLocal(CGNode node, int valueNumber) { if (valueNumber <= 0) { throw new IllegalArgumentException("illegal value number: " + valueNumber + " in " + node); } return new LocalPointerKey(node, valueNumber); } @Override public FilteredPointerKey getFilteredPointerKeyForLocal( CGNode node, int valueNumber, FilteredPointerKey.TypeFilter filter) { if (filter == null) { throw new IllegalArgumentException("null filter"); } assert valueNumber > 0 : "illegal value number: " + valueNumber + " in " + node; // TODO: add type filters! return new LocalPointerKeyWithFilter(node, valueNumber, filter); } @Override public PointerKey getPointerKeyForReturnValue(CGNode node) { return new ReturnValueKey(node); } @Override public PointerKey getPointerKeyForExceptionalReturnValue(CGNode node) { return new ExceptionReturnValueKey(node); } @Override public PointerKey getPointerKeyForStaticField(IField f) { if (f == null) { throw new IllegalArgumentException("null f"); } return new StaticFieldKey(f); } @Override public PointerKey getPointerKeyForInstanceField(InstanceKey I, IField field) { if (field == null) { throw new IllegalArgumentException("field is null"); } IField resolveAgain = I.getConcreteType().getField(field.getName(), field.getFieldTypeReference().getName()); if (resolveAgain != null) { field = resolveAgain; } return new InstanceFieldKey(I, field); } @Override public PointerKey getPointerKeyForArrayContents(InstanceKey I) { return new ArrayContentsKey(I); } }
3,002
33.125
97
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/ipa/callgraph/propagation/cfa/DefaultSSAInterpreter.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.ipa.callgraph.propagation.cfa; import com.ibm.wala.analysis.reflection.CloneInterpreter; import com.ibm.wala.cfg.ControlFlowGraph; import com.ibm.wala.classLoader.CallSiteReference; import com.ibm.wala.classLoader.IClass; import com.ibm.wala.classLoader.NewSiteReference; import com.ibm.wala.ipa.callgraph.AnalysisOptions; import com.ibm.wala.ipa.callgraph.CGNode; import com.ibm.wala.ipa.callgraph.IAnalysisCacheView; import com.ibm.wala.ipa.callgraph.propagation.SSAContextInterpreter; import com.ibm.wala.ipa.callgraph.propagation.rta.DefaultRTAInterpreter; import com.ibm.wala.ssa.DefUse; import com.ibm.wala.ssa.IR; import com.ibm.wala.ssa.IRView; import com.ibm.wala.ssa.ISSABasicBlock; import com.ibm.wala.ssa.SSAInstruction; import java.util.Iterator; /** Basic analysis; context-insensitive except for newInstance and clone */ public class DefaultSSAInterpreter extends DefaultRTAInterpreter implements SSAContextInterpreter { private final CloneInterpreter cloneInterpreter; private final ContextInsensitiveSSAInterpreter defaultInterpreter; public DefaultSSAInterpreter(AnalysisOptions options, IAnalysisCacheView cache) { super(options, cache); cloneInterpreter = new CloneInterpreter(); defaultInterpreter = new ContextInsensitiveSSAInterpreter(options, cache); } private SSAContextInterpreter getCFAInterpreter(CGNode node) { if (cloneInterpreter.understands(node)) { return cloneInterpreter; } else { return defaultInterpreter; } } @Override public IR getIR(CGNode node) { return getCFAInterpreter(node).getIR(node); } @Override public IRView getIRView(CGNode node) { return getIR(node); } @Override public int getNumberOfStatements(CGNode node) { return getCFAInterpreter(node).getNumberOfStatements(node); } @Override public Iterator<NewSiteReference> iterateNewSites(CGNode node) { return getCFAInterpreter(node).iterateNewSites(node); } @Override public Iterator<CallSiteReference> iterateCallSites(CGNode node) { return getCFAInterpreter(node).iterateCallSites(node); } @Override public boolean recordFactoryType(CGNode node, IClass klass) { // do nothing; we don't understand factory methods. return false; } @Override public ControlFlowGraph<SSAInstruction, ISSABasicBlock> getCFG(CGNode N) { return getCFAInterpreter(N).getCFG(N); } @Override public DefUse getDU(CGNode node) { return getCFAInterpreter(node).getDU(node); } }
2,891
30.434783
99
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/ipa/callgraph/propagation/cfa/DelegatingSSAContextInterpreter.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.ipa.callgraph.propagation.cfa; import com.ibm.wala.cfg.ControlFlowGraph; import com.ibm.wala.classLoader.IClass; import com.ibm.wala.ipa.callgraph.CGNode; import com.ibm.wala.ipa.callgraph.propagation.SSAContextInterpreter; import com.ibm.wala.ipa.callgraph.propagation.rta.DelegatingRTAContextInterpreter; import com.ibm.wala.ssa.DefUse; import com.ibm.wala.ssa.IR; import com.ibm.wala.ssa.IRView; import com.ibm.wala.ssa.ISSABasicBlock; import com.ibm.wala.ssa.SSAInstruction; /** An {@link SSAContextInterpreter} that first checks with A, then defaults to B. */ public class DelegatingSSAContextInterpreter extends DelegatingRTAContextInterpreter implements SSAContextInterpreter { private final SSAContextInterpreter A; private final SSAContextInterpreter B; /** neither A nor B should be null. */ public DelegatingSSAContextInterpreter(SSAContextInterpreter A, SSAContextInterpreter B) { super(A, B); this.A = A; this.B = B; if (A == null) { throw new IllegalArgumentException("A cannot be null"); } if (B == null) { throw new IllegalArgumentException("B cannot be null"); } } @Override public IR getIR(CGNode node) { if (A != null) { if (A.understands(node)) { return A.getIR(node); } } assert B.understands(node); return B.getIR(node); } @Override public IRView getIRView(CGNode node) { if (A != null) { if (A.understands(node)) { return A.getIRView(node); } } assert B.understands(node); return B.getIRView(node); } @Override public int getNumberOfStatements(CGNode node) { if (A != null) { if (A.understands(node)) { return A.getNumberOfStatements(node); } } assert B.understands(node); return B.getNumberOfStatements(node); } @Override public boolean understands(CGNode node) { return A.understands(node) || B.understands(node); } @Override public boolean recordFactoryType(CGNode node, IClass klass) { boolean result = false; if (A != null) { result |= A.recordFactoryType(node, klass); } result |= B.recordFactoryType(node, klass); return result; } @Override public ControlFlowGraph<SSAInstruction, ISSABasicBlock> getCFG(CGNode node) { if (A != null) { if (A.understands(node)) { return A.getCFG(node); } } assert B.understands(node); return B.getCFG(node); } @Override public DefUse getDU(CGNode node) { if (A != null) { if (A.understands(node)) { return A.getDU(node); } } assert B.understands(node); return B.getDU(node); } }
3,056
25.582609
92
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/ipa/callgraph/propagation/cfa/ExceptionReturnValueKey.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.ipa.callgraph.propagation.cfa; import com.ibm.wala.ipa.callgraph.CGNode; import com.ibm.wala.ipa.callgraph.propagation.ReturnValueKey; /** A key which represents the return value for a node. */ public final class ExceptionReturnValueKey extends ReturnValueKey { public ExceptionReturnValueKey(CGNode node) { super(node); } @Override public String toString() { return "[Exc-Ret-V:" + getNode() + ']'; } @Override public boolean equals(Object obj) { if (obj == null) { return false; } return (obj.getClass() == ExceptionReturnValueKey.class) && super.internalEquals(obj); } @Override public int hashCode() { return 1201 * super.internalHashCode(); } }
1,103
26.6
90
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/ipa/callgraph/propagation/cfa/FallbackContextInterpreter.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 */ /* * 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 com.ibm.wala.ipa.callgraph.propagation.cfa; import com.ibm.wala.cfg.ControlFlowGraph; import com.ibm.wala.classLoader.CallSiteReference; import com.ibm.wala.classLoader.IClass; import com.ibm.wala.classLoader.NewSiteReference; import com.ibm.wala.classLoader.ShrikeCTMethod; import com.ibm.wala.classLoader.SyntheticMethod; import com.ibm.wala.ipa.callgraph.CGNode; import com.ibm.wala.ipa.callgraph.propagation.SSAContextInterpreter; import com.ibm.wala.ssa.DefUse; import com.ibm.wala.ssa.IR; import com.ibm.wala.ssa.IRView; import com.ibm.wala.ssa.ISSABasicBlock; import com.ibm.wala.ssa.SSAInstruction; import com.ibm.wala.types.FieldReference; import com.ibm.wala.util.collections.EmptyIterator; import java.util.Iterator; /** * This ContextInterpreter can be used when using another WALA frontend than the shrike frontend. * WALA's standard ContextInterpreters, like e.g. DefaultSSAInterpreter delegate to CodeScanner, * which assumes, that the provided methods are instances of shrike classes. When using these * ContextInterpreter with another frontend than shrike, this leads to ClassCastExceptions. This * class can be used to work around this issue. It delegates to a given ContextInterpreter, if the * CGNode's IMethod is a Shrike class. Otherwise, it retrieves the required information from the * CGNode's IR, which should always work. * * @author Martin Mohr &lt;martin.mohr@kit.edu&gt; * <p>This class is provided by the JOANA project (joana.ipd.kit.edu). */ public class FallbackContextInterpreter implements SSAContextInterpreter { private final SSAContextInterpreter shrikeCI; public FallbackContextInterpreter(SSAContextInterpreter shrikeCI) { this.shrikeCI = shrikeCI; } /* (non-Javadoc) * @see com.ibm.wala.ipa.callgraph.propagation.rta.RTAContextInterpreter#iterateNewSites(com.ibm.wala.ipa.callgraph.CGNode) */ @Override public Iterator<NewSiteReference> iterateNewSites(CGNode node) { if (node.getMethod() instanceof SyntheticMethod || node.getMethod() instanceof ShrikeCTMethod) { return shrikeCI.iterateNewSites(node); } else { IRView ir = getIR(node); if (ir == null) { return EmptyIterator.instance(); } else { return ir.iterateNewSites(); } } } /* (non-Javadoc) * @see com.ibm.wala.ipa.callgraph.propagation.rta.RTAContextInterpreter#iterateFieldsRead(com.ibm.wala.ipa.callgraph.CGNode) */ @Override public Iterator<FieldReference> iterateFieldsRead(CGNode node) { return shrikeCI.iterateFieldsRead(node); } /* (non-Javadoc) * @see com.ibm.wala.ipa.callgraph.propagation.rta.RTAContextInterpreter#iterateFieldsWritten(com.ibm.wala.ipa.callgraph.CGNode) */ @Override public Iterator<FieldReference> iterateFieldsWritten(CGNode node) { return shrikeCI.iterateFieldsWritten(node); } /* (non-Javadoc) * @see com.ibm.wala.ipa.callgraph.cha.CHAContextInterpreter#iterateCallSites(com.ibm.wala.ipa.callgraph.CGNode) */ @Override public Iterator<CallSiteReference> iterateCallSites(CGNode node) { if (node.getMethod() instanceof SyntheticMethod || node.getMethod() instanceof ShrikeCTMethod) { return shrikeCI.iterateCallSites(node); } else { IRView ir = getIR(node); if (ir == null) { return EmptyIterator.instance(); } else { return ir.iterateCallSites(); } } } /* (non-Javadoc) * @see com.ibm.wala.ipa.callgraph.propagation.rta.RTAContextInterpreter#recordFactoryType(com.ibm.wala.ipa.callgraph.CGNode, com.ibm.wala.classLoader.IClass) */ @Override public boolean recordFactoryType(CGNode node, IClass klass) { return shrikeCI.recordFactoryType(node, klass); } /* (non-Javadoc) * @see com.ibm.wala.ipa.callgraph.cha.CHAContextInterpreter#understands(com.ibm.wala.ipa.callgraph.CGNode) */ @Override public boolean understands(CGNode node) { return true; } /* (non-Javadoc) * @see com.ibm.wala.ipa.callgraph.propagation.SSAContextInterpreter#getIR(com.ibm.wala.ipa.callgraph.CGNode) */ @Override public IR getIR(CGNode node) { return shrikeCI.getIR(node); } @Override public IRView getIRView(CGNode node) { return getIR(node); } /* (non-Javadoc) * @see com.ibm.wala.ipa.callgraph.propagation.SSAContextInterpreter#getDU(com.ibm.wala.ipa.callgraph.CGNode) */ @Override public DefUse getDU(CGNode node) { return shrikeCI.getDU(node); } /* (non-Javadoc) * @see com.ibm.wala.ipa.callgraph.propagation.SSAContextInterpreter#getNumberOfStatements(com.ibm.wala.ipa.callgraph.CGNode) */ @Override public int getNumberOfStatements(CGNode node) { return shrikeCI.getNumberOfStatements(node); } /* (non-Javadoc) * @see com.ibm.wala.ipa.callgraph.propagation.SSAContextInterpreter#getCFG(com.ibm.wala.ipa.callgraph.CGNode) */ @Override public ControlFlowGraph<SSAInstruction, ISSABasicBlock> getCFG(CGNode n) { return shrikeCI.getCFG(n); } }
5,649
34.093168
160
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/ipa/callgraph/propagation/cfa/OneLevelSiteContextSelector.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.ipa.callgraph.propagation.cfa; import com.ibm.wala.classLoader.CallSiteReference; import com.ibm.wala.classLoader.IMethod; import com.ibm.wala.ipa.callgraph.CGNode; import com.ibm.wala.ipa.callgraph.Context; import com.ibm.wala.ipa.callgraph.ContextSelector; import com.ibm.wala.ipa.callgraph.impl.Everywhere; import com.ibm.wala.ipa.callgraph.propagation.InstanceKey; import com.ibm.wala.util.intset.IntSet; /** This is a context selector that adds one level of calling context to a base context selector. */ public class OneLevelSiteContextSelector implements ContextSelector { private final ContextSelector baseSelector; /** * @param baseSelector a context selector which provides the context to analyze a method in, but * without one level of calling context. */ public OneLevelSiteContextSelector(ContextSelector baseSelector) { if (baseSelector == null) { throw new IllegalArgumentException("null baseSelector"); } this.baseSelector = baseSelector; } @Override public Context getCalleeTarget( CGNode caller, CallSiteReference site, IMethod callee, InstanceKey[] receiver) { Context baseContext = baseSelector.getCalleeTarget(caller, site, callee, receiver); if (baseContext.equals(Everywhere.EVERYWHERE)) { return new CallerSiteContext(caller, site); } else { return new CallerSiteContextPair(caller, site, baseContext); } } @Override public IntSet getRelevantParameters(CGNode caller, CallSiteReference site) { return baseSelector.getRelevantParameters(caller, site); } }
1,970
35.5
100
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/ipa/callgraph/propagation/cfa/ZeroXCFABuilder.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.ipa.callgraph.propagation.cfa; import com.ibm.wala.analysis.reflection.ReflectionContextInterpreter; import com.ibm.wala.classLoader.Language; import com.ibm.wala.ipa.callgraph.AnalysisOptions; import com.ibm.wala.ipa.callgraph.AnalysisScope; import com.ibm.wala.ipa.callgraph.ContextSelector; import com.ibm.wala.ipa.callgraph.IAnalysisCacheView; import com.ibm.wala.ipa.callgraph.impl.DefaultContextSelector; import com.ibm.wala.ipa.callgraph.impl.DelegatingContextSelector; import com.ibm.wala.ipa.callgraph.impl.Util; import com.ibm.wala.ipa.callgraph.propagation.SSAContextInterpreter; import com.ibm.wala.ipa.callgraph.propagation.SSAPropagationCallGraphBuilder; import com.ibm.wala.ipa.cha.IClassHierarchy; /** 0-1-CFA Call graph builder, optimized to not disambiguate instances of "uninteresting" types. */ public class ZeroXCFABuilder extends SSAPropagationCallGraphBuilder { public ZeroXCFABuilder( Language l, IClassHierarchy cha, AnalysisOptions options, IAnalysisCacheView cache, ContextSelector appContextSelector, SSAContextInterpreter appContextInterpreter, int instancePolicy) { super(l.getFakeRootMethod(cha, options, cache), options, cache, new DefaultPointerKeyFactory()); ContextSelector def = new DefaultContextSelector(options, cha); ContextSelector contextSelector = appContextSelector == null ? def : new DelegatingContextSelector(appContextSelector, def); setContextSelector(contextSelector); SSAContextInterpreter c = new DefaultSSAInterpreter(options, cache); c = new DelegatingSSAContextInterpreter( ReflectionContextInterpreter.createReflectionContextInterpreter( cha, options, getAnalysisCache()), c); SSAContextInterpreter contextInterpreter = appContextInterpreter == null ? c : new DelegatingSSAContextInterpreter(appContextInterpreter, c); setContextInterpreter(contextInterpreter); ZeroXInstanceKeys zik = makeInstanceKeys(cha, options, contextInterpreter, instancePolicy); setInstanceKeys(zik); } /** subclasses can override as desired */ protected ZeroXInstanceKeys makeInstanceKeys( IClassHierarchy cha, AnalysisOptions options, SSAContextInterpreter contextInterpreter, int instancePolicy) { ZeroXInstanceKeys zik = new ZeroXInstanceKeys(options, cha, contextInterpreter, instancePolicy); return zik; } /** * @param options options that govern call graph construction * @param cha governing class hierarchy * @param cl classloader that can find WALA resources * @param scope representation of the analysis scope * @param xmlFiles set of Strings that are names of XML files holding bypass logic specifications. * @return a 0-1-Opt-CFA Call Graph Builder. * @throws IllegalArgumentException if options is null * @throws IllegalArgumentException if xmlFiles == null */ public static SSAPropagationCallGraphBuilder make( AnalysisOptions options, IAnalysisCacheView cache, IClassHierarchy cha, ClassLoader cl, AnalysisScope scope, String[] xmlFiles, byte instancePolicy) throws IllegalArgumentException { if (xmlFiles == null) { throw new IllegalArgumentException("xmlFiles == null"); } if (options == null) { throw new IllegalArgumentException("options is null"); } Util.addDefaultSelectors(options, cha); for (String xmlFile : xmlFiles) { Util.addBypassLogic(options, cl, xmlFile, cha); } return new ZeroXCFABuilder(Language.JAVA, cha, options, cache, null, null, instancePolicy); } public static ZeroXCFABuilder make( Language l, IClassHierarchy cha, AnalysisOptions options, IAnalysisCacheView cache, ContextSelector appContextSelector, SSAContextInterpreter appContextInterpreter, int instancePolicy) throws IllegalArgumentException { if (options == null) { throw new IllegalArgumentException("options == null"); } return new ZeroXCFABuilder( l, cha, options, cache, appContextSelector, appContextInterpreter, instancePolicy); } }
4,600
37.024793
100
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/ipa/callgraph/propagation/cfa/ZeroXContainerCFABuilder.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.ipa.callgraph.propagation.cfa; import com.ibm.wala.classLoader.Language; import com.ibm.wala.ipa.callgraph.AnalysisOptions; import com.ibm.wala.ipa.callgraph.ContextSelector; import com.ibm.wala.ipa.callgraph.IAnalysisCacheView; import com.ibm.wala.ipa.callgraph.impl.DelegatingContextSelector; import com.ibm.wala.ipa.callgraph.propagation.SSAContextInterpreter; import com.ibm.wala.ipa.cha.IClassHierarchy; /** * 0-X-CFA Call graph builder which analyzes calls to "container methods" in a context which is * defined by the receiver instance. */ public class ZeroXContainerCFABuilder extends ZeroXCFABuilder { /** * @param cha governing class hierarchy * @param options call graph construction options * @param appContextSelector application-specific logic to choose contexts * @param appContextInterpreter application-specific logic to interpret a method in context * @throws IllegalArgumentException if options is null */ public ZeroXContainerCFABuilder( IClassHierarchy cha, AnalysisOptions options, IAnalysisCacheView cache, ContextSelector appContextSelector, SSAContextInterpreter appContextInterpreter, int instancePolicy) { super( Language.JAVA, cha, options, cache, appContextSelector, appContextInterpreter, instancePolicy); ContextSelector CCS = makeContainerContextSelector(cha, (ZeroXInstanceKeys) getInstanceKeys()); DelegatingContextSelector DCS = new DelegatingContextSelector(CCS, contextSelector); setContextSelector(DCS); } /** * @return an object which creates contexts for call graph nodes based on the container * disambiguation policy */ protected ContextSelector makeContainerContextSelector( IClassHierarchy cha, ZeroXInstanceKeys keys) { return new ContainerContextSelector(cha, keys); } }
2,283
34.138462
99
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/ipa/callgraph/propagation/cfa/ZeroXInstanceKeys.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.ipa.callgraph.propagation.cfa; import com.ibm.wala.classLoader.IClass; import com.ibm.wala.classLoader.IField; import com.ibm.wala.classLoader.NewSiteReference; import com.ibm.wala.classLoader.ProgramCounter; import com.ibm.wala.ipa.callgraph.AnalysisOptions; import com.ibm.wala.ipa.callgraph.CGNode; import com.ibm.wala.ipa.callgraph.propagation.AllocationSiteInNodeFactory; import com.ibm.wala.ipa.callgraph.propagation.ClassBasedInstanceKeys; import com.ibm.wala.ipa.callgraph.propagation.ConstantKey; import com.ibm.wala.ipa.callgraph.propagation.InstanceKey; import com.ibm.wala.ipa.callgraph.propagation.InstanceKeyFactory; import com.ibm.wala.ipa.callgraph.propagation.SmushedAllocationSiteInstanceKeys; import com.ibm.wala.ipa.callgraph.propagation.rta.RTAContextInterpreter; import com.ibm.wala.ipa.cha.IClassHierarchy; import com.ibm.wala.types.ClassLoaderReference; import com.ibm.wala.types.TypeName; import com.ibm.wala.types.TypeReference; import com.ibm.wala.util.collections.HashMapFactory; import com.ibm.wala.util.collections.HashSetFactory; import com.ibm.wala.util.collections.Iterator2Iterable; import java.util.Collections; import java.util.HashSet; import java.util.Map; import java.util.Set; /** * Flexible class to create {@link InstanceKey}s depending on various policies ranging from * class-based (i.e. 0-CFA) to allocation-site-based (0-1-CFA variants). */ public class ZeroXInstanceKeys implements InstanceKeyFactory { private static final TypeName JavaLangStringBufferName = TypeName.string2TypeName("Ljava/lang/StringBuffer"); public static final TypeReference JavaLangStringBuffer = TypeReference.findOrCreate(ClassLoaderReference.Primordial, JavaLangStringBufferName); private static final TypeName JavaLangStringBuilderName = TypeName.string2TypeName("Ljava/lang/StringBuilder"); public static final TypeReference JavaLangStringBuilder = TypeReference.findOrCreate(ClassLoaderReference.Primordial, JavaLangStringBuilderName); private static final TypeName JavaLangAbstractStringBuilderName = TypeName.string2TypeName("Ljava/lang/AbstractStringBuilder"); public static final TypeReference JavaLangAbstractStringBuilder = TypeReference.findOrCreate( ClassLoaderReference.Primordial, JavaLangAbstractStringBuilderName); /** The NONE policy is not allocation-site based */ public static final int NONE = 0; /** * An ALLOCATIONS - based policy distinguishes instances by allocation site. Otherwise, the policy * distinguishes instances by type. */ public static final int ALLOCATIONS = 1; /** * A policy variant where String and StringBuffers are NOT disambiguated according to allocation * site. */ public static final int SMUSH_STRINGS = 2; /** * A policy variant where {@link Throwable} instances are NOT disambiguated according to * allocation site. */ public static final int SMUSH_THROWABLES = 4; /** * A policy variant where if a type T has only primitive instance fields, then instances of type T * are NOT disambiguated by allocation site. */ public static final int SMUSH_PRIMITIVE_HOLDERS = 8; /** * This variant counts the N, number of allocation sites of a particular type T in each method. If * N &gt; SMUSH_LIMIT, then these N allocation sites are NOT distinguished ... instead there is a * single abstract allocation site for &lt;N,T&gt; * * <p>Probably the best choice in many cases. */ public static final int SMUSH_MANY = 16; /** Should we use constant-specific keys? */ public static final int CONSTANT_SPECIFIC = 32; /** When using smushing, how many sites in a node will be kept distinct before smushing? */ private final int SMUSH_LIMIT = 25; /** The policy choice for instance disambiguation */ private final int policy; /** A delegate object to create class-based abstract instances */ private final ClassBasedInstanceKeys classBased; /** A delegate object to create allocation site-based abstract instances */ private final AllocationSiteInNodeFactory siteBased; /** A delegate object to create "abstract allocation site" - based abstract instances */ private final SmushedAllocationSiteInstanceKeys smushed; /** The governing class hierarchy */ private final IClassHierarchy cha; /** An object which interprets nodes in context. */ private final RTAContextInterpreter contextInterpreter; /** a Map from CGNode-&gt;Set&lt;IClass&gt; that should be smushed. */ protected final Map<CGNode, Set<IClass>> smushMap = HashMapFactory.make(); public ZeroXInstanceKeys( AnalysisOptions options, IClassHierarchy cha, RTAContextInterpreter contextInterpreter, int policy) { if (options == null) { throw new IllegalArgumentException("null options"); } this.policy = policy; if (disambiguateConstants()) { // this is an ugly hack. TODO: clean it all up. options.setUseConstantSpecificKeys(true); } classBased = new ClassBasedInstanceKeys(options, cha); siteBased = new AllocationSiteInNodeFactory(options, cha); smushed = new SmushedAllocationSiteInstanceKeys(options, cha); this.cha = cha; this.contextInterpreter = contextInterpreter; } /** @return true iff the policy smushes some allocation sites */ private boolean smushMany() { return (policy & SMUSH_MANY) > 0; } private boolean allocationPolicy() { return (policy & ALLOCATIONS) > 0; } private boolean smushStrings() { return (policy & SMUSH_STRINGS) > 0; } public boolean smushThrowables() { return (policy & SMUSH_THROWABLES) > 0; } private boolean smushPrimHolders() { return (policy & SMUSH_PRIMITIVE_HOLDERS) > 0; } public boolean disambiguateConstants() { return (policy & CONSTANT_SPECIFIC) > 0; } @Override public InstanceKey getInstanceKeyForAllocation(CGNode node, NewSiteReference allocation) { if (allocation == null) { throw new IllegalArgumentException("allocation is null"); } TypeReference t = allocation.getDeclaredType(); IClass C = cha.lookupClass(t); if (C != null && isInteresting(C)) { if (smushMany()) { if (exceedsSmushLimit(C, node)) { return smushed.getInstanceKeyForAllocation(node, allocation); } else { return siteBased.getInstanceKeyForAllocation(node, allocation); } } else { return siteBased.getInstanceKeyForAllocation(node, allocation); } } else { return classBased.getInstanceKeyForAllocation(node, allocation); } } /** * side effect: populates the smush map. * * @return true iff the node contains too many allocation sites of type c */ private boolean exceedsSmushLimit(IClass c, CGNode node) { Set<IClass> s = smushMap.get(node); if (s == null) { Map<IClass, Integer> count = countAllocsByType(node); HashSet<IClass> smushees = HashSetFactory.make(5); for (Map.Entry<IClass, Integer> e : count.entrySet()) { Integer i = e.getValue(); if (i > SMUSH_LIMIT) { smushees.add(e.getKey()); } } s = smushees.isEmpty() ? Collections.<IClass>emptySet() : smushees; smushMap.put(node, s); } return s.contains(c); } /** @return Map: IClass -&gt; Integer, the number of allocation sites for each type. */ private Map<IClass, Integer> countAllocsByType(CGNode node) { Map<IClass, Integer> count = HashMapFactory.make(); for (NewSiteReference n : Iterator2Iterable.make(contextInterpreter.iterateNewSites(node))) { IClass alloc = cha.lookupClass(n.getDeclaredType()); if (alloc != null) { count.merge(alloc, 1, Integer::sum); } } return count; } @Override public InstanceKey getInstanceKeyForMultiNewArray( CGNode node, NewSiteReference allocation, int dim) { if (allocationPolicy()) { return siteBased.getInstanceKeyForMultiNewArray(node, allocation, dim); } else { return classBased.getInstanceKeyForMultiNewArray(node, allocation, dim); } } @Override public <T> InstanceKey getInstanceKeyForConstant(TypeReference type, T S) { if (type == null) { throw new IllegalArgumentException("null type"); } if (disambiguateConstants() || isReflectiveType(type)) { return new ConstantKey<>(S, getClassHierarchy().lookupClass(type)); } else { return classBased.getInstanceKeyForConstant(type, S); } } private static boolean isReflectiveType(TypeReference type) { return type.equals(TypeReference.JavaLangReflectConstructor) || type.equals(TypeReference.JavaLangReflectMethod); } @Override public InstanceKey getInstanceKeyForPEI(CGNode node, ProgramCounter pei, TypeReference type) { return classBased.getInstanceKeyForPEI(node, pei, type); } @Override public InstanceKey getInstanceKeyForMetadataObject(Object obj, TypeReference objType) { return classBased.getInstanceKeyForMetadataObject(obj, objType); } /** A class is "interesting" iff we distinguish instances of the class */ public boolean isInteresting(IClass C) { if (!allocationPolicy()) { return false; } else { if (smushStrings() && isStringish(C)) { return false; } else if (smushThrowables() && (isThrowable(C) || isStackTraceElement(C))) { return false; } else if (smushPrimHolders() && allFieldsArePrimitive(C)) { return false; } return true; } } public static boolean isStringish(IClass C) { if (C == null) { throw new IllegalArgumentException("C is null"); } return C.getReference().equals(TypeReference.JavaLangString) || C.getReference().equals(JavaLangStringBuffer) || C.getReference().equals(JavaLangStringBuilder) || C.getReference().equals(JavaLangAbstractStringBuilder); } public static boolean isThrowable(IClass c) { if (c == null) { throw new IllegalArgumentException("null c"); } return c.getClassHierarchy() .isSubclassOf(c, c.getClassHierarchy().lookupClass(TypeReference.JavaLangThrowable)); } public static boolean isStackTraceElement(IClass c) { if (c == null) { throw new IllegalArgumentException("C is null"); } return c.getReference().equals(TypeReference.JavaLangStackTraceElement); } private boolean allFieldsArePrimitive(IClass c) { if (c.isArrayClass()) { TypeReference t = c.getReference().getArrayElementType(); return t.isPrimitiveType(); } else { if (c.getReference().equals(TypeReference.JavaLangObject)) { return true; } else { for (IField f : c.getDeclaredInstanceFields()) { if (f.getReference().getFieldType().isReferenceType()) { return false; } } return allFieldsArePrimitive(c.getSuperclass()); } } } protected IClassHierarchy getClassHierarchy() { return cha; } public ClassBasedInstanceKeys getClassBasedInstanceKeys() { return classBased; } }
11,505
33.656627
100
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/ipa/callgraph/propagation/cfa/nCFABuilder.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.ipa.callgraph.propagation.cfa; import com.ibm.wala.analysis.reflection.ReflectionContextInterpreter; import com.ibm.wala.classLoader.IMethod; import com.ibm.wala.ipa.callgraph.AnalysisOptions; import com.ibm.wala.ipa.callgraph.ContextSelector; import com.ibm.wala.ipa.callgraph.IAnalysisCacheView; import com.ibm.wala.ipa.callgraph.impl.DefaultContextSelector; import com.ibm.wala.ipa.callgraph.impl.DelegatingContextSelector; import com.ibm.wala.ipa.callgraph.propagation.ClassBasedInstanceKeys; import com.ibm.wala.ipa.callgraph.propagation.SSAContextInterpreter; import com.ibm.wala.ipa.callgraph.propagation.SSAPropagationCallGraphBuilder; /** * nCFA Call graph builder. Note that by default, this builder uses a {@link ClassBasedInstanceKeys} * heap model. */ public class nCFABuilder extends SSAPropagationCallGraphBuilder { public nCFABuilder( int n, IMethod abstractRootMethod, AnalysisOptions options, IAnalysisCacheView cache, ContextSelector appContextSelector, SSAContextInterpreter appContextInterpreter) { super(abstractRootMethod, options, cache, new DefaultPointerKeyFactory()); if (options == null) { throw new IllegalArgumentException("options is null"); } setInstanceKeys(new ClassBasedInstanceKeys(options, cha)); ContextSelector def = new DefaultContextSelector(options, cha); ContextSelector contextSelector = appContextSelector == null ? def : new DelegatingContextSelector(appContextSelector, def); contextSelector = new nCFAContextSelector(n, contextSelector); setContextSelector(contextSelector); SSAContextInterpreter defI = new DefaultSSAInterpreter(options, cache); defI = new DelegatingSSAContextInterpreter( ReflectionContextInterpreter.createReflectionContextInterpreter( cha, options, getAnalysisCache()), defI); SSAContextInterpreter contextInterpreter = appContextInterpreter == null ? defI : new DelegatingSSAContextInterpreter(appContextInterpreter, defI); setContextInterpreter(contextInterpreter); } }
2,530
37.938462
100
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/ipa/callgraph/propagation/cfa/nCFAContextSelector.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.ipa.callgraph.propagation.cfa; import com.ibm.wala.classLoader.CallSiteReference; import com.ibm.wala.classLoader.IMethod; import com.ibm.wala.ipa.callgraph.CGNode; import com.ibm.wala.ipa.callgraph.ContextSelector; public class nCFAContextSelector extends CallStringContextSelector { private final int n; public nCFAContextSelector(int n, ContextSelector base) { super(base); this.n = n; } @Override protected int getLength(CGNode caller, CallSiteReference site, IMethod target) { return n; } }
920
28.709677
82
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/ipa/callgraph/propagation/cfa/nObjBuilder.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.ipa.callgraph.propagation.cfa; import com.ibm.wala.classLoader.Language; import com.ibm.wala.ipa.callgraph.AnalysisOptions; import com.ibm.wala.ipa.callgraph.ContextSelector; import com.ibm.wala.ipa.callgraph.IAnalysisCacheView; import com.ibm.wala.ipa.callgraph.impl.DefaultContextSelector; import com.ibm.wala.ipa.callgraph.impl.DelegatingContextSelector; import com.ibm.wala.ipa.callgraph.propagation.SSAContextInterpreter; import com.ibm.wala.ipa.cha.IClassHierarchy; /** call graph builder based on object sensitivity */ public class nObjBuilder extends ZeroXCFABuilder { public nObjBuilder( int n, IClassHierarchy cha, AnalysisOptions options, IAnalysisCacheView cache, ContextSelector appContextSelector, SSAContextInterpreter appContextInterpreter, int instancePolicy) { super( Language.JAVA, cha, options, cache, appContextSelector, appContextInterpreter, instancePolicy); ContextSelector def = new DefaultContextSelector(options, cha); ContextSelector contextSelector = appContextSelector == null ? def : new DelegatingContextSelector(appContextSelector, def); ContextSelector nObjContextSelector = new nObjContextSelector(n, contextSelector); setContextSelector(nObjContextSelector); } }
1,733
31.716981
98
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/ipa/callgraph/propagation/cfa/nObjContextSelector.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.ipa.callgraph.propagation.cfa; import com.ibm.wala.classLoader.CallSiteReference; import com.ibm.wala.classLoader.IMethod; import com.ibm.wala.ipa.callgraph.CGNode; import com.ibm.wala.ipa.callgraph.Context; import com.ibm.wala.ipa.callgraph.ContextKey; import com.ibm.wala.ipa.callgraph.ContextSelector; import com.ibm.wala.ipa.callgraph.DelegatingContext; import com.ibm.wala.ipa.callgraph.impl.Everywhere; import com.ibm.wala.ipa.callgraph.propagation.AllocationSite; import com.ibm.wala.ipa.callgraph.propagation.AllocationSiteInNode; import com.ibm.wala.ipa.callgraph.propagation.InstanceKey; import com.ibm.wala.util.intset.EmptyIntSet; import com.ibm.wala.util.intset.IntSet; import com.ibm.wala.util.intset.IntSetUtil; /** * k-limited object sensitive context selector * * <ul> * <li>for static method : For a few well-known static factory methods from the standard * libraries, use {@link CallerSiteContext}.Otherwise, directly copy the context of the last * non-static method * <li>for virtual method : The {@link Context} consists of n allocation sites * <li>for an object(fixed at allocation) : The heap context consists of n allocation sites * inherited from {@link CGNode} * </ul> */ public class nObjContextSelector implements ContextSelector { public static final ContextKey ALLOCATION_STRING_KEY = new ContextKey() { @Override public String toString() { return "ALLOCATION_STRING_KEY"; } }; private final int n; private final ContextSelector base; public nObjContextSelector(int n, ContextSelector base) { if (n <= 0) { throw new IllegalArgumentException("n must be a positive number"); } this.n = n; this.base = base; } @Override public Context getCalleeTarget( CGNode caller, CallSiteReference site, IMethod callee, InstanceKey[] actualParameters) { Context calleeContext = Everywhere.EVERYWHERE; InstanceKey receiver = (actualParameters != null && actualParameters.length > 0 && actualParameters[0] != null) ? actualParameters[0] : null; if (site.isStatic()) { calleeContext = getCalleeTargetForStaticCall(caller, site, callee); } else if (receiver instanceof AllocationSiteInNode) { AllocationString allocationString = assemblyReceiverAllocString((AllocationSiteInNode) receiver); calleeContext = new AllocationStringContext(allocationString); } Context baseContext = base.getCalleeTarget(caller, site, callee, actualParameters); return appendBaseContext(calleeContext, baseContext); } private AllocationString assemblyReceiverAllocString(AllocationSiteInNode receiver) { Context receiverHeapContext = receiver.getNode().getContext(); AllocationSite receiverAllocSite = new AllocationSite( receiver.getNode().getMethod(), receiver.getSite(), receiver.getConcreteType()); if (receiverHeapContext.get(ALLOCATION_STRING_KEY) != null) { AllocationString receiverAllocString = (AllocationString) receiverHeapContext.get(ALLOCATION_STRING_KEY); int siteLength = Math.min(n, receiverAllocString.getLength() + 1); AllocationSite[] sites = new AllocationSite[siteLength]; sites[0] = receiverAllocSite; System.arraycopy(receiverAllocString.getAllocationSites(), 0, sites, 1, siteLength - 1); return new AllocationString(sites); } else { return new AllocationString(receiverAllocSite); } } protected Context getCalleeTargetForStaticCall( CGNode caller, CallSiteReference site, IMethod callee) { return ContainerContextSelector.isWellKnownStaticFactory(callee.getReference()) ? new CallerSiteContext(caller, site) : caller.getContext(); } private Context appendBaseContext(Context curr, Context base) { if (curr == Everywhere.EVERYWHERE) { return base; } else { return base == Everywhere.EVERYWHERE ? curr : new DelegatingContext(curr, base); } } private static final IntSet thisParameter = IntSetUtil.make(new int[] {0}); @Override public IntSet getRelevantParameters(CGNode caller, CallSiteReference site) { if (site.isDispatch()) { return thisParameter; } else { return EmptyIntSet.instance; } } }
4,723
35.061069
98
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/ipa/callgraph/propagation/rta/AbstractRTABuilder.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.ipa.callgraph.propagation.rta; import com.ibm.wala.analysis.reflection.ReflectionContextInterpreter; import com.ibm.wala.classLoader.CallSiteReference; import com.ibm.wala.classLoader.IClass; import com.ibm.wala.classLoader.IMethod; import com.ibm.wala.classLoader.Language; import com.ibm.wala.classLoader.NewSiteReference; import com.ibm.wala.fixpoint.UnaryOperator; import com.ibm.wala.ipa.callgraph.AnalysisOptions; import com.ibm.wala.ipa.callgraph.CGNode; import com.ibm.wala.ipa.callgraph.ContextSelector; import com.ibm.wala.ipa.callgraph.IAnalysisCacheView; import com.ibm.wala.ipa.callgraph.impl.DefaultContextSelector; import com.ibm.wala.ipa.callgraph.impl.DelegatingContextSelector; import com.ibm.wala.ipa.callgraph.impl.Everywhere; import com.ibm.wala.ipa.callgraph.impl.ExplicitCallGraph; import com.ibm.wala.ipa.callgraph.impl.FakeRootMethod; import com.ibm.wala.ipa.callgraph.impl.FakeWorldClinitMethod; import com.ibm.wala.ipa.callgraph.propagation.ClassBasedInstanceKeys; import com.ibm.wala.ipa.callgraph.propagation.IPointsToSolver; 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.PointsToSetVariable; import com.ibm.wala.ipa.callgraph.propagation.PropagationCallGraphBuilder; import com.ibm.wala.ipa.callgraph.propagation.PropagationSystem; import com.ibm.wala.ipa.callgraph.propagation.SSAContextInterpreter; import com.ibm.wala.ipa.callgraph.propagation.StandardSolver; import com.ibm.wala.ipa.callgraph.propagation.cfa.DefaultPointerKeyFactory; import com.ibm.wala.ipa.callgraph.propagation.cfa.DefaultSSAInterpreter; import com.ibm.wala.ipa.callgraph.propagation.cfa.DelegatingSSAContextInterpreter; import com.ibm.wala.ipa.cha.IClassHierarchy; import com.ibm.wala.shrike.shrikeBT.IInvokeInstruction; import com.ibm.wala.ssa.SSAAbstractInvokeInstruction; import com.ibm.wala.ssa.SSANewInstruction; import com.ibm.wala.types.ClassLoaderReference; import com.ibm.wala.types.FieldReference; import com.ibm.wala.types.MethodReference; import com.ibm.wala.types.TypeReference; import com.ibm.wala.util.CancelException; import com.ibm.wala.util.MonitorUtil.IProgressMonitor; import com.ibm.wala.util.collections.HashSetFactory; import com.ibm.wala.util.collections.Iterator2Iterable; import java.util.HashSet; import java.util.Set; /** Abstract superclass of various RTA flavors */ public abstract class AbstractRTABuilder extends PropagationCallGraphBuilder { protected static final int DEBUG_LEVEL = 0; protected static final boolean DEBUG = (DEBUG_LEVEL > 0); private static final int VERBOSE_INTERVAL = 10000; private static final int PERIODIC_MAINTAIN_INTERVAL = 10000; /** Should we change calls to clone() to assignments? */ protected final boolean clone2Assign = true; /** set of classes whose clinit are processed */ protected final Set<IClass> clinitProcessed = HashSetFactory.make(); /** set of classes (IClass) discovered to be allocated */ protected final HashSet<IClass> allocatedClasses = HashSetFactory.make(); /** * set of class names that are implicitly pre-allocated Note: for performance reasons make sure * java.lang.Object comes first */ private static final TypeReference[] PRE_ALLOC = { TypeReference.findOrCreate(ClassLoaderReference.Primordial, "Ljava/lang/Object"), TypeReference.findOrCreate(ClassLoaderReference.Primordial, "Ljava/lang/ArithmeticException"), TypeReference.findOrCreate(ClassLoaderReference.Primordial, "Ljava/lang/ArrayStoreException"), TypeReference.findOrCreate(ClassLoaderReference.Primordial, "Ljava/lang/ClassCastException"), TypeReference.findOrCreate( ClassLoaderReference.Primordial, "Ljava/lang/ClassNotFoundException"), TypeReference.findOrCreate( ClassLoaderReference.Primordial, "Ljava/lang/IndexOutOfBoundsException"), TypeReference.findOrCreate( ClassLoaderReference.Primordial, "Ljava/lang/NegativeArraySizeException"), TypeReference.findOrCreate( ClassLoaderReference.Primordial, "Ljava/lang/ExceptionInInitializerError"), TypeReference.findOrCreate(ClassLoaderReference.Primordial, "Ljava/lang/NullPointerException") }; protected AbstractRTABuilder( IClassHierarchy cha, AnalysisOptions options, IAnalysisCacheView cache, ContextSelector appContextSelector, SSAContextInterpreter appContextInterpreter) { super( Language.JAVA.getFakeRootMethod(cha, options, cache), options, cache, new DefaultPointerKeyFactory()); setInstanceKeys(new ClassBasedInstanceKeys(options, cha)); setContextSelector(makeContextSelector(appContextSelector)); setContextInterpreter(makeContextInterpreter(appContextInterpreter)); } protected RTAContextInterpreter getRTAContextInterpreter() { return getContextInterpreter(); } /** * Visit all instructions in a node, and add dataflow constraints induced by each statement * relevat to RTA */ @Override protected boolean addConstraintsFromNode(CGNode node, IProgressMonitor monitor) { if (haveAlreadyVisited(node)) { return false; } else { markAlreadyVisited(node); } if (DEBUG) { System.err.println(("\n\nAdd constraints from node " + node)); } // add all relevant constraints addNewConstraints(node); addCallConstraints(node); addFieldConstraints(node); // conservatively assume something changed. return true; } /** Add a constraint for each allocate */ private void addNewConstraints(CGNode node) { for (NewSiteReference n : Iterator2Iterable.make(getRTAContextInterpreter().iterateNewSites(node))) { visitNew(node, n); } } /** Add a constraint for each invoke */ private void addCallConstraints(CGNode node) { for (CallSiteReference c : Iterator2Iterable.make(getRTAContextInterpreter().iterateCallSites(node))) { visitInvoke(node, c); } } /** Handle accesses to static fields */ private void addFieldConstraints(CGNode node) { for (FieldReference f : Iterator2Iterable.make(getRTAContextInterpreter().iterateFieldsRead(node))) { processFieldAccess(f); } for (FieldReference f : Iterator2Iterable.make(getRTAContextInterpreter().iterateFieldsWritten(node))) { processFieldAccess(f); } } /** * Is s is a getstatic or putstatic, then potentially add the relevant &lt;clinit&gt; to the * newMethod set. */ private void processFieldAccess(FieldReference f) { if (DEBUG) { System.err.println(("processFieldAccess: " + f)); } TypeReference t = f.getDeclaringClass(); IClass klass = getClassHierarchy().lookupClass(t); if (klass == null) { } else { processClassInitializer(klass); } } protected void processClassInitializer(IClass klass) { if (!clinitProcessed.add(klass)) { return; } if (klass.getClassInitializer() != null) { if (DEBUG) { System.err.println(("process class initializer for " + klass)); } // add an invocation from the fake root method to the <clinit> FakeWorldClinitMethod fakeWorldClinitMethod = (FakeWorldClinitMethod) callGraph.getFakeWorldClinitNode().getMethod(); MethodReference m = klass.getClassInitializer().getReference(); CallSiteReference site = CallSiteReference.make(1, m, IInvokeInstruction.Dispatch.STATIC); IMethod targetMethod = options .getMethodTargetSelector() .getCalleeTarget(callGraph.getFakeRootNode(), site, null); if (targetMethod != null) { CGNode target = callGraph.getNode(targetMethod, Everywhere.EVERYWHERE); if (target == null) { SSAAbstractInvokeInstruction s = fakeWorldClinitMethod.addInvocation(null, site); try { target = callGraph.findOrCreateNode(targetMethod, Everywhere.EVERYWHERE); processResolvedCall(callGraph.getFakeWorldClinitNode(), s.getCallSite(), target); } catch (CancelException e) { if (DEBUG) { System.err.println( "Could not add node for class initializer: " + targetMethod.getSignature() + " due to constraints on the maximum number of nodes in the call graph."); return; } } } } } klass = klass.getSuperclass(); if (klass != null && !clinitProcessed.contains(klass)) processClassInitializer(klass); } /** * Add a constraint for a call instruction * * @throws IllegalArgumentException if site is null */ public void visitInvoke(CGNode node, CallSiteReference site) { if (site == null) { throw new IllegalArgumentException("site is null"); } if (DEBUG) { System.err.println(("visitInvoke: " + site)); } // if non-virtual, add callgraph edges directly IInvokeInstruction.IDispatch code = site.getInvocationCode(); if (code == IInvokeInstruction.Dispatch.STATIC) { CGNode n = getTargetForCall(node, site, null, null); if (n != null) { processResolvedCall(node, site, n); // side effect of invoke: may call class initializer processClassInitializer(cha.lookupClass(site.getDeclaredTarget().getDeclaringClass())); } } else { // Add a side effect that will fire when we determine a value // for the receiver. This side effect will create a new node // and new constraints based on the new callee context. // TODO: special case logic for dispatch to "final" - type stuff, where // receiver and context can be determined a priori ... like we currently // do for invokestatic above. PointerKey selector = getKeyForSite(site); if (selector == null) { return; } if (DEBUG) { System.err.println(("Add side effect, dispatch to " + site)); } UnaryOperator<PointsToSetVariable> dispatchOperator = makeDispatchOperator(site, node); system.newSideEffect(dispatchOperator, selector); } } protected abstract UnaryOperator<PointsToSetVariable> makeDispatchOperator( CallSiteReference site, CGNode node); protected abstract PointerKey getKeyForSite(CallSiteReference site); /** * Add constraints for a call site after we have computed a reachable target for the dispatch * * <p>Side effect: add edge to the call graph. */ void processResolvedCall(CGNode caller, CallSiteReference site, CGNode target) { if (DEBUG) { System.err.println(("processResolvedCall: " + caller + " ," + site + " , " + target)); } caller.addTarget(site, target); if (caller.equals(callGraph.getFakeRootNode())) { if (entrypointCallSites.contains(site)) { callGraph.registerEntrypoint(target); } } if (!haveAlreadyVisited(target)) { markDiscovered(target); } } /** * Add a constraint for an allocate * * @throws IllegalArgumentException if newSite is null */ public void visitNew(CGNode node, NewSiteReference newSite) { if (newSite == null) { throw new IllegalArgumentException("newSite is null"); } if (DEBUG) { System.err.println(("visitNew: " + newSite)); } InstanceKey iKey = getInstanceKeyForAllocation(node, newSite); if (iKey == null) { // something went wrong. I hope someone raised a warning. return; } IClass klass = iKey.getConcreteType(); if (DEBUG) { System.err.println(("iKey: " + iKey + ' ' + system.findOrCreateIndexForInstanceKey(iKey))); } if (klass == null) { return; } if (!allocatedClasses.add(klass)) { return; } updateSetsForNewClass(klass, iKey, node, newSite); // side effect of new: may call class initializer processClassInitializer(klass); } /** Perform needed bookkeeping when a new class is discovered. */ protected abstract void updateSetsForNewClass( IClass klass, InstanceKey iKey, CGNode node, NewSiteReference ns); @Override protected void customInit() { super.customInit(); FakeRootMethod m = (FakeRootMethod) getCallGraph().getFakeRootNode().getMethod(); for (TypeReference element : PRE_ALLOC) { SSANewInstruction n = m.addAllocation(element); // visit now to ensure java.lang.Object is visited first visitNew(getCallGraph().getFakeRootNode(), n.getNewSite()); } } /** @return set of IClasses determined to be allocated */ @SuppressWarnings("unchecked") public Set<IClass> getAllocatedTypes() { return (Set<IClass>) allocatedClasses.clone(); } @Override protected IPointsToSolver makeSolver() { return new StandardSolver(system, this); } protected ContextSelector makeContextSelector(ContextSelector appContextSelector) { ContextSelector def = new DefaultContextSelector(options, cha); ContextSelector contextSelector = appContextSelector == null ? def : new DelegatingContextSelector(appContextSelector, def); return contextSelector; } protected SSAContextInterpreter makeContextInterpreter( SSAContextInterpreter appContextInterpreter) { SSAContextInterpreter defI = new DefaultSSAInterpreter(getOptions(), getAnalysisCache()); defI = new DelegatingSSAContextInterpreter( ReflectionContextInterpreter.createReflectionContextInterpreter( cha, getOptions(), getAnalysisCache()), defI); SSAContextInterpreter contextInterpreter = appContextInterpreter == null ? defI : new DelegatingSSAContextInterpreter(appContextInterpreter, defI); return contextInterpreter; } @Override protected boolean unconditionallyAddConstraintsFromNode(CGNode node, IProgressMonitor monitor) { // add all relevant constraints addNewConstraints(node); addCallConstraints(node); addFieldConstraints(node); markAlreadyVisited(node); return true; } @Override protected ExplicitCallGraph createEmptyCallGraph(IMethod fakeRootClass, AnalysisOptions options) { return new DelegatingExplicitCallGraph(fakeRootClass, options, getAnalysisCache()); } @Override protected PropagationSystem makeSystem(AnalysisOptions options) { PropagationSystem result = super.makeSystem(options); result.setVerboseInterval(VERBOSE_INTERVAL); result.setPeriodicMaintainInterval(PERIODIC_MAINTAIN_INTERVAL); return result; } /** @see com.ibm.wala.ipa.callgraph.CallGraphBuilder#getPointerAnalysis() */ @Override public PointerAnalysis<InstanceKey> getPointerAnalysis() { return TypeBasedPointerAnalysis.make(getOptions(), allocatedClasses, getCallGraph()); } }
15,284
35.306413
100
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/ipa/callgraph/propagation/rta/BasicRTABuilder.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.ipa.callgraph.propagation.rta; import com.ibm.wala.analysis.reflection.CloneInterpreter; import com.ibm.wala.classLoader.CallSiteReference; import com.ibm.wala.classLoader.IClass; import com.ibm.wala.classLoader.IMethod; import com.ibm.wala.classLoader.NewSiteReference; import com.ibm.wala.fixpoint.UnaryOperator; import com.ibm.wala.ipa.callgraph.AnalysisOptions; import com.ibm.wala.ipa.callgraph.CGNode; import com.ibm.wala.ipa.callgraph.ContextSelector; import com.ibm.wala.ipa.callgraph.IAnalysisCacheView; import com.ibm.wala.ipa.callgraph.impl.ExplicitCallGraph; import com.ibm.wala.ipa.callgraph.impl.ExplicitCallGraph.ExplicitNode; import com.ibm.wala.ipa.callgraph.propagation.InstanceKey; import com.ibm.wala.ipa.callgraph.propagation.PointerKey; import com.ibm.wala.ipa.callgraph.propagation.PointsToSetVariable; import com.ibm.wala.ipa.callgraph.propagation.SSAContextInterpreter; import com.ibm.wala.ipa.cha.IClassHierarchy; import com.ibm.wala.types.Selector; import com.ibm.wala.util.intset.IntSet; import com.ibm.wala.util.intset.IntSetAction; import com.ibm.wala.util.intset.IntSetUtil; import com.ibm.wala.util.intset.MutableIntSet; /** TODO: refactor to eliminate more redundancy with SSACallGraphBuilder */ public class BasicRTABuilder extends AbstractRTABuilder { public BasicRTABuilder( IClassHierarchy cha, AnalysisOptions options, IAnalysisCacheView cache, ContextSelector contextSelector, SSAContextInterpreter contextInterpreter) { super(cha, options, cache, contextSelector, contextInterpreter); } /** Perform needed bookkeeping when a new class is discovered. */ @Override protected void updateSetsForNewClass( IClass klass, InstanceKey iKey, CGNode node, NewSiteReference n) { // set up the selector map to record each method that class implements registerImplementedMethods(klass, iKey); for (IClass c : klass.getAllImplementedInterfaces()) { registerImplementedMethods(c, iKey); } klass = klass.getSuperclass(); while (klass != null) { registerImplementedMethods(klass, iKey); klass = klass.getSuperclass(); } } /** Record state for each method implemented by iKey. */ private void registerImplementedMethods(IClass declarer, InstanceKey iKey) { if (DEBUG) { System.err.println(("registerImplementedMethods: " + declarer + ' ' + iKey)); } for (IMethod M : declarer.getDeclaredMethods()) { Selector selector = M.getReference().getSelector(); PointerKey sKey = getKeyForSelector(selector); if (DEBUG) { System.err.println(("Add constraint: " + selector + " U= " + iKey.getConcreteType())); } system.newConstraint(sKey, iKey); } } @Override protected PointerKey getKeyForSite(CallSiteReference site) { return new RTASelectorKey(site.getDeclaredTarget().getSelector()); } protected RTASelectorKey getKeyForSelector(Selector selector) { return new RTASelectorKey(selector); } /** * An operator to fire when we discover a potential new callee for a virtual or interface call * site. * * <p>This operator will create a new callee context and constraints if necessary. * * <p>N.B: This implementation assumes that the calling context depends solely on the dataflow * information computed for the receiver. TODO: generalize this to have other forms of context * selection, such as CPA-style algorithms. */ private final class DispatchOperator extends UnaryOperator<PointsToSetVariable> { private final CallSiteReference site; private final ExplicitCallGraph.ExplicitNode caller; DispatchOperator(CallSiteReference site, ExplicitNode caller) { this.site = site; this.caller = caller; } /** The set of classes that have already been processed. */ private final MutableIntSet previousReceivers = IntSetUtil.getDefaultIntSetFactory().make(); @SuppressWarnings("unused") @Override public byte evaluate(PointsToSetVariable lhs, PointsToSetVariable rhs) { PointsToSetVariable receivers = rhs; // compute the set of pointers that were not previously handled IntSet value = receivers.getValue(); if (value == null) { // this constraint was put on the work list, probably by initialization, // even though the right-hand-side is empty. // TODO: be more careful about what goes on the worklist to // avoid this. if (DEBUG) { System.err.println("EVAL dispatch with value null"); } return NOT_CHANGED; } if (DEBUG) { String S = "EVAL dispatch to " + caller + ':' + site; System.err.println(S); if (DEBUG_LEVEL >= 2) { System.err.println(("receivers: " + value)); } } // TODO: cache this!!! IClass recvClass = getClassHierarchy().lookupClass(site.getDeclaredTarget().getDeclaringClass()); if (recvClass == null) { return NOT_CHANGED; } value = filterForClass(value, recvClass); if (DEBUG_LEVEL >= 2) { System.err.println(("filtered value: " + value)); } IntSetAction action = ptr -> { if (DEBUG) { System.err.println((" dispatch to ptr " + ptr)); } InstanceKey iKey = system.getInstanceKey(ptr); CGNode target = getTargetForCall(caller, site, iKey.getConcreteType(), new InstanceKey[] {iKey}); if (target == null) { // This indicates an error; I sure hope getTargetForCall // raised a warning about this! if (DEBUG) { System.err.println(("Warning: null target for call " + site + ' ' + iKey)); } return; } if (clone2Assign) { if (target.getMethod().getReference().equals(CloneInterpreter.CLONE)) { // (mostly) ignore a call to clone: it won't affect the // solution, but we should probably at least have a call // edge caller.addTarget(site, target); return; } } IntSet targets = getCallGraph().getPossibleTargetNumbers(caller, site); if (targets != null && targets.contains(target.getGraphNodeId())) { // do nothing; we've previously discovered and handled this // receiver for this call site. return; } // process the newly discovered target for this call processResolvedCall(caller, site, target); if (!haveAlreadyVisited(target)) { markDiscovered(target); } }; value.foreachExcluding(previousReceivers, action); // update the set of receivers previously considered previousReceivers.copySet(value); return NOT_CHANGED; } @Override public String toString() { return "Dispatch"; } @Override public int hashCode() { return caller.hashCode() + 8707 * site.hashCode(); } @Override public boolean equals(Object o) { if (o instanceof DispatchOperator) { DispatchOperator other = (DispatchOperator) o; return caller.equals(other.caller) && site.equals(other.site); } else { return false; } } } /* * @see * com.ibm.wala.ipa.callgraph.propagation.rta.AbstractRTABuilder#makeDispatchOperator(com.ibm.wala.classLoader.CallSiteReference, * com.ibm.wala.ipa.callgraph.CGNode) */ @Override protected UnaryOperator<PointsToSetVariable> makeDispatchOperator( CallSiteReference site, CGNode node) { return new DispatchOperator(site, (ExplicitNode) node); } }
8,195
34.790393
131
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/ipa/callgraph/propagation/rta/CallSite.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.ipa.callgraph.propagation.rta; import com.ibm.wala.classLoader.CallSiteReference; import com.ibm.wala.ipa.callgraph.CGNode; import com.ibm.wala.types.Selector; import com.ibm.wala.util.collections.Pair; /** A utility class consisting of a pair CallSiteReference x CGNode */ public final class CallSite extends Pair<CallSiteReference, CGNode> { private static final long serialVersionUID = -5277592800329960642L; public CallSite(CallSiteReference site, CGNode node) { super(site, node); if (site == null) { throw new IllegalArgumentException("null site"); } if (node == null) { throw new IllegalArgumentException("null node"); } } public CGNode getNode() { return snd; } public CallSiteReference getSite() { return fst; } /** @return the Selector that identifies this site */ public Selector getSelector() { return getSite().getDeclaredTarget().getSelector(); } }
1,330
27.934783
72
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/ipa/callgraph/propagation/rta/ContextInsensitiveRTAInterpreter.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.ipa.callgraph.propagation.rta; import com.ibm.wala.classLoader.CodeScanner; import com.ibm.wala.classLoader.IClass; import com.ibm.wala.classLoader.NewSiteReference; import com.ibm.wala.ipa.callgraph.CGNode; import com.ibm.wala.ipa.callgraph.IAnalysisCacheView; import com.ibm.wala.ipa.callgraph.cha.ContextInsensitiveCHAContextInterpreter; import com.ibm.wala.ipa.callgraph.propagation.SSAContextInterpreter; import com.ibm.wala.shrike.shrikeCT.InvalidClassFileException; import com.ibm.wala.types.FieldReference; import com.ibm.wala.util.debug.Assertions; import java.util.Iterator; /** Default implementation of MethodContextInterpreter for context-insensitive analysis */ public abstract class ContextInsensitiveRTAInterpreter extends ContextInsensitiveCHAContextInterpreter implements RTAContextInterpreter, SSAContextInterpreter { private final IAnalysisCacheView analysisCache; public ContextInsensitiveRTAInterpreter(IAnalysisCacheView cache) { this.analysisCache = cache; } public IAnalysisCacheView getAnalysisCache() { return analysisCache; } @Override public Iterator<NewSiteReference> iterateNewSites(CGNode node) { if (node == null) { throw new IllegalArgumentException("node is null"); } try { return CodeScanner.getNewSites(node.getMethod()).iterator(); } catch (InvalidClassFileException e) { e.printStackTrace(); Assertions.UNREACHABLE(); return null; } } @Override public Iterator<FieldReference> iterateFieldsRead(CGNode node) { if (node == null) { throw new IllegalArgumentException("node is null"); } try { return CodeScanner.getFieldsRead(node.getMethod()).iterator(); } catch (InvalidClassFileException e) { e.printStackTrace(); Assertions.UNREACHABLE(); return null; } } @Override public Iterator<FieldReference> iterateFieldsWritten(CGNode node) { if (node == null) { throw new IllegalArgumentException("node is null"); } try { return CodeScanner.getFieldsWritten(node.getMethod()).iterator(); } catch (InvalidClassFileException e) { e.printStackTrace(); Assertions.UNREACHABLE(); return null; } } @Override public boolean recordFactoryType(CGNode node, IClass klass) { // not a factory type return false; } }
2,750
29.910112
90
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/ipa/callgraph/propagation/rta/DefaultRTAInterpreter.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.ipa.callgraph.propagation.rta; import com.ibm.wala.classLoader.CallSiteReference; import com.ibm.wala.classLoader.IClass; import com.ibm.wala.classLoader.NewSiteReference; import com.ibm.wala.ipa.callgraph.AnalysisOptions; import com.ibm.wala.ipa.callgraph.CGNode; import com.ibm.wala.ipa.callgraph.IAnalysisCacheView; import com.ibm.wala.ipa.callgraph.impl.FakeRootMethod; import com.ibm.wala.ipa.callgraph.propagation.cfa.ContextInsensitiveSSAInterpreter; import com.ibm.wala.types.FieldReference; import java.util.Iterator; /** Basic analysis; context-insensitive */ public class DefaultRTAInterpreter implements RTAContextInterpreter { private static final boolean DEBUG = false; private final ContextInsensitiveRTAInterpreter defaultInterpreter; /** @param options governing analysis options */ public DefaultRTAInterpreter(AnalysisOptions options, IAnalysisCacheView cache) { defaultInterpreter = new ContextInsensitiveSSAInterpreter(options, cache); } private RTAContextInterpreter getNodeInterpreter(CGNode node) { if (node.getMethod() instanceof FakeRootMethod) { FakeRootMethod f = (FakeRootMethod) node.getMethod(); return f.getInterpreter(); } else { if (DEBUG) { System.err.println(("providing context insensitive interpreter for node " + node)); } return defaultInterpreter; } } @Override public Iterator<NewSiteReference> iterateNewSites(CGNode node) { if (node == null) { throw new IllegalArgumentException("node is null"); } return getNodeInterpreter(node).iterateNewSites(node); } @Override public Iterator<CallSiteReference> iterateCallSites(CGNode node) { if (node == null) { throw new IllegalArgumentException("node is null"); } return getNodeInterpreter(node).iterateCallSites(node); } @Override public Iterator<FieldReference> iterateFieldsRead(CGNode node) { if (node == null) { throw new IllegalArgumentException("node is null"); } return getNodeInterpreter(node).iterateFieldsRead(node); } @Override public Iterator<FieldReference> iterateFieldsWritten(CGNode node) { if (node == null) { throw new IllegalArgumentException("node is null"); } return getNodeInterpreter(node).iterateFieldsWritten(node); } @Override public boolean understands(CGNode node) { return true; } @Override public boolean recordFactoryType(CGNode node, IClass klass) { // not a factory type return false; } }
2,907
30.268817
91
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/ipa/callgraph/propagation/rta/DelegatingExplicitCallGraph.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.ipa.callgraph.propagation.rta; import com.ibm.wala.classLoader.CallSiteReference; import com.ibm.wala.classLoader.IMethod; import com.ibm.wala.ipa.callgraph.AnalysisOptions; import com.ibm.wala.ipa.callgraph.CGNode; import com.ibm.wala.ipa.callgraph.Context; import com.ibm.wala.ipa.callgraph.IAnalysisCacheView; import com.ibm.wala.ipa.callgraph.impl.ExplicitCallGraph; import com.ibm.wala.util.debug.Assertions; import com.ibm.wala.util.intset.BasicNaturalRelation; import com.ibm.wala.util.intset.BitVectorIntSet; import com.ibm.wala.util.intset.IBinaryNaturalRelation; import com.ibm.wala.util.intset.IntIterator; import com.ibm.wala.util.intset.IntSet; import com.ibm.wala.util.intset.MutableSharedBitVectorIntSet; import com.ibm.wala.util.intset.MutableSparseIntSet; import java.util.Set; /** * A call graph implementation where some edges are delegated to other call sites, since they are * guaranteed to be the same. */ public class DelegatingExplicitCallGraph extends ExplicitCallGraph { /** delegateR(x,y) means that for at least one site, node number y delegates to node number x. */ private final IBinaryNaturalRelation delegateR = new BasicNaturalRelation(); public DelegatingExplicitCallGraph( IMethod fakeRootClass, AnalysisOptions options, IAnalysisCacheView cache) { super(fakeRootClass, options, cache); } /** * In this implementation, super.targets is a mapping from call site -&gt; Object, where Object is * a * * <ul> * <li>CGNode if we've discovered exactly one target for the site * <li>or an IntSet of node numbers if we've discovered more than one target for the site. * <li>a CallSite if we're delegating these edges to another node * </ul> */ public class DelegatingCGNode extends ExplicitNode { protected DelegatingCGNode(IMethod method, Context C) { super(method, C); } @Override public MutableSharedBitVectorIntSet getAllTargetNumbers() { MutableSharedBitVectorIntSet result = new MutableSharedBitVectorIntSet(super.getAllTargetNumbers()); for (Object n : targets) { if (n instanceof CallSite) { ExplicitNode delegate = (ExplicitNode) ((CallSite) n).getNode(); IntSet s = DelegatingExplicitCallGraph.this.getPossibleTargetNumbers( delegate, ((CallSite) n).getSite()); if (s != null) { result.addAll(s); } } } return result; } @Override public Set<CGNode> getPossibleTargets(CallSiteReference site) { Object result = targets.get(site.getProgramCounter()); if (result != null && result instanceof CallSite) { CallSite p = (CallSite) result; CGNode n = p.getNode(); CallSiteReference s = p.getSite(); return DelegatingExplicitCallGraph.this.getPossibleTargets(n, s); } else { return super.getPossibleTargets(site); } } @Override public IntSet getPossibleTargetNumbers(CallSiteReference site) { Object t = targets.get(site.getProgramCounter()); if (t != null && t instanceof CallSite) { CallSite p = (CallSite) t; DelegatingCGNode n = (DelegatingCGNode) p.getNode(); CallSiteReference s = p.getSite(); return n.getPossibleTargetNumbers(s); } else { return super.getPossibleTargetNumbers(site); } } private boolean hasTarget(int y) { if (super.getAllTargetNumbers().contains(y)) { return true; } else { for (Object n : targets) { if (n instanceof CallSite) { ExplicitNode delegate = (ExplicitNode) ((CallSite) n).getNode(); IntSet s = DelegatingExplicitCallGraph.this.getPossibleTargetNumbers( delegate, ((CallSite) n).getSite()); if (s != null && s.contains(y)) { return true; } } } } return false; } @Override public int getNumberOfTargets(CallSiteReference site) { Object result = targets.get(site.getProgramCounter()); if (result != null && result instanceof CallSite) { CallSite p = (CallSite) result; CGNode n = p.getNode(); CallSiteReference s = p.getSite(); return DelegatingExplicitCallGraph.this.getNumberOfTargets(n, s); } else { return super.getNumberOfTargets(site); } } public void delegate( CallSiteReference site, CGNode delegateNode, CallSiteReference delegateSite) { CallSite d = new CallSite(delegateSite, delegateNode); targets.set(site.getProgramCounter(), d); int y = getCallGraph().getNumber(this); int x = getCallGraph().getNumber(delegateNode); delegateR.add(x, y); } } @Override protected ExplicitNode makeNode(IMethod method, Context context) { return new DelegatingCGNode(method, context); } private class DelegatingEdgeManager extends ExplicitEdgeManager { @Override public void addEdge(CGNode src, CGNode dst) { // we assume that this is called from ExplicitNode.addTarget(). // so we only have to track the inverse edge. // this structure is pretty fragile .. we only explicitly represent the // edges when NOT delegating. // see getPredNodeNumbers() below which recovers. super.addEdge(src, dst); } @Override public void removeAllIncidentEdges(CGNode node) { Assertions.UNREACHABLE(); } @Override public void removeIncomingEdges(CGNode node) { Assertions.UNREACHABLE(); } @Override public void removeOutgoingEdges(CGNode node) { Assertions.UNREACHABLE(); } @Override public boolean hasEdge(CGNode src, CGNode dst) { if (super.hasEdge(src, dst)) { return true; } else { DelegatingCGNode s = (DelegatingCGNode) src; int y = getNumber(dst); return s.hasTarget(y); } } @Override public int getPredNodeCount(CGNode N) { IntSet s = getPredNodeNumbers(N); return s == null ? 0 : s.size(); } @Override public IntSet getPredNodeNumbers(CGNode node) { IntSet superR = super.getPredNodeNumbers(node); if (superR == null) { return null; } else { MutableSparseIntSet result = MutableSparseIntSet.make(superR); BitVectorIntSet allPossiblePreds = new BitVectorIntSet(superR); for (IntIterator it = superR.intIterator(); it.hasNext(); ) { int x = it.next(); IntSet ySet = delegateR.getRelated(x); if (ySet != null) { allPossiblePreds.addAll(ySet); } } for (IntIterator it = allPossiblePreds.intIterator(); it.hasNext(); ) { int y = it.next(); DelegatingCGNode yNode = (DelegatingCGNode) getNode(y); if (hasEdge(yNode, node)) { result.add(y); } } return result; } } } @Override protected ExplicitEdgeManager makeEdgeManger() { return new DelegatingEdgeManager(); } }
7,509
32.0837
100
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/ipa/callgraph/propagation/rta/DelegatingRTAContextInterpreter.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.ipa.callgraph.propagation.rta; import com.ibm.wala.classLoader.CallSiteReference; import com.ibm.wala.classLoader.IClass; import com.ibm.wala.classLoader.NewSiteReference; import com.ibm.wala.ipa.callgraph.CGNode; import com.ibm.wala.types.FieldReference; import java.util.Iterator; /** A context interpreter that first checks with A, then defaults to B. */ public class DelegatingRTAContextInterpreter implements RTAContextInterpreter { private final RTAContextInterpreter A; private final RTAContextInterpreter B; public DelegatingRTAContextInterpreter(RTAContextInterpreter A, RTAContextInterpreter B) { this.A = A; this.B = B; if (B == null) { throw new IllegalArgumentException("null B"); } } @Override public boolean understands(CGNode node) { if (A != null) { return A.understands(node) || B.understands(node); } else { return B.understands(node); } } @Override public Iterator<NewSiteReference> iterateNewSites(CGNode node) { if (A != null) { if (A.understands(node)) { return A.iterateNewSites(node); } } assert B.understands(node); return B.iterateNewSites(node); } @Override public Iterator<CallSiteReference> iterateCallSites(CGNode node) { if (A != null) { if (A.understands(node)) { return A.iterateCallSites(node); } } assert B.understands(node); return B.iterateCallSites(node); } @Override public Iterator<FieldReference> iterateFieldsRead(CGNode node) { if (A != null) { if (A.understands(node)) { return A.iterateFieldsRead(node); } } assert B.understands(node); return B.iterateFieldsRead(node); } @Override public Iterator<FieldReference> iterateFieldsWritten(CGNode node) { if (A != null) { if (A.understands(node)) { return A.iterateFieldsWritten(node); } } assert B.understands(node); return B.iterateFieldsWritten(node); } @Override public boolean recordFactoryType(CGNode node, IClass klass) { boolean result = false; if (A != null) { result |= A.recordFactoryType(node, klass); } result |= B.recordFactoryType(node, klass); return result; } @Override public String toString() { return getClass().getName() + ": " + A + ", " + B; } }
2,738
25.592233
92
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/ipa/callgraph/propagation/rta/RTAContextInterpreter.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.ipa.callgraph.propagation.rta; import com.ibm.wala.classLoader.IClass; import com.ibm.wala.classLoader.NewSiteReference; import com.ibm.wala.ipa.callgraph.CGNode; import com.ibm.wala.ipa.callgraph.cha.CHAContextInterpreter; import com.ibm.wala.types.FieldReference; import java.util.Iterator; /** This object will analyze a method in a context and return information needed for RTA. */ public interface RTAContextInterpreter extends CHAContextInterpreter { /** * @return an Iterator of the types that may be allocated by a given method in a given context. */ @Override Iterator<NewSiteReference> iterateNewSites(CGNode node); /** @return iterator of FieldReference */ Iterator<FieldReference> iterateFieldsRead(CGNode node); /** @return iterator of FieldReference */ Iterator<FieldReference> iterateFieldsWritten(CGNode node); /** * record that the "factory" method of a node should be interpreted to allocate a particular * class. * * <p>TODO: this is a little ugly, is there a better place to move this? * * @return true iff a NEW type was recorded, false if the type was previously recorded. */ boolean recordFactoryType(CGNode node, IClass klass); }
1,601
34.6
97
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/ipa/callgraph/propagation/rta/RTASelectorKey.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.ipa.callgraph.propagation.rta; import com.ibm.wala.classLoader.IClass; import com.ibm.wala.ipa.callgraph.propagation.PointerKey; import com.ibm.wala.types.Selector; import com.ibm.wala.util.debug.Assertions; import com.ibm.wala.util.debug.UnimplementedError; /** This RTA implementation tracks a single set of Classes for each Selector */ public class RTASelectorKey implements PointerKey { private final Selector selector; RTASelectorKey(Selector selector) { this.selector = selector; } @Override public int hashCode() { return 131 * selector.hashCode(); } @Override public boolean equals(Object arg0) { if (arg0 == null) { return false; } if (arg0.getClass().equals(getClass())) { RTASelectorKey other = (RTASelectorKey) arg0; return selector.equals(other.selector); } else { return false; } } @Override public String toString() { return "RTAKey:" + selector.toString(); } /** @see com.ibm.wala.ipa.callgraph.propagation.FilteredPointerKey#getTypeFilter() */ public IClass getTypeFilter() throws UnimplementedError { Assertions.UNREACHABLE(); return null; } }
1,561
25.931034
87
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/ipa/callgraph/propagation/rta/TypeBasedHeapModel.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.ipa.callgraph.propagation.rta; import com.ibm.wala.analysis.typeInference.TypeAbstraction; import com.ibm.wala.analysis.typeInference.TypeInference; import com.ibm.wala.classLoader.ArrayClass; import com.ibm.wala.classLoader.IClass; import com.ibm.wala.classLoader.IField; import com.ibm.wala.classLoader.NewSiteReference; import com.ibm.wala.classLoader.ProgramCounter; 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.propagation.ClassBasedInstanceKeys; import com.ibm.wala.ipa.callgraph.propagation.ConcreteTypeKey; import com.ibm.wala.ipa.callgraph.propagation.FilteredPointerKey; import com.ibm.wala.ipa.callgraph.propagation.HeapModel; import com.ibm.wala.ipa.callgraph.propagation.InstanceKey; import com.ibm.wala.ipa.callgraph.propagation.PointerKey; import com.ibm.wala.ipa.callgraph.propagation.cfa.DefaultPointerKeyFactory; import com.ibm.wala.ipa.cha.IClassHierarchy; import com.ibm.wala.ssa.IR; import com.ibm.wala.ssa.SymbolTable; import com.ibm.wala.types.TypeReference; import com.ibm.wala.util.collections.*; import com.ibm.wala.util.debug.Assertions; import com.ibm.wala.util.debug.UnimplementedError; import java.util.Collection; import java.util.Collections; import java.util.Iterator; import java.util.Map; /** * A trivial field-based heap model, which only uses the information of which types (classes) are * live. * * <p>Note that this heap model is based on ssa value numbers for locals, since we will build a * pointer flow graph based on this heap model when resolving reflection. * * <p>This is an inefficient prototype. */ public class TypeBasedHeapModel implements HeapModel { private static final boolean DEBUG = false; final DefaultPointerKeyFactory pointerKeys = new DefaultPointerKeyFactory(); private final ClassBasedInstanceKeys iKeyFactory; private final Collection<IClass> klasses; private final CallGraph cg; private final Collection<CGNode> nodesHandled = HashSetFactory.make(); /** * Map: &lt;PointerKey&gt; -&gt; thing, where thing is a FilteredPointerKey or an InstanceKey * representing a constant. * * <p>computed lazily */ private Map<PointerKey, Object> pKeys; /** * @param klasses Collection&lt;IClass&gt; * @throws IllegalArgumentException if cg is null */ public TypeBasedHeapModel(AnalysisOptions options, Collection<IClass> klasses, CallGraph cg) { if (cg == null) { throw new IllegalArgumentException("cg is null"); } iKeyFactory = new ClassBasedInstanceKeys(options, cg.getClassHierarchy()); this.klasses = klasses; this.cg = cg; } private void initAllPKeys() { if (pKeys == null) { pKeys = HashMapFactory.make(); } for (IClass klass : klasses) { pKeys.putAll(computePointerKeys(klass)); } for (CGNode node : cg) { initPKeysForNode(node); } } private void initPKeysForNode(CGNode node) { if (pKeys == null) { pKeys = HashMapFactory.make(); } if (!nodesHandled.contains(node)) { nodesHandled.add(node); pKeys.putAll(computePointerKeys(node)); } } private Map<PointerKey, Object> computePointerKeys(CGNode node) { if (DEBUG) { System.err.println("computePointerKeys " + node); } IR ir = node.getIR(); if (ir == null) { return Collections.emptyMap(); } Map<PointerKey, Object> result = HashMapFactory.make(); SymbolTable s = ir.getSymbolTable(); if (s == null) { return Collections.emptyMap(); } TypeInference ti = TypeInference.make(ir, false); for (int i = 1; i <= s.getMaxValueNumber(); i++) { if (DEBUG) { System.err.print(i); } if (s.isConstant(i)) { if (s.isStringConstant(i)) { TypeReference type = node.getMethod() .getDeclaringClass() .getClassLoader() .getLanguage() .getConstantType(s.getStringValue(i)); result.put( pointerKeys.getPointerKeyForLocal(node, i), getInstanceKeyForConstant(type, s.getConstantValue(i))); } } else { TypeAbstraction t = ti.getType(i); if (DEBUG) { System.err.println(" type " + t); } if (t.getType() != null && t.getType().isReferenceType()) { result.put( pointerKeys.getPointerKeyForLocal(node, i), pointerKeys.getFilteredPointerKeyForLocal( node, i, new FilteredPointerKey.SingleClassFilter(t.getType()))); } } } return result; } private Map<PointerKey, Object> computePointerKeys(IClass klass) { Map<PointerKey, Object> result = HashMapFactory.make(); if (klass.isArrayClass()) { ArrayClass a = (ArrayClass) klass; if (a.getElementClass() != null && a.getElementClass().isReferenceType()) { PointerKey p = pointerKeys.getPointerKeyForArrayContents(new ConcreteTypeKey(a)); result.put(p, p); } } else { for (IField f : klass.getAllFields()) { if (!f.getFieldTypeReference().isPrimitiveType()) { if (f.isStatic()) { PointerKey p = pointerKeys.getPointerKeyForStaticField(f); result.put(p, p); } else { PointerKey p = pointerKeys.getPointerKeyForInstanceField(new ConcreteTypeKey(klass), f); result.put(p, p); } } } } return result; } @Override public Iterator<PointerKey> iteratePointerKeys() { initAllPKeys(); return IteratorUtil.filter(pKeys.values().iterator(), PointerKey.class); } @Override public IClassHierarchy getClassHierarchy() { return iKeyFactory.getClassHierarchy(); } @Override public InstanceKey getInstanceKeyForAllocation(CGNode node, NewSiteReference allocation) throws UnimplementedError { return iKeyFactory.getInstanceKeyForAllocation(node, allocation); } @Override public InstanceKey getInstanceKeyForMultiNewArray( CGNode node, NewSiteReference allocation, int dim) throws UnimplementedError { return iKeyFactory.getInstanceKeyForMultiNewArray(node, allocation, dim); } @Override public InstanceKey getInstanceKeyForConstant(TypeReference type, Object S) { return iKeyFactory.getInstanceKeyForConstant(type, S); } public String getStringConstantForInstanceKey() throws UnimplementedError { Assertions.UNREACHABLE(); return null; } @Override public InstanceKey getInstanceKeyForPEI(CGNode node, ProgramCounter instr, TypeReference type) throws UnimplementedError { Assertions.UNREACHABLE(); return null; } @Override public InstanceKey getInstanceKeyForMetadataObject(Object obj, TypeReference objType) throws UnimplementedError { Assertions.UNREACHABLE(); return null; } /** * Note that this always returns a {@link FilteredPointerKey}, since the {@link * TypeBasedPointerAnalysis} relies on the type filter to compute points to sets. */ @Override public FilteredPointerKey getPointerKeyForLocal(CGNode node, int valueNumber) { initPKeysForNode(node); PointerKey p = pointerKeys.getPointerKeyForLocal(node, valueNumber); Object result = pKeys.get(p); if (result == null) { // a null constant return null; } if (result instanceof FilteredPointerKey) { return (FilteredPointerKey) result; } else { if (result instanceof ConcreteTypeKey) { ConcreteTypeKey c = (ConcreteTypeKey) result; if (c.getConcreteType().getReference().equals(TypeReference.JavaLangString)) { // a string constant; return pointerKeys.getFilteredPointerKeyForLocal( node, valueNumber, new FilteredPointerKey.SingleClassFilter(c.getConcreteType())); } else { Assertions.UNREACHABLE("need to handle " + result.getClass()); return null; } } else { Assertions.UNREACHABLE("need to handle " + result.getClass()); return null; } } } @Override public FilteredPointerKey getFilteredPointerKeyForLocal( CGNode node, int valueNumber, FilteredPointerKey.TypeFilter filter) throws UnimplementedError { Assertions.UNREACHABLE(); return null; } @Override public PointerKey getPointerKeyForReturnValue(CGNode node) { return pointerKeys.getPointerKeyForReturnValue(node); } @Override public PointerKey getPointerKeyForExceptionalReturnValue(CGNode node) { return pointerKeys.getPointerKeyForExceptionalReturnValue(node); } @Override public PointerKey getPointerKeyForStaticField(IField f) { return pointerKeys.getPointerKeyForStaticField(f); } @Override public PointerKey getPointerKeyForInstanceField(InstanceKey I, IField field) { return pointerKeys.getPointerKeyForInstanceField(I, field); } @Override public PointerKey getPointerKeyForArrayContents(InstanceKey I) { return pointerKeys.getPointerKeyForArrayContents(I); } protected ClassBasedInstanceKeys getIKeyFactory() { return iKeyFactory; } }
9,604
31.231544
100
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/ipa/callgraph/propagation/rta/TypeBasedPointerAnalysis.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.ipa.callgraph.propagation.rta; import com.ibm.wala.classLoader.IClass; import com.ibm.wala.ipa.callgraph.AnalysisOptions; import com.ibm.wala.ipa.callgraph.CallGraph; import com.ibm.wala.ipa.callgraph.propagation.AbstractPointerAnalysis; import com.ibm.wala.ipa.callgraph.propagation.ArrayContentsKey; import com.ibm.wala.ipa.callgraph.propagation.ConcreteTypeKey; import com.ibm.wala.ipa.callgraph.propagation.FilteredPointerKey; import com.ibm.wala.ipa.callgraph.propagation.HeapModel; import com.ibm.wala.ipa.callgraph.propagation.InstanceFieldKey; import com.ibm.wala.ipa.callgraph.propagation.InstanceKey; import com.ibm.wala.ipa.callgraph.propagation.LocalPointerKeyWithFilter; import com.ibm.wala.ipa.callgraph.propagation.PointerKey; import com.ibm.wala.ipa.callgraph.propagation.ReturnValueKey; import com.ibm.wala.ipa.callgraph.propagation.StaticFieldKey; import com.ibm.wala.ipa.callgraph.propagation.cfa.ExceptionReturnValueKey; import com.ibm.wala.ipa.cha.IClassHierarchy; import com.ibm.wala.types.TypeReference; import com.ibm.wala.util.collections.HashMapFactory; import com.ibm.wala.util.collections.HashSetFactory; import com.ibm.wala.util.collections.Iterator2Collection; import com.ibm.wala.util.debug.Assertions; import com.ibm.wala.util.intset.BimodalMutableIntSet; import com.ibm.wala.util.intset.MutableMapping; import com.ibm.wala.util.intset.OrdinalSet; import java.util.Collection; import java.util.Map; /** * A trivial field-based pointer analysis solution, which only uses the information of which types * (classes) are live. */ public class TypeBasedPointerAnalysis extends AbstractPointerAnalysis { private final Collection<IClass> klasses; private final TypeBasedHeapModel heapModel; /** Map: IClass -&gt; OrdinalSet */ private final Map<IClass, OrdinalSet<InstanceKey>> pointsTo = HashMapFactory.make(); /** * @param klasses {@code Collection<IClass>} * @throws AssertionError if klasses is null */ private TypeBasedPointerAnalysis( AnalysisOptions options, Collection<IClass> klasses, CallGraph cg) throws AssertionError { super(cg, makeInstanceKeys(klasses)); this.klasses = klasses; heapModel = new TypeBasedHeapModel(options, klasses, cg); } /** @param c {@code Collection<IClass>} */ private static MutableMapping<InstanceKey> makeInstanceKeys(Collection<IClass> c) { if (c == null) { throw new IllegalArgumentException("null c"); } MutableMapping<InstanceKey> result = MutableMapping.make(); for (IClass klass : c) { if (!klass.isAbstract() && !klass.isInterface()) { result.add(new ConcreteTypeKey(klass)); } } return result; } public static TypeBasedPointerAnalysis make( AnalysisOptions options, Collection<IClass> klasses, CallGraph cg) throws AssertionError { return new TypeBasedPointerAnalysis(options, klasses, cg); } @Override public OrdinalSet<InstanceKey> getPointsToSet(PointerKey key) throws IllegalArgumentException { if (key == null) { throw new IllegalArgumentException("key == null"); } IClass type = inferType(key); if (type == null) { return OrdinalSet.empty(); } else { OrdinalSet<InstanceKey> result = pointsTo.get(type); if (result == null) { result = computeOrdinalInstanceSet(type); pointsTo.put(type, result); } return result; } } /** Compute the set of {@link InstanceKey}s which may represent a particular type. */ private OrdinalSet<InstanceKey> computeOrdinalInstanceSet(IClass type) { Collection<IClass> klasses = null; if (type.isInterface()) { klasses = getCallGraph().getClassHierarchy().getImplementors(type.getReference()); } else { Collection<IClass> sc = getCallGraph().getClassHierarchy().computeSubClasses(type.getReference()); klasses = HashSetFactory.make(); for (IClass c : sc) { if (!c.isInterface()) { klasses.add(c); } } } Collection<IClass> c = HashSetFactory.make(); for (IClass klass : klasses) { if (klass.isArrayClass()) { TypeReference elementType = klass.getReference().getArrayElementType(); if (elementType.isPrimitiveType()) { c.add(klass); } else { // just add Object[], since with array typing rules we have no idea // the exact type of array the reference is pointing to c.add( klass .getClassHierarchy() .lookupClass(TypeReference.JavaLangObject.getArrayTypeForElementType())); } } else if (this.klasses.contains(klass)) { c.add(klass); } } OrdinalSet<InstanceKey> result = toOrdinalInstanceKeySet(c); return result; } private OrdinalSet<InstanceKey> toOrdinalInstanceKeySet(Collection<IClass> c) { BimodalMutableIntSet s = new BimodalMutableIntSet(); for (IClass klass : c) { int index = getInstanceKeyMapping().add(new ConcreteTypeKey(klass)); s.add(index); } return new OrdinalSet<>(s, getInstanceKeyMapping()); } private IClass inferType(PointerKey key) { if (key instanceof LocalPointerKeyWithFilter) { LocalPointerKeyWithFilter lpk = (LocalPointerKeyWithFilter) key; FilteredPointerKey.TypeFilter filter = lpk.getTypeFilter(); assert filter instanceof FilteredPointerKey.SingleClassFilter; return ((FilteredPointerKey.SingleClassFilter) filter).getConcreteType(); } else if (key instanceof StaticFieldKey) { StaticFieldKey s = (StaticFieldKey) key; return getCallGraph().getClassHierarchy().lookupClass(s.getField().getFieldTypeReference()); } else if (key instanceof InstanceFieldKey) { InstanceFieldKey i = (InstanceFieldKey) key; return getCallGraph().getClassHierarchy().lookupClass(i.getField().getFieldTypeReference()); } else if (key instanceof ArrayContentsKey) { ArrayContentsKey i = (ArrayContentsKey) key; FilteredPointerKey.TypeFilter filter = i.getTypeFilter(); assert filter instanceof FilteredPointerKey.SingleClassFilter; return ((FilteredPointerKey.SingleClassFilter) filter).getConcreteType(); } else if (key instanceof ExceptionReturnValueKey) { return getCallGraph().getClassHierarchy().lookupClass(TypeReference.JavaLangException); } else if (key instanceof ReturnValueKey) { ReturnValueKey r = (ReturnValueKey) key; return getCallGraph() .getClassHierarchy() .lookupClass(r.getNode().getMethod().getReturnType()); } else { Assertions.UNREACHABLE("inferType " + key.getClass()); return null; } } @Override public HeapModel getHeapModel() { return heapModel; } @Override public Collection<PointerKey> getPointerKeys() { return Iterator2Collection.toSet(heapModel.iteratePointerKeys()); } @Override public boolean isFiltered(PointerKey pk) { return false; } @Override public IClassHierarchy getClassHierarchy() { return heapModel.getClassHierarchy(); } }
7,472
36.93401
98
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/ipa/callgraph/pruned/ApplicationLoaderPolicy.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 com.ibm.wala.ipa.callgraph.pruned; import com.ibm.wala.ipa.callgraph.AnalysisScope; import com.ibm.wala.ipa.callgraph.CGNode; /** * Keeps a given CGNode if it stems from application code * * @author Martin Mohr */ public class ApplicationLoaderPolicy implements PruningPolicy { public static final ApplicationLoaderPolicy INSTANCE = new ApplicationLoaderPolicy(); private ApplicationLoaderPolicy() {} @Override public boolean check(CGNode n) { return n.getMethod() .getDeclaringClass() .getClassLoader() .getName() .equals(AnalysisScope.APPLICATION); } }
986
26.416667
87
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/ipa/callgraph/pruned/CallGraphPruning.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.ipa.callgraph.pruned; import com.ibm.wala.ipa.callgraph.CGNode; import com.ibm.wala.ipa.callgraph.CallGraph; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Set; public final class CallGraphPruning { public CallGraphPruning(CallGraph cg) { this.cg = cg; } private PruningPolicy pruningPolicy; private Set<CGNode> keep; private ArrayDeque<CGNode> visited; private List<CGNode> marked; private int depth; private final CallGraph cg; private final boolean DEBUG = false; /** * Searches all nodes in the callgraph that correspond to a method of the application (and not the * system library). It includes methods from the system library that transitively may call back * into the application. * * @return Set of relevant callgraph nodes. */ public Set<CGNode> findApplicationNodes() { return findApplicationNodes(0); } /** * Searches all nodes in the callgraph that correspond to a method of the application (and not the * system library). It includes methods from the system library that transitively may call back * into the application. Library methods that do not transitively call back into application * methods are cut at the level provided by parameter depth. * * @param depth The level at which non-returning library methods are cut off. * @return Set of relevant callgraph nodes. */ public Set<CGNode> findApplicationNodes(final int depth) { return findNodes(depth, ApplicationLoaderPolicy.INSTANCE); } /** * Searches all nodes in the callgraph according to the given pruning policy. It includes all * methods which transitively may call methods which comply to the given pruning policy. All other * methods are cut at the level provided by parameter 'depth' * * @param depth the level at which methods which do not comply to the given pruning policy are cut * off. * @param policy pruning policy which decides which branches are kept in the call graph * @return set of relevant callgraph nodes */ public Set<CGNode> findNodes(final int depth, PruningPolicy policy) { if (DEBUG) { System.out.println("Running optimization with depth: " + depth); } this.marked = new ArrayList<>(); this.keep = new HashSet<>(); this.visited = new ArrayDeque<>(); this.depth = depth; this.pruningPolicy = policy; dfs(cg.getFakeRootNode()); return keep; } private void dfs(CGNode root) { visited.addLast(root); Iterator<CGNode> it = cg.getSuccNodes(root); while (it.hasNext()) { CGNode next = it.next(); if (!marked.contains(next)) { marked.add(next); dfs(next); } else { if (keep.contains(next)) { keep.addAll(visited); } } } if (pruningPolicy.check(root)) { keep.addAll(visited); addDepth(root); } visited.removeLast(); } private void addDepth(CGNode node) { ArrayList<CGNode> A = new ArrayList<>(); ArrayList<CGNode> B = new ArrayList<>(); int i = depth; A.add(node); while (i > 0) { for (CGNode n : A) { Iterator<CGNode> it = cg.getSuccNodes(n); while (it.hasNext()) { B.add(it.next()); } } if (DEBUG) { System.out.println("Tiefe: " + B); } keep.addAll(B); A.clear(); A.addAll(B); B.clear(); i--; } } }
3,909
27.129496
100
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/ipa/callgraph/pruned/DoNotPrune.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.ipa.callgraph.pruned; import com.ibm.wala.ipa.callgraph.CGNode; public class DoNotPrune implements PruningPolicy { public static DoNotPrune INSTANCE = new DoNotPrune(); @Override public boolean check(CGNode n) { return true; } }
642
24.72
72
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/ipa/callgraph/pruned/PrunedCallGraph.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.ipa.callgraph.pruned; import com.ibm.wala.classLoader.CallSiteReference; import com.ibm.wala.classLoader.IMethod; import com.ibm.wala.ipa.callgraph.CGNode; import com.ibm.wala.ipa.callgraph.CallGraph; import com.ibm.wala.ipa.callgraph.Context; import com.ibm.wala.ipa.cha.IClassHierarchy; import com.ibm.wala.types.MethodReference; import com.ibm.wala.util.intset.BitVectorIntSet; import com.ibm.wala.util.intset.IntSet; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashSet; import java.util.Iterator; import java.util.Map; import java.util.Set; import java.util.stream.Stream; public class PrunedCallGraph implements CallGraph { private final CallGraph cg; private final Set<CGNode> keep; private Map<CGNode, Set<CGNode>> remove = Collections.emptyMap(); /** * Create a pruned (filtered) view of an existing call graph. * * <p>Note: the created instance retains references to {@code cg} and {@code keep} without making * private copies thereof. Be cautious if subsequently modifying {@code cg} or {@code keep} * outside of this class's control. In particular, {@code keep} must always be a subset of the * nodes in {@code cg} or else unexpected behavior may arise. * * @param cg Underlying call graph to prune * @param keep Subset of {@code cg} nodes to include in the pruned graph * @throws IllegalArgumentException if any {@code keep} node is not a node in {@code cg} */ public PrunedCallGraph(CallGraph cg, Set<CGNode> keep) { this.cg = cg; this.keep = keep; for (CGNode keptNode : keep) if (!cg.containsNode(keptNode)) throw new IllegalArgumentException(String.format("%s does not contain %s", cg, keptNode)); } public PrunedCallGraph(CallGraph cg, Set<CGNode> keep, Map<CGNode, Set<CGNode>> remove) { this(cg, keep); this.remove = remove; } @Override public void removeNodeAndEdges(CGNode n) throws UnsupportedOperationException { cg.removeNodeAndEdges(n); keep.remove(n); remove.remove(n); } @Override public Iterator<CGNode> iterator() { return keep.iterator(); } @Override public Stream<CGNode> stream() { return keep.stream(); } @Override public int getNumberOfNodes() { return keep.size(); } @Override public void addNode(CGNode n) { cg.addNode(n); keep.add(n); } @Override public void removeNode(CGNode n) throws UnsupportedOperationException { cg.removeNode(n); keep.remove(n); remove.remove(n); } @Override public boolean containsNode(CGNode n) { return cg.containsNode(n) && keep.contains(n); } private boolean removedEdge(CGNode src, CGNode target) { return remove.containsKey(src) && remove.get(src).contains(target); } @Override public Iterator<CGNode> getPredNodes(CGNode n) { Iterator<CGNode> tmp = cg.getPredNodes(n); Collection<CGNode> col = new ArrayList<>(); while (tmp.hasNext()) { CGNode no = tmp.next(); if (keep.contains(no) && !removedEdge(no, n)) { col.add(no); } } return col.iterator(); } @Override public int getPredNodeCount(CGNode n) { Iterator<CGNode> tmp = cg.getPredNodes(n); int cnt = 0; while (tmp.hasNext()) { CGNode no = tmp.next(); if (keep.contains(no) && !removedEdge(no, n)) { cnt++; } } return cnt; } @Override public Iterator<CGNode> getSuccNodes(CGNode n) { Iterator<CGNode> tmp = cg.getSuccNodes(n); Collection<CGNode> col = new ArrayList<>(); while (tmp.hasNext()) { CGNode no = tmp.next(); if (keep.contains(no) && !removedEdge(n, no)) { col.add(no); } } return col.iterator(); } @Override public int getSuccNodeCount(CGNode n) { Iterator<CGNode> tmp = cg.getSuccNodes(n); int cnt = 0; while (tmp.hasNext()) { CGNode no = tmp.next(); if (keep.contains(no) && !removedEdge(n, no)) { cnt++; } } return cnt; } @Override public void addEdge(CGNode src, CGNode dst) { if (keep.contains(src) && keep.contains(dst)) { cg.addEdge(src, dst); } } @Override public void removeEdge(CGNode src, CGNode dst) throws UnsupportedOperationException { cg.removeEdge(src, dst); } @Override public void removeAllIncidentEdges(CGNode node) throws UnsupportedOperationException { cg.removeAllIncidentEdges(node); } @Override public void removeIncomingEdges(CGNode node) throws UnsupportedOperationException { cg.removeIncomingEdges(node); } @Override public void removeOutgoingEdges(CGNode node) throws UnsupportedOperationException { cg.removeOutgoingEdges(node); } @Override public boolean hasEdge(CGNode src, CGNode dst) { return cg.hasEdge(src, dst) && keep.contains(src) && keep.contains(dst) && !removedEdge(src, dst); } @Override public int getNumber(CGNode N) { if (keep.contains(N)) { return cg.getNumber(N); } else { return -1; } } @Override public CGNode getNode(int number) { if (keep.contains(cg.getNode(number))) { return cg.getNode(number); } else { return null; } } @Override public int getMaxNumber() { return cg.getMaxNumber(); } @Override public Iterator<CGNode> iterateNodes(IntSet s) { Iterator<CGNode> tmp = cg.iterateNodes(s); Collection<CGNode> col = new ArrayList<>(); while (tmp.hasNext()) { CGNode n = tmp.next(); if (keep.contains(n)) { col.add(n); } } return col.iterator(); } @Override public IntSet getSuccNodeNumbers(CGNode node) { if (!keep.contains(node)) { return null; } IntSet tmp = cg.getSuccNodeNumbers(node); BitVectorIntSet kp = new BitVectorIntSet(); for (CGNode n : keep) { if (!removedEdge(node, n)) { kp.add(getNumber(n)); } } return tmp.intersection(kp); } @Override public IntSet getPredNodeNumbers(CGNode node) { if (!keep.contains(node)) { return null; } IntSet tmp = cg.getPredNodeNumbers(node); BitVectorIntSet kp = new BitVectorIntSet(); for (CGNode n : keep) { if (!removedEdge(n, node)) { kp.add(getNumber(n)); } } return tmp.intersection(kp); } @Override public CGNode getFakeRootNode() { if (keep.contains(cg.getFakeRootNode())) { return cg.getFakeRootNode(); } else { return null; } } @Override public CGNode getFakeWorldClinitNode() { if (keep.contains(cg.getFakeWorldClinitNode())) { return cg.getFakeRootNode(); } else { return null; } } @Override public Collection<CGNode> getEntrypointNodes() { Collection<CGNode> tmp = cg.getEntrypointNodes(); Set<CGNode> ret = new HashSet<>(); for (CGNode n : tmp) { if (keep.contains(n)) { ret.add(n); } } return ret; } @Override public CGNode getNode(IMethod method, Context C) { if (keep.contains(cg.getNode(method, C))) { return cg.getNode(method, C); } else { return null; } } @Override public Set<CGNode> getNodes(MethodReference m) { Set<CGNode> tmp = cg.getNodes(m); Set<CGNode> ret = new HashSet<>(); for (CGNode n : tmp) { if (keep.contains(n)) { ret.add(n); } } return ret; } @Override public IClassHierarchy getClassHierarchy() { return cg.getClassHierarchy(); } @Override public Set<CGNode> getPossibleTargets(CGNode node, CallSiteReference site) { if (!keep.contains(node)) { return null; } Set<CGNode> tmp = cg.getPossibleTargets(node, site); Set<CGNode> ret = new HashSet<>(); for (CGNode n : tmp) { if (keep.contains(n) && !removedEdge(node, n)) { ret.add(n); } } return ret; } @Override public int getNumberOfTargets(CGNode node, CallSiteReference site) { if (!keep.contains(node)) { return -1; } return getPossibleTargets(node, site).size(); } @Override public Iterator<CallSiteReference> getPossibleSites(CGNode src, CGNode target) { if (!(keep.contains(src) && keep.contains(target)) || removedEdge(src, target)) { return null; } return cg.getPossibleSites(src, target); } }
8,745
23.988571
99
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/ipa/callgraph/pruned/PruningPolicy.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.ipa.callgraph.pruned; import com.ibm.wala.ipa.callgraph.CGNode; /** * Policy which decides which branch of a call graph is going to be pruned. * * @author Martin Mohr */ public interface PruningPolicy { /** * Returns whether the given node shall be kept. * * @param n node to be checked * @return {@code true}, if this node shall be kept, {@code false} otherwise */ boolean check(CGNode n); }
815
26.2
78
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/ipa/callgraph/util/CallGraphSearchUtil.java
package com.ibm.wala.ipa.callgraph.util; import com.ibm.wala.core.util.strings.Atom; import com.ibm.wala.ipa.callgraph.CGNode; import com.ibm.wala.ipa.callgraph.CallGraph; import com.ibm.wala.types.Descriptor; import com.ibm.wala.util.collections.Iterator2Iterable; import com.ibm.wala.util.debug.Assertions; /** * Utility methods for searching call graphs, e.g., to find particular {@link CGNode}s or types of * statements within a node */ public class CallGraphSearchUtil { private CallGraphSearchUtil() {} /** * Find the main method in a call graph * * @param cg call graph * @return CGNode for the main method * @throws com.ibm.wala.util.debug.UnimplementedError if no main method is not found */ public static CGNode findMainMethod(CallGraph cg) { Descriptor d = Descriptor.findOrCreateUTF8("([Ljava/lang/String;)V"); Atom name = Atom.findOrCreateUnicodeAtom("main"); return findMethod(cg, d, name); } /** * Find a method in a call graph * * @param cg the call graph * @param d descriptor for the desired method * @param name name of the desired method * @return the corresponding CGNode. If multiple CGNodes exist for the descriptor and name, * returns one of them arbitrarily * @throws com.ibm.wala.util.debug.UnimplementedError if no matching CGNode is found */ public static CGNode findMethod(CallGraph cg, Descriptor d, Atom name) { for (CGNode n : Iterator2Iterable.make(cg.getSuccNodes(cg.getFakeRootNode()))) { if (n.getMethod().getName().equals(name) && n.getMethod().getDescriptor().equals(d)) { return n; } } // if it's not a successor of fake root, just iterate over everything for (CGNode n : cg) { if (n.getMethod().getName().equals(name) && n.getMethod().getDescriptor().equals(d)) { return n; } } Assertions.UNREACHABLE("failed to find method " + name); return null; } /** * Find method with some name in a call graph * * @param cg the call graph * @param name desired method name * @return matching {@link CGNode} * @throws com.ibm.wala.util.debug.UnimplementedError if no matching CGNode is found */ public static CGNode findMethod(CallGraph cg, String name) { Atom a = Atom.findOrCreateUnicodeAtom(name); for (CGNode n : cg) { if (n.getMethod().getName().equals(a)) { return n; } } System.err.println("call graph " + cg); Assertions.UNREACHABLE("failed to find method " + name); return null; } }
2,543
32.038961
98
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/ipa/cfg/AbstractInterproceduralCFG.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.ipa.cfg; import com.ibm.wala.cfg.ControlFlowGraph; import com.ibm.wala.cfg.IBasicBlock; import com.ibm.wala.classLoader.CallSiteReference; import com.ibm.wala.ipa.callgraph.CGNode; import com.ibm.wala.ipa.callgraph.CallGraph; import com.ibm.wala.ssa.ISSABasicBlock; import com.ibm.wala.ssa.SSAAbstractInvokeInstruction; import com.ibm.wala.ssa.SSAInstruction; import com.ibm.wala.util.collections.FilterIterator; import com.ibm.wala.util.collections.IndiscriminateFilter; import com.ibm.wala.util.collections.Iterator2Iterable; import com.ibm.wala.util.collections.MapIterator; import com.ibm.wala.util.debug.Assertions; import com.ibm.wala.util.debug.UnimplementedError; import com.ibm.wala.util.graph.NodeManager; import com.ibm.wala.util.graph.NumberedGraph; import com.ibm.wala.util.graph.impl.SlowSparseNumberedGraph; import com.ibm.wala.util.intset.BitVector; import com.ibm.wala.util.intset.BitVectorIntSet; import com.ibm.wala.util.intset.IntSet; import com.ibm.wala.util.intset.MutableIntSet; import java.util.Iterator; import java.util.Set; import java.util.function.Function; import java.util.function.Predicate; import java.util.stream.Stream; /** Interprocedural control-flow graph, constructed lazily. */ public abstract class AbstractInterproceduralCFG<T extends ISSABasicBlock> implements NumberedGraph<BasicBlockInContext<T>> { private static final int DEBUG_LEVEL = 0; private static final boolean WARN_ON_EAGER_CONSTRUCTION = false; private static final boolean FAIL_ON_EAGER_CONSTRUCTION = false; /** * Should the graph include call-to-return edges? When set to {@code false}, the graphs output by * {@link com.ibm.wala.ide.ui.IFDSExplorer} look incorrect */ @SuppressWarnings({"JavadocReference", "javadoc"}) private static final boolean CALL_TO_RETURN_EDGES = true; /** Graph implementation we delegate to. */ private final NumberedGraph<BasicBlockInContext<T>> g = new SlowSparseNumberedGraph<>(2) { private static final long serialVersionUID = 1L; @Override protected String nodeString(BasicBlockInContext<T> n, boolean forEdge) { if (forEdge) { return n.toString(); } else { StringBuilder sb = new StringBuilder(n.toString()); n.iterator().forEachRemaining(inst -> sb.append("\n").append(inst.toString())); return sb.toString(); } } }; /** Governing call graph */ private final CallGraph cg; /** Filter that determines relevant call graph nodes */ private final Predicate<CGNode> relevant; /** a cache: for each node (Basic Block), does that block end in a call? */ private final BitVector hasCallVector = new BitVector(); /** CGNodes whose intraprocedural edges have been added to IPCFG */ private MutableIntSet cgNodesVisited = new BitVectorIntSet(); /** those cg nodes whose edges to callers have been added */ private MutableIntSet cgNodesWithCallerEdges = new BitVectorIntSet(); /** those call nodes whose successor edges (interprocedural) have been added */ private MutableIntSet handledCalls = new BitVectorIntSet(); /** those return nodes whose predecessor edges (interprocedural) have been added */ private MutableIntSet handledReturns = new BitVectorIntSet(); /** those nodes whose successor edges (intra- and inter-procedural) have been added */ private MutableIntSet addedSuccs = new BitVectorIntSet(); /** those nodes whose predecessor edges (intra- and inter-procedural) have been added */ private MutableIntSet addedPreds = new BitVectorIntSet(); /** * Should be invoked when the underlying call graph has changed. This will cause certain successor * and predecessor edges to be recomputed. USE WITH EXTREME CARE. */ public void callGraphUpdated() { cgNodesVisited = new BitVectorIntSet(); cgNodesWithCallerEdges = new BitVectorIntSet(); handledCalls = new BitVectorIntSet(); handledReturns = new BitVectorIntSet(); addedSuccs = new BitVectorIntSet(); addedPreds = new BitVectorIntSet(); } public abstract ControlFlowGraph<SSAInstruction, T> getCFG(CGNode n); /** * Build an Interprocedural CFG from a call graph. This version defaults to using whatever CFGs * the call graph provides by default, and includes all nodes in the call graph. * * @param cg the call graph */ public AbstractInterproceduralCFG(CallGraph cg) { this(cg, IndiscriminateFilter.<CGNode>singleton()); } /** * Build an Interprocedural CFG from a call graph. * * @param CG the call graph * @param relevant a filter which accepts those call graph nodes which should be included in the * I-CFG. Other nodes are ignored. */ public AbstractInterproceduralCFG(CallGraph CG, Predicate<CGNode> relevant) { this.cg = CG; this.relevant = relevant; } /** If n is relevant and its cfg has not already been added, add nodes and edges for n */ @SuppressWarnings("unused") private void addIntraproceduralNodesAndEdgesForCGNodeIfNeeded(CGNode n) { if (!cgNodesVisited.contains(cg.getNumber(n)) && relevant.test(n)) { if (DEBUG_LEVEL > 0) { System.err.println("Adding nodes and edges for cg node: " + n); } cgNodesVisited.add(cg.getNumber(n)); // retrieve a cfg for node n. ControlFlowGraph<SSAInstruction, T> cfg = getCFG(n); if (cfg != null) { // create a node for each basic block. addNodeForEachBasicBlock(cfg, n); SSAInstruction[] instrs = cfg.getInstructions(); // create edges for node n. for (T bb : cfg) { if (bb != cfg.entry()) addEdgesToNonEntryBlock(n, cfg, instrs, bb); } } } } /** * Add edges to the IPCFG for the incoming edges incident on a basic block bb. * * @param n a call graph node * @param cfg the CFG for n * @param instrs the instructions for node n * @param bb a basic block in the CFG */ @SuppressWarnings("unused") protected void addEdgesToNonEntryBlock( CGNode n, ControlFlowGraph<?, T> cfg, SSAInstruction[] instrs, T bb) { if (DEBUG_LEVEL > 1) { System.err.println("addEdgesToNonEntryBlock: " + bb); System.err.println("nPred: " + cfg.getPredNodeCount(bb)); } for (T pb : Iterator2Iterable.make(cfg.getPredNodes(bb))) { if (DEBUG_LEVEL > 1) { System.err.println("Consider previous block: " + pb); } if (pb.equals(cfg.entry())) { // entry block has no instructions BasicBlockInContext<T> p = new BasicBlockInContext<>(n, pb); BasicBlockInContext<T> b = new BasicBlockInContext<>(n, bb); g.addEdge(p, b); continue; } SSAInstruction inst = getLastInstructionForBlock(pb, instrs); if (DEBUG_LEVEL > 1) { System.err.println("Last instruction is : " + inst); } if (inst instanceof SSAAbstractInvokeInstruction) { if (CALL_TO_RETURN_EDGES) { // Add a "normal" edge from the predecessor block to this block. BasicBlockInContext<T> p = new BasicBlockInContext<>(n, pb); BasicBlockInContext<T> b = new BasicBlockInContext<>(n, bb); g.addEdge(p, b); } } else { // previous instruction is not a call instruction. BasicBlockInContext<T> p = new BasicBlockInContext<>(n, pb); BasicBlockInContext<T> b = new BasicBlockInContext<>(n, bb); if (!g.containsNode(p) || !g.containsNode(b)) { assert g.containsNode(p) : "IPCFG does not contain " + p; assert g.containsNode(b) : "IPCFG does not contain " + b; } g.addEdge(p, b); } } } protected SSAInstruction getLastInstructionForBlock(T pb, SSAInstruction[] instrs) { int index = pb.getLastInstructionIndex(); SSAInstruction inst = instrs[index]; return inst; } /** * Add an edge from the exit() block of a callee to a return site in the caller * * @param returnBlock the return site for a call * @param targetCFG the called method */ @SuppressWarnings("unused") private void addEdgesFromExitToReturn( CGNode caller, T returnBlock, CGNode target, ControlFlowGraph<SSAInstruction, ? extends T> targetCFG) { T texit = targetCFG.exit(); BasicBlockInContext<T> exit = new BasicBlockInContext<>(target, texit); addNodeForBasicBlockIfNeeded(exit); BasicBlockInContext<T> ret = new BasicBlockInContext<>(caller, returnBlock); if (!g.containsNode(exit) || !g.containsNode(ret)) { assert g.containsNode(exit) : "IPCFG does not contain " + exit; assert g.containsNode(ret) : "IPCFG does not contain " + ret; } if (DEBUG_LEVEL > 1) { System.err.println("addEdgeFromExitToReturn " + exit + ret); } g.addEdge(exit, ret); } /** * Add an edge from the exit() block of a callee to a return site in the caller * * @param callBlock the return site for a call * @param targetCFG the called method */ @SuppressWarnings("unused") private void addEdgesFromCallToEntry( CGNode caller, T callBlock, CGNode target, ControlFlowGraph<SSAInstruction, ? extends T> targetCFG) { T tentry = targetCFG.entry(); BasicBlockInContext<T> entry = new BasicBlockInContext<>(target, tentry); addNodeForBasicBlockIfNeeded(entry); BasicBlockInContext<T> call = new BasicBlockInContext<>(caller, callBlock); if (!g.containsNode(entry) || !g.containsNode(call)) { assert g.containsNode(entry) : "IPCFG does not contain " + entry; assert g.containsNode(call) : "IPCFG does not contain " + call; } if (DEBUG_LEVEL > 1) { System.err.println("addEdgeFromCallToEntry " + call + ' ' + entry); } g.addEdge(call, entry); } /** * Add the incoming edges to the entry() block and the outgoing edges from the exit() block for a * call graph node. * * @param n a node in the call graph */ @SuppressWarnings("unused") private void addInterproceduralEdgesForEntryAndExitBlocks( CGNode n, ControlFlowGraph<SSAInstruction, ? extends T> cfg) { T entryBlock = cfg.entry(); T exitBlock = cfg.exit(); if (DEBUG_LEVEL > 0) { System.err.println("addInterproceduralEdgesForEntryAndExitBlocks " + n); } for (CGNode caller : Iterator2Iterable.make(cg.getPredNodes(n))) { if (DEBUG_LEVEL > 1) { System.err.println("got caller " + caller); } if (relevant.test(caller)) { addEntryAndExitEdgesToCaller(n, entryBlock, exitBlock, caller); } } } @SuppressWarnings("unused") private void addEntryAndExitEdgesToCaller(CGNode n, T entryBlock, T exitBlock, CGNode caller) { if (DEBUG_LEVEL > 0) { System.err.println("caller " + caller + "is relevant"); } ControlFlowGraph<SSAInstruction, T> ccfg = getCFG(caller); if (ccfg != null) { SSAInstruction[] cinsts = ccfg.getInstructions(); if (DEBUG_LEVEL > 1) { System.err.println("Visiting " + cinsts.length + " instructions"); } for (int i = 0; i < cinsts.length; i++) { if (cinsts[i] instanceof SSAAbstractInvokeInstruction) { if (DEBUG_LEVEL > 1) { System.err.println("Checking invokeinstruction: " + cinsts[i]); } SSAAbstractInvokeInstruction call = (SSAAbstractInvokeInstruction) cinsts[i]; CallSiteReference site = call.getCallSite(); assert site.getProgramCounter() == ccfg.getProgramCounter(i); if (cg.getPossibleTargets(caller, site).contains(n)) { if (DEBUG_LEVEL > 1) { System.err.println( "Adding edge " + ccfg.getBlockForInstruction(i) + " to " + entryBlock); } T callerBB = ccfg.getBlockForInstruction(i); BasicBlockInContext<T> b1 = new BasicBlockInContext<>(caller, callerBB); // need to add a node for caller basic block, in case we haven't processed caller yet addNodeForBasicBlockIfNeeded(b1); BasicBlockInContext<T> b2 = new BasicBlockInContext<>(n, entryBlock); g.addEdge(b1, b2); // also add edges from exit node to all return nodes (successor of call bb) for (T returnBB : Iterator2Iterable.make(ccfg.getSuccNodes(callerBB))) { BasicBlockInContext<T> b3 = new BasicBlockInContext<>(n, exitBlock); BasicBlockInContext<T> b4 = new BasicBlockInContext<>(caller, returnBB); addNodeForBasicBlockIfNeeded(b4); g.addEdge(b3, b4); } } } } } } /** * Add a node to the IPCFG for each node in a CFG. side effect: populates the hasCallVector * * @param cfg a control-flow graph */ @SuppressWarnings("unused") private void addNodeForEachBasicBlock( ControlFlowGraph<? extends SSAInstruction, ? extends T> cfg, CGNode N) { for (T bb : cfg) { if (DEBUG_LEVEL > 1) { System.err.println("IPCFG Add basic block " + bb); } BasicBlockInContext<T> b = new BasicBlockInContext<>(N, bb); addNodeForBasicBlockIfNeeded(b); } } private void addNodeForBasicBlockIfNeeded(BasicBlockInContext<T> b) { if (!g.containsNode(b)) { g.addNode(b); ControlFlowGraph<SSAInstruction, T> cfg = getCFG(b); if (hasCall(b, cfg)) { hasCallVector.set(g.getNumber(b)); } } } /** * @return the original CFG from whence B came * @throws IllegalArgumentException if B == null */ public ControlFlowGraph<SSAInstruction, T> getCFG(BasicBlockInContext<T> B) throws IllegalArgumentException { if (B == null) { throw new IllegalArgumentException("B == null"); } return getCFG(getCGNode(B)); } /** * @return the original CGNode from whence B came * @throws IllegalArgumentException if B == null */ public CGNode getCGNode(BasicBlockInContext<T> B) throws IllegalArgumentException { if (B == null) { throw new IllegalArgumentException("B == null"); } return B.getNode(); } /** @see com.ibm.wala.util.graph.Graph#removeNodeAndEdges(Object) */ @Override public void removeNodeAndEdges(BasicBlockInContext<T> N) throws UnsupportedOperationException { throw new UnsupportedOperationException(); } /** @see NodeManager#iterator() */ @Override public Iterator<BasicBlockInContext<T>> iterator() { constructFullGraph("iterator"); return g.iterator(); } /** @see NodeManager#iterator() */ @Override public Stream<BasicBlockInContext<T>> stream() { constructFullGraph("stream"); return g.stream(); } /** @see com.ibm.wala.util.graph.NodeManager#getNumberOfNodes() */ @Override public int getNumberOfNodes() { constructFullGraph("getNumberOfNodes"); return g.getNumberOfNodes(); } private boolean constructedFullGraph = false; private void constructFullGraph(String onBehalfOf) { if (WARN_ON_EAGER_CONSTRUCTION) { System.err.format("WARNING: forcing full ICFG construction by calling %s()\n", onBehalfOf); } if (FAIL_ON_EAGER_CONSTRUCTION) { throw new UnimplementedError(); } if (!constructedFullGraph) { for (CGNode n : cg) { addIntraproceduralNodesAndEdgesForCGNodeIfNeeded(n); addEdgesToCallees(n); } for (int i = 0; i < g.getMaxNumber(); i++) { addedSuccs.add(i); addedPreds.add(i); } constructedFullGraph = true; } } /** add interprocedural edges to nodes in callees of n */ private void addEdgesToCallees(CGNode n) { ControlFlowGraph<SSAInstruction, T> cfg = getCFG(n); if (cfg != null) { for (T bb : cfg) { BasicBlockInContext<T> block = new BasicBlockInContext<>(n, bb); if (hasCall(block)) { addCalleeEdgesForCall(n, block); } } } } /** add edges to callees for return block and corresponding call block(s) */ private void addCalleeEdgesForReturn(CGNode node, BasicBlockInContext<T> returnBlock) { final int num = g.getNumber(returnBlock); if (!handledReturns.contains(num)) { handledReturns.add(num); // compute calls for return ControlFlowGraph<SSAInstruction, T> cfg = getCFG(returnBlock); for (Iterator<? extends T> it = cfg.getPredNodes(returnBlock.getDelegate()); it.hasNext(); ) { T b = it.next(); final BasicBlockInContext<T> block = new BasicBlockInContext<>(node, b); if (hasCall(block)) { addCalleeEdgesForCall(node, block); } } } } /** * add edges to callee entry for call block, and edges from callee exit to corresponding return * blocks */ @SuppressWarnings("unused") private void addCalleeEdgesForCall(CGNode n, BasicBlockInContext<T> callBlock) { int num = g.getNumber(callBlock); if (!handledCalls.contains(num)) { handledCalls.add(num); ControlFlowGraph<SSAInstruction, T> cfg = getCFG(n); CallSiteReference site = getCallSiteForCallBlock(callBlock, cfg); if (DEBUG_LEVEL > 1) { System.err.println("got Site: " + site); } boolean irrelevantTargets = false; for (CGNode tn : cg.getPossibleTargets(n, site)) { if (!relevant.test(tn)) { if (DEBUG_LEVEL > 1) { System.err.println("Irrelevant target: " + tn); } irrelevantTargets = true; continue; } if (DEBUG_LEVEL > 1) { System.err.println("Relevant target: " + tn); } // add an edge from tn exit to this node ControlFlowGraph<SSAInstruction, ? extends T> tcfg = getCFG(tn); // tcfg might be null if tn is an unmodelled native method if (tcfg != null) { final T cbDelegate = callBlock.getDelegate(); addEdgesFromCallToEntry(n, cbDelegate, tn, tcfg); for (Iterator<? extends T> returnBlocks = cfg.getSuccNodes(cbDelegate); returnBlocks.hasNext(); ) { T retBlock = returnBlocks.next(); addEdgesFromExitToReturn(n, retBlock, tn, tcfg); if (irrelevantTargets) { // Add a "normal" edge from the call block to the return block. g.addEdge(callBlock, new BasicBlockInContext<>(n, retBlock)); } } } } } } /** add edges to nodes in callers of n */ private void addCallerEdges(CGNode n) { final int num = cg.getNumber(n); if (!cgNodesWithCallerEdges.contains(num)) { cgNodesWithCallerEdges.add(num); ControlFlowGraph<SSAInstruction, T> cfg = getCFG(n); addInterproceduralEdgesForEntryAndExitBlocks(n, cfg); } } /** @see com.ibm.wala.util.graph.NodeManager#addNode(Object) */ @Override public void addNode(BasicBlockInContext<T> n) throws UnsupportedOperationException { throw new UnsupportedOperationException(); } /** @see com.ibm.wala.util.graph.NodeManager#removeNode(Object) */ @Override public void removeNode(BasicBlockInContext<T> n) throws UnsupportedOperationException { throw new UnsupportedOperationException(); } /** @see com.ibm.wala.util.graph.EdgeManager#getPredNodes(Object) */ @Override public Iterator<BasicBlockInContext<T>> getPredNodes(BasicBlockInContext<T> N) { initForPred(N); return g.getPredNodes(N); } /** add enough nodes and edges to the graph to allow for computing predecessors of N */ private void initForPred(BasicBlockInContext<T> N) { CGNode node = getCGNode(N); addIntraproceduralNodesAndEdgesForCGNodeIfNeeded(node); int num = g.getNumber(N); if (!addedPreds.contains(num)) { addedPreds.add(num); if (N.getDelegate().isEntryBlock()) { addCallerEdges(node); } if (isReturn(N)) { addCalleeEdgesForReturn(node, N); } } } /** add enough nodes and edges to the graph to allow for computing successors of N */ private void initForSucc(BasicBlockInContext<T> N) { CGNode node = getCGNode(N); addIntraproceduralNodesAndEdgesForCGNodeIfNeeded(node); int num = g.getNumber(N); if (!addedSuccs.contains(num)) { addedSuccs.add(num); if (N.getDelegate().isExitBlock()) { addCallerEdges(node); } if (hasCall(N)) { addCalleeEdgesForCall(node, N); } } } /** @see com.ibm.wala.util.graph.EdgeManager#getPredNodeCount(Object) */ @Override public int getPredNodeCount(BasicBlockInContext<T> N) { initForPred(N); return g.getPredNodeCount(N); } /** @see com.ibm.wala.util.graph.EdgeManager#getSuccNodes(Object) */ @Override public Iterator<BasicBlockInContext<T>> getSuccNodes(BasicBlockInContext<T> N) { initForSucc(N); return g.getSuccNodes(N); } /** @see com.ibm.wala.util.graph.EdgeManager#getSuccNodeCount(Object) */ @Override public int getSuccNodeCount(BasicBlockInContext<T> N) { initForSucc(N); return g.getSuccNodeCount(N); } /** @see com.ibm.wala.util.graph.EdgeManager#addEdge(Object, Object) */ @Override public void addEdge(BasicBlockInContext<T> src, BasicBlockInContext<T> dst) throws UnsupportedOperationException { throw new UnsupportedOperationException(); } @Override public void removeEdge(BasicBlockInContext<T> src, BasicBlockInContext<T> dst) throws UnsupportedOperationException { throw new UnsupportedOperationException(); } /** @see com.ibm.wala.util.graph.EdgeManager#removeAllIncidentEdges(Object) */ @Override public void removeAllIncidentEdges(BasicBlockInContext<T> node) throws UnsupportedOperationException { throw new UnsupportedOperationException(); } @Override public String toString() { return g.toString(); } /** @see com.ibm.wala.util.graph.Graph#containsNode(Object) */ @Override public boolean containsNode(BasicBlockInContext<T> N) { return g.containsNode(N); } /** @return true iff basic block B ends in a call instuction */ public boolean hasCall(BasicBlockInContext<T> B) { addNodeForBasicBlockIfNeeded(B); return hasCallVector.get(getNumber(B)); } /** @return true iff basic block B ends in a call instuction */ protected boolean hasCall(BasicBlockInContext<T> B, ControlFlowGraph<SSAInstruction, T> cfg) { SSAInstruction[] statements = cfg.getInstructions(); int lastIndex = B.getLastInstructionIndex(); if (lastIndex >= 0) { if (statements.length <= lastIndex) { System.err.println(statements.length); System.err.println(cfg); assert lastIndex < statements.length : "bad BB " + B + " and CFG for " + getCGNode(B); } SSAInstruction last = statements[lastIndex]; return (last instanceof SSAAbstractInvokeInstruction); } else { return false; } } /** * @return the set of CGNodes that B may call, according to the governing call graph. * @throws IllegalArgumentException if B is null */ public Set<CGNode> getCallTargets(BasicBlockInContext<T> B) { if (B == null) { throw new IllegalArgumentException("B is null"); } ControlFlowGraph<SSAInstruction, T> cfg = getCFG(B); return getCallTargets(B, cfg, getCGNode(B)); } /** @return the set of CGNodes that B may call, according to the governing call graph. */ private Set<CGNode> getCallTargets( IBasicBlock<SSAInstruction> B, ControlFlowGraph<SSAInstruction, T> cfg, CGNode Bnode) { CallSiteReference site = getCallSiteForCallBlock(B, cfg); return cg.getPossibleTargets(Bnode, site); } /** * get the {@link CallSiteReference} corresponding to the last instruction in B (assumed to be a * call) */ protected CallSiteReference getCallSiteForCallBlock( IBasicBlock<SSAInstruction> B, ControlFlowGraph<SSAInstruction, T> cfg) { SSAInstruction[] statements = cfg.getInstructions(); SSAAbstractInvokeInstruction call = (SSAAbstractInvokeInstruction) statements[B.getLastInstructionIndex()]; int pc = cfg.getProgramCounter(B.getLastInstructionIndex()); CallSiteReference site = call.getCallSite(); assert site.getProgramCounter() == pc; return site; } @Override public void removeIncomingEdges(BasicBlockInContext<T> node) throws UnsupportedOperationException { throw new UnsupportedOperationException(); } @Override public void removeOutgoingEdges(BasicBlockInContext<T> node) throws UnsupportedOperationException { throw new UnsupportedOperationException(); } @Override public boolean hasEdge(BasicBlockInContext<T> src, BasicBlockInContext<T> dst) { if (!addedSuccs.contains(getNumber(src))) { if (!src.getNode().equals(dst.getNode())) { if (src.getDelegate().isExitBlock()) { // checking for an exit to return edge CGNode callee = src.getNode(); if (!cgNodesWithCallerEdges.contains(cg.getNumber(callee))) { CGNode caller = dst.getNode(); T exitBlock = src.getDelegate(); T entryBlock = getCFG(callee).entry(); addEntryAndExitEdgesToCaller(callee, entryBlock, exitBlock, caller); } } else if (hasCall(src) && dst.getDelegate().isEntryBlock()) { // checking for a call to entry edge CGNode callee = dst.getNode(); if (!cgNodesWithCallerEdges.contains(cg.getNumber(callee))) { CGNode caller = src.getNode(); T entryBlock = dst.getDelegate(); T exitBlock = getCFG(callee).exit(); addEntryAndExitEdgesToCaller(callee, entryBlock, exitBlock, caller); } } } else { // if it exists, edge must be intraprocedural addIntraproceduralNodesAndEdgesForCGNodeIfNeeded(src.getNode()); } } addedSuccs.add(getNumber(src)); return g.hasEdge(src, dst); } @Override public int getNumber(BasicBlockInContext<T> N) { addNodeForBasicBlockIfNeeded(N); return g.getNumber(N); } @Override public BasicBlockInContext<T> getNode(int number) throws UnimplementedError { return g.getNode(number); } @Override public int getMaxNumber() { constructFullGraph("getMaxNumber"); return g.getMaxNumber(); } @Override public Iterator<BasicBlockInContext<T>> iterateNodes(IntSet s) throws UnimplementedError { Assertions.UNREACHABLE(); return null; } @Override public IntSet getSuccNodeNumbers(BasicBlockInContext<T> node) { initForSucc(node); return g.getSuccNodeNumbers(node); } @Override public IntSet getPredNodeNumbers(BasicBlockInContext<T> node) { initForPred(node); return g.getPredNodeNumbers(node); } public BasicBlockInContext<T> getEntry(CGNode n) { ControlFlowGraph<SSAInstruction, ? extends T> cfg = getCFG(n); if (cfg != null) { T entry = cfg.entry(); return new BasicBlockInContext<>(n, entry); } else { return null; } } public BasicBlockInContext<T> getExit(CGNode n) { ControlFlowGraph<SSAInstruction, ? extends T> cfg = getCFG(n); T entry = cfg.exit(); return new BasicBlockInContext<>(n, entry); } /** * @param callBlock node in the IPCFG that ends in a call * @return the nodes that are return sites for this call. * @throws IllegalArgumentException if bb is null */ public Iterator<BasicBlockInContext<T>> getReturnSites(BasicBlockInContext<T> callBlock) { if (callBlock == null) { throw new IllegalArgumentException("bb is null"); } final CGNode node = callBlock.getNode(); // a successor node is a return site if it is in the same // procedure, and is not the entry() node. Predicate<BasicBlockInContext<T>> isReturn = other -> !other.isEntryBlock() && node.equals(other.getNode()); return new FilterIterator<>(getSuccNodes(callBlock), isReturn); } /** * get the basic blocks which are call sites that may call callee and return to returnBlock if * callee is null, answer return sites for which no callee was found. */ public Iterator<BasicBlockInContext<T>> getCallSites( BasicBlockInContext<T> returnBlock, final CGNode callee) { if (returnBlock == null) { throw new IllegalArgumentException("bb is null"); } final ControlFlowGraph<SSAInstruction, T> cfg = getCFG(returnBlock); Iterator<? extends T> it = cfg.getPredNodes(returnBlock.getDelegate()); final CGNode node = returnBlock.getNode(); Predicate<T> dispatchFilter = callBlock -> { BasicBlockInContext<T> bb = new BasicBlockInContext<>(node, callBlock); if (!hasCall(bb, cfg)) { return false; } if (callee != null) { return getCallTargets(bb).contains(callee); } else { return getCallTargets(bb).isEmpty(); } }; it = new FilterIterator<T>(it, dispatchFilter); Function<T, BasicBlockInContext<T>> toContext = object -> { T b = object; return new BasicBlockInContext<>(node, b); }; MapIterator<T, BasicBlockInContext<T>> m = new MapIterator<>(it, toContext); return new FilterIterator<>(m, isCall); } private final Predicate<BasicBlockInContext<T>> isCall = this::hasCall; public boolean isReturn(BasicBlockInContext<T> bb) throws IllegalArgumentException { if (bb == null) { throw new IllegalArgumentException("bb == null"); } ControlFlowGraph<SSAInstruction, T> cfg = getCFG(bb); for (T b : Iterator2Iterable.make(cfg.getPredNodes(bb.getDelegate()))) { if (hasCall(new BasicBlockInContext<>(bb.getNode(), b))) { return true; } } return false; } /** @return the governing {@link CallGraph} used to build this ICFG */ public CallGraph getCallGraph() { return cg; } }
30,222
34.102207
100
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/ipa/cfg/BasicBlockInContext.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.ipa.cfg; import com.ibm.wala.classLoader.IMethod; import com.ibm.wala.ipa.callgraph.CGNode; import com.ibm.wala.ssa.ISSABasicBlock; import com.ibm.wala.ssa.SSAInstruction; import com.ibm.wala.ssa.SSAPhiInstruction; import com.ibm.wala.ssa.SSAPiInstruction; import com.ibm.wala.types.TypeReference; import com.ibm.wala.util.graph.impl.NodeWithNumber; import java.util.Iterator; /** A helper class to make the ipcfg work correctly with context-sensitive call graphs. */ public final class BasicBlockInContext<T extends ISSABasicBlock> extends NodeWithNumber implements ISSABasicBlock { private final T delegate; private final CGNode node; public BasicBlockInContext(CGNode node, T bb) { if (bb == null) { throw new IllegalArgumentException("null bb"); } this.delegate = bb; this.node = node; } /** @see com.ibm.wala.cfg.IBasicBlock#getFirstInstructionIndex() */ @Override public int getFirstInstructionIndex() { return delegate.getFirstInstructionIndex(); } /** @see com.ibm.wala.cfg.IBasicBlock#getLastInstructionIndex() */ @Override public int getLastInstructionIndex() { return delegate.getLastInstructionIndex(); } /** @see com.ibm.wala.cfg.IBasicBlock#iterator() */ @Override public Iterator<SSAInstruction> iterator() { return delegate.iterator(); } /** @see com.ibm.wala.cfg.IBasicBlock#getMethod() */ @Override public IMethod getMethod() { return delegate.getMethod(); } /** @see com.ibm.wala.cfg.IBasicBlock#getNumber() */ @Override public int getNumber() { return delegate.getNumber(); } /** @see com.ibm.wala.cfg.IBasicBlock#isCatchBlock() */ @Override public boolean isCatchBlock() { return delegate.isCatchBlock(); } /** @see com.ibm.wala.cfg.IBasicBlock#isEntryBlock() */ @Override public boolean isEntryBlock() { return delegate.isEntryBlock(); } /** @see com.ibm.wala.cfg.IBasicBlock#isExitBlock() */ @Override public boolean isExitBlock() { return delegate.isExitBlock(); } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((delegate == null) ? 0 : delegate.hashCode()); result = prime * result + ((node == null) ? 0 : node.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; final BasicBlockInContext<?> other = (BasicBlockInContext<?>) obj; if (delegate == null) { if (other.delegate != null) return false; } else if (!delegate.equals(other.delegate)) return false; if (node == null) { if (other.node != null) return false; } else if (!node.equals(other.node)) return false; return true; } public T getDelegate() { return delegate; } public CGNode getNode() { return node; } @Override public String toString() { return delegate.toString(); } @Override public Iterator<TypeReference> getCaughtExceptionTypes() { return delegate.getCaughtExceptionTypes(); } @Override public SSAInstruction getLastInstruction() { return delegate.getLastInstruction(); } @Override public Iterator<SSAPhiInstruction> iteratePhis() { return delegate.iteratePhis(); } @Override public Iterator<SSAPiInstruction> iteratePis() { return delegate.iteratePis(); } }
3,830
25.79021
90
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/ipa/cfg/EdgeFilter.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 com.ibm.wala.ipa.cfg; import com.ibm.wala.cfg.IBasicBlock; /** * This class is used by the PrunedCFG to determine which edges in a given CFG should be kept in the * pruned version. */ public interface EdgeFilter<T extends IBasicBlock<?>> { /** * This method must return true if and only if a normal edge from src to dst exists in the * original CFG and should be kept for the pruned version of that CFG. Note that this must _must_ * return false for any normal edge that is not in the original CFG. */ boolean hasNormalEdge(T src, T dst); /** * This method must return true if and only if an exceptional edge from src to dst exists in the * original CFG and should be kept for the pruned version of that CFG. Note that this must _must_ * return false for any exceptional edge that is not in the original CFG. */ boolean hasExceptionalEdge(T src, T dst); }
1,271
35.342857
100
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/ipa/cfg/ExceptionPrunedCFG.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 com.ibm.wala.ipa.cfg; import com.ibm.wala.cfg.ControlFlowGraph; import com.ibm.wala.cfg.IBasicBlock; /** A view of a CFG that ignores exceptional edges */ public class ExceptionPrunedCFG { private static class ExceptionEdgePruner<I, T extends IBasicBlock<I>> implements EdgeFilter<T> { private final ControlFlowGraph<I, T> cfg; ExceptionEdgePruner(ControlFlowGraph<I, T> cfg) { this.cfg = cfg; } @Override public boolean hasNormalEdge(T src, T dst) { return cfg.getNormalSuccessors(src).contains(dst); } @Override public boolean hasExceptionalEdge(T src, T dst) { return false; } } public static <I, T extends IBasicBlock<I>> PrunedCFG<I, T> make(ControlFlowGraph<I, T> cfg) { return PrunedCFG.make(cfg, new ExceptionEdgePruner<>(cfg)); } }
1,190
28.04878
98
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/ipa/cfg/ExplodedInterproceduralCFG.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.ipa.cfg; import com.ibm.wala.cfg.ControlFlowGraph; import com.ibm.wala.ipa.callgraph.CGNode; import com.ibm.wala.ipa.callgraph.CallGraph; import com.ibm.wala.ssa.IR; import com.ibm.wala.ssa.SSAInstruction; import com.ibm.wala.ssa.analysis.ExplodedControlFlowGraph; import com.ibm.wala.ssa.analysis.IExplodedBasicBlock; import com.ibm.wala.util.collections.HashMapFactory; import java.util.Map; import java.util.function.Predicate; /** Exploded interprocedural control-flow graph, constructed lazily. */ public class ExplodedInterproceduralCFG extends AbstractInterproceduralCFG<IExplodedBasicBlock> { /** Caching to improve runtime .. hope it doesn't turn into a memory leak. */ private Map<CGNode, ExplodedControlFlowGraph> cfgMap; public static ExplodedInterproceduralCFG make(CallGraph cg) { return new ExplodedInterproceduralCFG(cg); } protected ExplodedInterproceduralCFG(CallGraph cg) { super(cg); } public ExplodedInterproceduralCFG(CallGraph cg, Predicate<CGNode> filter) { super(cg, filter); } /** * @return the cfg for n, or null if none found * @throws IllegalArgumentException if n == null */ @Override public ControlFlowGraph<SSAInstruction, IExplodedBasicBlock> getCFG(CGNode n) throws IllegalArgumentException { if (n == null) { throw new IllegalArgumentException("n == null"); } if (cfgMap == null) { // we have to initialize this lazily since this might be called from a super() constructor cfgMap = HashMapFactory.make(); } ExplodedControlFlowGraph result = cfgMap.get(n); if (result == null) { IR ir = n.getIR(); if (ir == null) { return null; } result = ExplodedControlFlowGraph.make(ir); cfgMap.put(n, result); } return result; } }
2,195
31.294118
97
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/ipa/cfg/InterproceduralCFG.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.ipa.cfg; import com.ibm.wala.cfg.ControlFlowGraph; import com.ibm.wala.ipa.callgraph.CGNode; import com.ibm.wala.ipa.callgraph.CallGraph; import com.ibm.wala.ssa.ISSABasicBlock; import com.ibm.wala.ssa.SSAInstruction; import java.util.function.Predicate; /** * Interprocedural control-flow graph. * * <p>TODO: think about a better implementation; perhaps a lazy view of the constituent CFGs Lots of * ways this can be optimized? */ public class InterproceduralCFG extends AbstractInterproceduralCFG<ISSABasicBlock> { public InterproceduralCFG(CallGraph CG) { super(CG); } public InterproceduralCFG(CallGraph cg, Predicate<CGNode> filtersection) { super(cg, filtersection); } /** * @return the cfg for n, or null if none found * @throws IllegalArgumentException if n == null */ @Override public ControlFlowGraph<SSAInstruction, ISSABasicBlock> getCFG(CGNode n) throws IllegalArgumentException { if (n == null) { throw new IllegalArgumentException("n == null"); } if (n.getIR() == null) { return null; } ControlFlowGraph<SSAInstruction, ISSABasicBlock> cfg = n.getIR().getControlFlowGraph(); if (cfg == null) { return null; } return cfg; } }
1,636
27.719298
100
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/ipa/cfg/PrunedCFG.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.ipa.cfg; import com.ibm.wala.cfg.ControlFlowGraph; import com.ibm.wala.cfg.IBasicBlock; import com.ibm.wala.classLoader.IMethod; import com.ibm.wala.util.collections.FilterIterator; import com.ibm.wala.util.collections.Iterator2Collection; import com.ibm.wala.util.collections.Iterator2Iterable; import com.ibm.wala.util.graph.AbstractNumberedGraph; import com.ibm.wala.util.graph.Graph; import com.ibm.wala.util.graph.NumberedEdgeManager; import com.ibm.wala.util.graph.NumberedNodeManager; import com.ibm.wala.util.graph.impl.GraphInverter; import com.ibm.wala.util.graph.traverse.DFS; import com.ibm.wala.util.intset.BitVector; import com.ibm.wala.util.intset.IntSet; import com.ibm.wala.util.intset.IntSetUtil; import com.ibm.wala.util.intset.MutableIntSet; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.NoSuchElementException; import java.util.Set; import java.util.stream.Stream; /** * A pruned view of a {@link ControlFlowGraph}. Use this class along with an {@link EdgeFilter} to * produce a custom view of a CFG. * * <p>For example, you can use this class to produce a CFG view that ignores certain types of * exceptional edges. */ public class PrunedCFG<I, T extends IBasicBlock<I>> extends AbstractNumberedGraph<T> implements ControlFlowGraph<I, T> { /** * @param cfg the original CFG that you want a view of * @param filter an object that selectively filters edges in the original CFG * @return a view of cfg that includes only edges accepted by the filter. * @throws IllegalArgumentException if cfg is null */ public static <I, T extends IBasicBlock<I>> PrunedCFG<I, T> make( final ControlFlowGraph<I, T> cfg, final EdgeFilter<T> filter) { if (cfg == null) { throw new IllegalArgumentException("cfg is null"); } return new PrunedCFG<>(cfg, filter); } private static class FilteredCFGEdges<I, T extends IBasicBlock<I>> implements NumberedEdgeManager<T> { private final ControlFlowGraph<I, T> cfg; private final NumberedNodeManager<T> currentCFGNodes; private final EdgeFilter<T> filter; FilteredCFGEdges( ControlFlowGraph<I, T> cfg, NumberedNodeManager<T> currentCFGNodes, EdgeFilter<T> filter) { this.cfg = cfg; this.filter = filter; this.currentCFGNodes = currentCFGNodes; } public Iterator<T> getExceptionalSuccessors(final T N) { return new FilterIterator<>( cfg.getExceptionalSuccessors(N).iterator(), o -> currentCFGNodes.containsNode(o) && filter.hasExceptionalEdge(N, o)); } public Iterator<T> getNormalSuccessors(final T N) { return new FilterIterator<>( cfg.getNormalSuccessors(N).iterator(), o -> currentCFGNodes.containsNode(o) && filter.hasNormalEdge(N, o)); } public Iterator<T> getExceptionalPredecessors(final T N) { return new FilterIterator<>( cfg.getExceptionalPredecessors(N).iterator(), o -> currentCFGNodes.containsNode(o) && filter.hasExceptionalEdge(o, N)); } public Iterator<T> getNormalPredecessors(final T N) { return new FilterIterator<>( cfg.getNormalPredecessors(N).iterator(), o -> currentCFGNodes.containsNode(o) && filter.hasNormalEdge(o, N)); } @Override public Iterator<T> getSuccNodes(final T N) { return new FilterIterator<>( cfg.getSuccNodes(N), o -> currentCFGNodes.containsNode(o) && (filter.hasNormalEdge(N, o) || filter.hasExceptionalEdge(N, o))); } @Override public int getSuccNodeCount(T N) { return Iterator2Collection.toSet(getSuccNodes(N)).size(); } @Override public IntSet getSuccNodeNumbers(T N) { MutableIntSet bits = IntSetUtil.make(); for (T EE : Iterator2Iterable.make(getSuccNodes(N))) { bits.add(EE.getNumber()); } return bits; } @Override public Iterator<T> getPredNodes(final T N) { return new FilterIterator<>( cfg.getPredNodes(N), o -> currentCFGNodes.containsNode(o) && (filter.hasNormalEdge(o, N) || filter.hasExceptionalEdge(o, N))); } @Override public int getPredNodeCount(T N) { return Iterator2Collection.toSet(getPredNodes(N)).size(); } @Override public IntSet getPredNodeNumbers(T N) { MutableIntSet bits = IntSetUtil.make(); for (T EE : Iterator2Iterable.make(getPredNodes(N))) { bits.add(EE.getNumber()); } return bits; } @Override public boolean hasEdge(T src, T dst) { for (T EE : Iterator2Iterable.make(getSuccNodes(src))) { if (EE.equals(dst)) { return true; } } return false; } @Override public void addEdge(T src, T dst) { throw new UnsupportedOperationException(); } @Override public void removeEdge(T src, T dst) { throw new UnsupportedOperationException(); } @Override public void removeAllIncidentEdges(T node) { throw new UnsupportedOperationException(); } @Override public void removeIncomingEdges(T node) { throw new UnsupportedOperationException(); } @Override public void removeOutgoingEdges(T node) { throw new UnsupportedOperationException(); } } private static class FilteredNodes<T> implements NumberedNodeManager<T> { private final NumberedNodeManager<T> nodes; private final Set<T> subset; FilteredNodes(NumberedNodeManager<T> nodes, Set<T> subset) { this.nodes = nodes; this.subset = subset; } @Override public int getNumber(T N) { if (subset.contains(N)) return nodes.getNumber(N); else return -1; } @Override public T getNode(int number) { T N = nodes.getNode(number); if (subset.contains(N)) return N; else throw new NoSuchElementException(); } @Override public int getMaxNumber() { int max = -1; for (T N : nodes) { if (subset.contains(N) && getNumber(N) > max) { max = getNumber(N); } } return max; } private Iterator<T> filterNodes(Iterator<T> nodeIterator) { return new FilterIterator<>(nodeIterator, subset::contains); } @Override public Iterator<T> iterateNodes(IntSet s) { return filterNodes(nodes.iterateNodes(s)); } @Override public Iterator<T> iterator() { return filterNodes(nodes.iterator()); } @Override public Stream<T> stream() { return nodes.stream().filter(subset::contains); } @Override public int getNumberOfNodes() { return subset.size(); } @Override public void addNode(T n) { throw new UnsupportedOperationException(); } @Override public void removeNode(T n) { throw new UnsupportedOperationException(); } @Override public boolean containsNode(T N) { return subset.contains(N); } } private final ControlFlowGraph<I, T> cfg; private final FilteredNodes<T> nodes; private final FilteredCFGEdges<I, T> edges; private PrunedCFG(final ControlFlowGraph<I, T> cfg, final EdgeFilter<T> filter) { this.cfg = cfg; Graph<T> temp = new AbstractNumberedGraph<>() { private final NumberedEdgeManager<T> edges = new FilteredCFGEdges<>(cfg, cfg, filter); @Override protected NumberedNodeManager<T> getNodeManager() { return cfg; } @Override protected NumberedEdgeManager<T> getEdgeManager() { return edges; } }; Set<T> reachable = DFS.getReachableNodes(temp, Collections.singleton(cfg.entry())); Set<T> back = DFS.getReachableNodes(GraphInverter.invert(temp), Collections.singleton(cfg.exit())); reachable.retainAll(back); reachable.add(cfg.entry()); reachable.add(cfg.exit()); this.nodes = new FilteredNodes<>(cfg, reachable); this.edges = new FilteredCFGEdges<>(cfg, nodes, filter); } @Override protected NumberedNodeManager<T> getNodeManager() { return nodes; } @Override protected NumberedEdgeManager<T> getEdgeManager() { return edges; } @Override public List<T> getExceptionalSuccessors(final T N) { ArrayList<T> result = new ArrayList<>(); for (T s : Iterator2Iterable.make(edges.getExceptionalSuccessors(N))) { result.add(s); } return result; } @Override public Collection<T> getNormalSuccessors(final T N) { return Iterator2Collection.toSet(edges.getNormalSuccessors(N)); } @Override public Collection<T> getExceptionalPredecessors(final T N) { return Iterator2Collection.toSet(edges.getExceptionalPredecessors(N)); } @Override public Collection<T> getNormalPredecessors(final T N) { return Iterator2Collection.toSet(edges.getNormalPredecessors(N)); } @Override public T entry() { return cfg.entry(); } @Override public T exit() { return cfg.exit(); } @Override public T getBlockForInstruction(int index) { return cfg.getBlockForInstruction(index); } @Override public I[] getInstructions() { return cfg.getInstructions(); } @Override public int getProgramCounter(int index) { return cfg.getProgramCounter(index); } @Override public IMethod getMethod() { return cfg.getMethod(); } @Override public BitVector getCatchBlocks() { BitVector result = new BitVector(); BitVector blocks = cfg.getCatchBlocks(); int i = 0; while ((i = blocks.nextSetBit(i)) != -1) { if (nodes.containsNode(getNode(i))) { result.set(i); } } return result; } public IntSet getPhiIndices(T bb) { assert containsNode(bb); assert cfg.containsNode(bb); int i = 0; MutableIntSet valid = IntSetUtil.make(); for (T pb : Iterator2Iterable.make(cfg.getPredNodes(bb))) { if (nodes.containsNode(pb)) { valid.add(i); } ++i; } return valid; } }
10,550
26.123393
99
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/ipa/cfg/exceptionpruning/ExceptionFilter.java
package com.ibm.wala.ipa.cfg.exceptionpruning; import java.util.Collection; /** * To filter exceptions you can implement this interface and use it in combination with {@link * ExceptionFilter2EdgeFilter}. For more Details see package-info. * * @author Stephan Gocht {@code <stephan@gobro.de>} */ public interface ExceptionFilter<Instruction> { /** @return if the instruction does always throw an exception */ boolean alwaysThrowsException(Instruction instruction); /** @return a list of exceptions, which have to be filtered for the given instruction */ Collection<FilteredException> filteredExceptions(Instruction instruction); }
647
35
94
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/ipa/cfg/exceptionpruning/ExceptionFilter2EdgeFilter.java
package com.ibm.wala.ipa.cfg.exceptionpruning; import com.ibm.wala.cfg.ControlFlowGraph; import com.ibm.wala.ipa.cfg.EdgeFilter; import com.ibm.wala.ipa.cha.ClassHierarchy; import com.ibm.wala.ssa.ISSABasicBlock; import com.ibm.wala.ssa.SSAAbstractInvokeInstruction; import com.ibm.wala.ssa.SSAAbstractThrowInstruction; import com.ibm.wala.ssa.SSAInstruction; import com.ibm.wala.types.TypeReference; import java.util.Collection; /** * This class converts an exception filter to an edge filter. * * @author Stephan Gocht {@code <stephan@gobro.de>} */ public class ExceptionFilter2EdgeFilter<Block extends ISSABasicBlock> implements EdgeFilter<Block> { private final ExceptionFilter<SSAInstruction> filter; private final ClassHierarchy cha; private final ControlFlowGraph<SSAInstruction, Block> cfg; public ExceptionFilter2EdgeFilter( ExceptionFilter<SSAInstruction> filter, ClassHierarchy cha, ControlFlowGraph<SSAInstruction, Block> cfg) { this.cfg = cfg; this.filter = filter; this.cha = cha; } @Override public boolean hasExceptionalEdge(Block src, Block dst) { boolean hasExceptionalEdge = this.cfg.getExceptionalSuccessors(src).contains(dst); final SSAInstruction relevantInstruction = src.getLastInstruction(); if (hasExceptionalEdge && relevantInstruction != null) { if (weKnowAllExceptions(relevantInstruction)) { final Collection<TypeReference> thrownExceptions = relevantInstruction.getExceptionTypes(); final Collection<FilteredException> filteredExceptions = this.filter.filteredExceptions(relevantInstruction); final boolean isFiltered = ExceptionMatcher.isFiltered(thrownExceptions, filteredExceptions, this.cha); hasExceptionalEdge = !isFiltered; } } return hasExceptionalEdge; } @Override public boolean hasNormalEdge(Block src, Block dst) { boolean result = true; if (src.getLastInstructionIndex() >= 0) { final SSAInstruction relevantInstruction = src.getLastInstruction(); if (relevantInstruction != null && this.filter.alwaysThrowsException(relevantInstruction)) { result = false; } } return result && this.cfg.getNormalSuccessors(src).contains(dst); } /** * SSAInstruction::getExceptionTypes() does not return exceptions thrown by throw or invoke * instructions, so we may not remove edges from those instructions, even if all exceptions * returned by instruction.getExceptionTypes() are to be filtered. * * @return if we know all exceptions, that can occur at this address from getExceptionTypes() */ private static boolean weKnowAllExceptions(SSAInstruction instruction) { return !((instruction instanceof SSAAbstractInvokeInstruction) || (instruction instanceof SSAAbstractThrowInstruction)); } }
2,855
35.151899
100
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/ipa/cfg/exceptionpruning/ExceptionMatcher.java
package com.ibm.wala.ipa.cfg.exceptionpruning; import com.ibm.wala.classLoader.IClass; import com.ibm.wala.ipa.cha.ClassHierarchy; import com.ibm.wala.types.TypeReference; import java.util.Collection; import java.util.LinkedHashSet; import java.util.Set; /** * Helper class to check if an exception is part of a set of filtered exceptions. * * @author Stephan Gocht {@code <stephan@gobro.de>} */ public class ExceptionMatcher { /** @return true, iff thrownExceptions is part of filteredExceptions */ public static boolean isFiltered( Collection<TypeReference> thrownExceptions, Collection<FilteredException> filteredExceptions, ClassHierarchy cha) { final ExceptionMatcher matcher = new ExceptionMatcher(thrownExceptions, filteredExceptions, cha); return matcher.areAllExceptionsIgnored(); } /** * Returns all exceptions of thrownExceptions which are not filtered by filteredExceptions * * @return all exceptions of thrownExceptions which are not filtered by filteredExceptions */ public static Set<TypeReference> retainedExceptions( Collection<TypeReference> thrownExceptions, Collection<FilteredException> filteredExceptions, ClassHierarchy cha) { final ExceptionMatcher matcher = new ExceptionMatcher(thrownExceptions, filteredExceptions, cha); return matcher.getRetainedExceptions(); } private Set<TypeReference> ignoreExact; private Set<TypeReference> ignoreSubclass; private final Set<TypeReference> retainedExceptions; private ClassHierarchy cha; private final boolean areAllExceptionsIgnored; private ExceptionMatcher( Collection<TypeReference> thrownExceptions, Collection<FilteredException> filteredExceptions, ClassHierarchy cha) { this.ignoreExact = new LinkedHashSet<>(); this.ignoreSubclass = new LinkedHashSet<>(); this.cha = cha; this.retainedExceptions = new LinkedHashSet<>(); this.fillIgnore(filteredExceptions); this.computeRetainedExceptions(thrownExceptions); this.areAllExceptionsIgnored = this.retainedExceptions.isEmpty(); this.free(); } private void computeRetainedExceptions(Collection<TypeReference> thrownExceptions) { for (final TypeReference exception : thrownExceptions) { if (!this.isFiltered(exception)) { this.retainedExceptions.add(exception); } } } private boolean areAllExceptionsIgnored() { return this.areAllExceptionsIgnored; } private void fillIgnore(Collection<FilteredException> filteredExceptions) { for (final FilteredException filteredException : filteredExceptions) { final TypeReference exception = filteredException.getException(); this.ignoreExact.add(exception); if (filteredException.isSubclassFiltered()) { this.ignoreSubclass.add(exception); } } } private void free() { this.ignoreExact = null; this.ignoreSubclass = null; this.cha = null; } /** * Check if the exception itself is filtered or if it is derived from a filtered exception. * * @return if the exception is filtered */ private boolean isFiltered(TypeReference exception) { boolean isFiltered = false; if (this.ignoreExact.contains(exception)) { isFiltered = true; } else { for (final TypeReference ignoreException : this.ignoreSubclass) { final IClass exceptionClass = this.cha.lookupClass(exception); final IClass ignoreClass = this.cha.lookupClass(ignoreException); if (this.cha.isAssignableFrom(ignoreClass, exceptionClass)) { isFiltered = true; break; } } } return isFiltered; } public Set<TypeReference> getRetainedExceptions() { return retainedExceptions; } }
3,776
30.475
93
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/ipa/cfg/exceptionpruning/FilteredException.java
package com.ibm.wala.ipa.cfg.exceptionpruning; import com.ibm.wala.types.TypeReference; /** * FilteredException represents either a single exception or an exception and all its subclasses. * * @author Stephan Gocht {@code <stephan@gobro.de>} */ public class FilteredException { public static final boolean FILTER_SUBCLASSES = true; private final TypeReference exception; private final boolean isSubclassFiltered; public FilteredException(TypeReference exception) { this(exception, false); } public FilteredException(TypeReference exception, boolean isSubclassFiltered) { super(); this.exception = exception; this.isSubclassFiltered = isSubclassFiltered; } public TypeReference getException() { return this.exception; } public boolean isSubclassFiltered() { return this.isSubclassFiltered; } }
850
24.029412
97
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/ipa/cfg/exceptionpruning/package-info.java
/** * If we want to filter edges of a control flow graph we already have {@link * com.ibm.wala.ipa.cfg.EdgeFilter}, but if we want to remove exceptions in particular we may want * to combine different analysis. Therefore we need a possibility to collect a set of removed * exceptions, so that an exceptional edge may be removed as soon as all exceptions, which can occur * along these edge are filtered. * * <p>This package contains classes for this job and also adapter for some analysis. * * @author Stephan Gocht {@code <stephan@gobro.de>} */ package com.ibm.wala.ipa.cfg.exceptionpruning;
603
45.461538
100
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/ipa/cfg/exceptionpruning/filter/ArrayOutOfBoundFilter.java
package com.ibm.wala.ipa.cfg.exceptionpruning.filter; import com.ibm.wala.analysis.arraybounds.ArrayOutOfBoundsAnalysis; import com.ibm.wala.analysis.arraybounds.ArrayOutOfBoundsAnalysis.UnnecessaryCheck; import com.ibm.wala.ipa.cfg.exceptionpruning.ExceptionFilter; import com.ibm.wala.ipa.cfg.exceptionpruning.FilteredException; import com.ibm.wala.ssa.SSAInstruction; import com.ibm.wala.types.TypeReference; import java.util.Collection; import java.util.Collections; /** * Adapter for using {@link ArrayOutOfBoundsAnalysis}. This filter is filtering * ArrayOutOfBoundException, which can not occur. * * @author Stephan Gocht {@code <stephan@gobro.de>} */ public class ArrayOutOfBoundFilter implements ExceptionFilter<SSAInstruction> { private final ArrayOutOfBoundsAnalysis analysis; public ArrayOutOfBoundFilter(ArrayOutOfBoundsAnalysis analysis) { this.analysis = analysis; } @Override public boolean alwaysThrowsException(SSAInstruction instruction) { return false; } @Override public Collection<FilteredException> filteredExceptions(SSAInstruction instruction) { final UnnecessaryCheck unnecessary = this.analysis.getBoundsCheckNecessary().get(instruction); if (unnecessary == UnnecessaryCheck.BOTH) { return Collections.singletonList( new FilteredException(TypeReference.JavaLangArrayIndexOutOfBoundsException)); } else { return Collections.emptyList(); } } }
1,443
34.219512
98
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/ipa/cfg/exceptionpruning/filter/CombinedExceptionFilter.java
package com.ibm.wala.ipa.cfg.exceptionpruning.filter; import com.ibm.wala.ipa.cfg.exceptionpruning.ExceptionFilter; import com.ibm.wala.ipa.cfg.exceptionpruning.FilteredException; import java.util.ArrayList; import java.util.Collection; /** * Use this class to combine multiple {@link ExceptionFilter} * * @author Stephan Gocht {@code <stephan@gobro.de>} */ public class CombinedExceptionFilter<Instruction> implements ExceptionFilter<Instruction> { private final Collection<ExceptionFilter<Instruction>> exceptionFilter; public CombinedExceptionFilter() { this.exceptionFilter = new ArrayList<>(); } public CombinedExceptionFilter(Collection<ExceptionFilter<Instruction>> exceptionFilter) { this.exceptionFilter = exceptionFilter; } public boolean add(ExceptionFilter<Instruction> e) { return this.exceptionFilter.add(e); } public boolean addAll(Collection<? extends ExceptionFilter<Instruction>> c) { return this.exceptionFilter.addAll(c); } @Override public boolean alwaysThrowsException(Instruction instruction) { boolean result = false; for (final ExceptionFilter<Instruction> filter : this.exceptionFilter) { result |= filter.alwaysThrowsException(instruction); } return result; } @Override public Collection<FilteredException> filteredExceptions(Instruction instruction) { final ArrayList<FilteredException> result = new ArrayList<>(); for (final ExceptionFilter<Instruction> filter : this.exceptionFilter) { result.addAll(filter.filteredExceptions(instruction)); } return result; } }
1,596
29.711538
92
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/ipa/cfg/exceptionpruning/filter/DummyFilter.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 com.ibm.wala.ipa.cfg.exceptionpruning.filter; import com.ibm.wala.ipa.cfg.exceptionpruning.ExceptionFilter; import com.ibm.wala.ipa.cfg.exceptionpruning.FilteredException; import java.util.Collection; import java.util.Collections; public class DummyFilter<Instruction> implements ExceptionFilter<Instruction> { @Override public boolean alwaysThrowsException(Instruction instruction) { return false; } @Override public Collection<FilteredException> filteredExceptions(Instruction instruction) { return Collections.emptyList(); } }
929
31.068966
84
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/ipa/cfg/exceptionpruning/filter/IgnoreExceptionsFilter.java
package com.ibm.wala.ipa.cfg.exceptionpruning.filter; import com.ibm.wala.ipa.cfg.exceptionpruning.ExceptionFilter; import com.ibm.wala.ipa.cfg.exceptionpruning.FilteredException; import com.ibm.wala.ssa.SSAInstruction; import com.ibm.wala.types.TypeReference; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; /** * For filtering specific exceptions. * * @author Stephan Gocht {@code <stephan@gobro.de>} */ public class IgnoreExceptionsFilter implements ExceptionFilter<SSAInstruction> { private final Collection<FilteredException> toBeIgnored; /** All given exceptions and subclasses will be ignored. */ public IgnoreExceptionsFilter(Collection<TypeReference> toBeIgnored) { this.toBeIgnored = new ArrayList<>(); this.addAll(toBeIgnored); } /** The given exception and subclasses will be ignored. */ public IgnoreExceptionsFilter(TypeReference toBeIgnored) { this.toBeIgnored = new ArrayList<>(); this.addAll(Collections.singletonList(toBeIgnored)); } private void addAll(Collection<TypeReference> toBeIgnored) { for (final TypeReference ignored : toBeIgnored) { this.toBeIgnored.add(new FilteredException(ignored, FilteredException.FILTER_SUBCLASSES)); } } @Override public boolean alwaysThrowsException(SSAInstruction instruction) { return false; } @Override public Collection<FilteredException> filteredExceptions(SSAInstruction instruction) { return this.toBeIgnored; } }
1,496
29.55102
96
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/ipa/cfg/exceptionpruning/filter/NullPointerExceptionFilter.java
package com.ibm.wala.ipa.cfg.exceptionpruning.filter; import com.ibm.wala.analysis.nullpointer.IntraproceduralNullPointerAnalysis; import com.ibm.wala.cfg.exc.intra.NullPointerState.State; import com.ibm.wala.ipa.cfg.exceptionpruning.ExceptionFilter; import com.ibm.wala.ipa.cfg.exceptionpruning.FilteredException; import com.ibm.wala.ssa.SSAInstruction; import com.ibm.wala.types.TypeReference; import java.util.Collection; import java.util.Collections; /** * Adapter for {@link IntraproceduralNullPointerAnalysis}. This filter is filtering * NullPointerException, which can not occur. * * @author Stephan Gocht {@code <stephan@gobro.de>} */ public class NullPointerExceptionFilter implements ExceptionFilter<SSAInstruction> { private final IntraproceduralNullPointerAnalysis analysis; public NullPointerExceptionFilter(IntraproceduralNullPointerAnalysis analysis) { this.analysis = analysis; } @Override public boolean alwaysThrowsException(SSAInstruction instruction) { return this.analysis.nullPointerExceptionThrowState(instruction) == State.NULL; } @Override public Collection<FilteredException> filteredExceptions(SSAInstruction instruction) { if (this.analysis.nullPointerExceptionThrowState(instruction) == State.NOT_NULL) { return Collections.singletonList( new FilteredException(TypeReference.JavaLangNullPointerException)); } else { return Collections.emptyList(); } } }
1,453
35.35
87
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/ipa/cfg/exceptionpruning/filter/package-info.java
/** * All available filters should be contained in this package. * * @author Stephan Gocht {@code <stephan@gobro.de>} */ package com.ibm.wala.ipa.cfg.exceptionpruning.filter;
179
24.714286
61
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/ipa/cfg/exceptionpruning/interprocedural/ArrayOutOfBoundInterFilter.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 com.ibm.wala.ipa.cfg.exceptionpruning.interprocedural; import com.ibm.wala.analysis.arraybounds.ArrayOutOfBoundsAnalysis; import com.ibm.wala.ipa.callgraph.CGNode; import com.ibm.wala.ipa.cfg.exceptionpruning.ExceptionFilter; import com.ibm.wala.ipa.cfg.exceptionpruning.filter.ArrayOutOfBoundFilter; import com.ibm.wala.ssa.SSAInstruction; public class ArrayOutOfBoundInterFilter extends StoringExceptionFilter<SSAInstruction> { @Override protected ExceptionFilter<SSAInstruction> computeFilter(CGNode node) { ArrayOutOfBoundsAnalysis analysis = new ArrayOutOfBoundsAnalysis(node.getIR()); return new ArrayOutOfBoundFilter(analysis); } }
1,032
37.259259
88
java