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/cfg/exceptionpruning/interprocedural/CombinedInterproceduralExceptionFilter.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.ipa.callgraph.CGNode;
import com.ibm.wala.ipa.cfg.exceptionpruning.ExceptionFilter;
import com.ibm.wala.ipa.cfg.exceptionpruning.filter.CombinedExceptionFilter;
import java.util.ArrayList;
import java.util.Collection;
public class CombinedInterproceduralExceptionFilter<Instruction>
implements InterproceduralExceptionFilter<Instruction> {
private final Collection<InterproceduralExceptionFilter<Instruction>> filter;
public CombinedInterproceduralExceptionFilter() {
this.filter = new ArrayList<>();
}
public CombinedInterproceduralExceptionFilter(
Collection<InterproceduralExceptionFilter<Instruction>> filter) {
this.filter = filter;
}
public boolean add(InterproceduralExceptionFilter<Instruction> e) {
return this.filter.add(e);
}
public boolean addAll(Collection<? extends InterproceduralExceptionFilter<Instruction>> c) {
return this.filter.addAll(c);
}
@Override
public ExceptionFilter<Instruction> getFilter(CGNode node) {
CombinedExceptionFilter<Instruction> result = new CombinedExceptionFilter<>();
for (InterproceduralExceptionFilter<Instruction> exceptionFilter : filter) {
result.add(exceptionFilter.getFilter(node));
}
return result;
}
}
| 1,686
| 32.74
| 94
|
java
|
WALA
|
WALA-master/core/src/main/java/com/ibm/wala/ipa/cfg/exceptionpruning/interprocedural/IgnoreExceptionsInterFilter.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.ipa.callgraph.CGNode;
import com.ibm.wala.ipa.cfg.exceptionpruning.ExceptionFilter;
public class IgnoreExceptionsInterFilter<Instruction>
implements InterproceduralExceptionFilter<Instruction> {
private final ExceptionFilter<Instruction> filter;
public IgnoreExceptionsInterFilter(ExceptionFilter<Instruction> filter) {
this.filter = filter;
}
@Override
public ExceptionFilter<Instruction> getFilter(CGNode node) {
return filter;
}
}
| 913
| 30.517241
| 75
|
java
|
WALA
|
WALA-master/core/src/main/java/com/ibm/wala/ipa/cfg/exceptionpruning/interprocedural/InterproceduralExceptionFilter.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.ipa.callgraph.CGNode;
import com.ibm.wala.ipa.cfg.exceptionpruning.ExceptionFilter;
public interface InterproceduralExceptionFilter<Instruction> {
ExceptionFilter<Instruction> getFilter(CGNode node);
}
| 657
| 33.631579
| 72
|
java
|
WALA
|
WALA-master/core/src/main/java/com/ibm/wala/ipa/cfg/exceptionpruning/interprocedural/NullPointerExceptionInterFilter.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.nullpointer.IntraproceduralNullPointerAnalysis;
import com.ibm.wala.ipa.callgraph.CGNode;
import com.ibm.wala.ipa.cfg.exceptionpruning.ExceptionFilter;
import com.ibm.wala.ipa.cfg.exceptionpruning.filter.NullPointerExceptionFilter;
import com.ibm.wala.ssa.SSAInstruction;
public class NullPointerExceptionInterFilter extends StoringExceptionFilter<SSAInstruction> {
@Override
protected ExceptionFilter<SSAInstruction> computeFilter(CGNode node) {
IntraproceduralNullPointerAnalysis analysis =
new IntraproceduralNullPointerAnalysis(node.getIR());
return new NullPointerExceptionFilter(analysis);
}
}
| 1,085
| 37.785714
| 93
|
java
|
WALA
|
WALA-master/core/src/main/java/com/ibm/wala/ipa/cfg/exceptionpruning/interprocedural/StoringExceptionFilter.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.ipa.callgraph.CGNode;
import com.ibm.wala.ipa.cfg.exceptionpruning.ExceptionFilter;
import java.util.LinkedHashMap;
import java.util.Map;
public abstract class StoringExceptionFilter<Instruction>
implements InterproceduralExceptionFilter<Instruction> {
private final Map<CGNode, ExceptionFilter<Instruction>> store;
public StoringExceptionFilter() {
this.store = new LinkedHashMap<>();
}
protected abstract ExceptionFilter<Instruction> computeFilter(CGNode node);
@Override
public ExceptionFilter<Instruction> getFilter(CGNode node) {
if (store.containsKey(node)) {
return store.get(node);
} else {
ExceptionFilter<Instruction> filter = computeFilter(node);
store.put(node, filter);
return filter;
}
}
}
| 1,218
| 30.25641
| 77
|
java
|
WALA
|
WALA-master/core/src/main/java/com/ibm/wala/ipa/cfg/exceptionpruning/interprocedural/package-info.java
|
/** @author stephan */
package com.ibm.wala.ipa.cfg.exceptionpruning.interprocedural;
| 86
| 28
| 62
|
java
|
WALA
|
WALA-master/core/src/main/java/com/ibm/wala/ipa/cha/CancelCHAConstructionException.java
|
/*
* Copyright (c) 2006 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.ipa.cha;
/**
* Exception class that indicates that construction of class hierarchy has been cancelled by a
* progress monitor.
*/
public final class CancelCHAConstructionException extends ClassHierarchyException {
private static final long serialVersionUID = -1987107302523285889L;
public CancelCHAConstructionException() {
super("class hierarchy construction was cancelled");
}
}
| 787
| 29.307692
| 94
|
java
|
WALA
|
WALA-master/core/src/main/java/com/ibm/wala/ipa/cha/ClassHierarchy.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.cha;
import com.ibm.wala.classLoader.ArrayClass;
import com.ibm.wala.classLoader.BytecodeClass;
import com.ibm.wala.classLoader.ClassLoaderFactory;
import com.ibm.wala.classLoader.IClass;
import com.ibm.wala.classLoader.IClassLoader;
import com.ibm.wala.classLoader.IField;
import com.ibm.wala.classLoader.IMethod;
import com.ibm.wala.classLoader.Language;
import com.ibm.wala.classLoader.NoSuperclassFoundException;
import com.ibm.wala.classLoader.PhantomClass;
import com.ibm.wala.classLoader.ShrikeClass;
import com.ibm.wala.core.util.ref.CacheReference;
import com.ibm.wala.core.util.ref.ReferenceCleanser;
import com.ibm.wala.core.util.strings.Atom;
import com.ibm.wala.core.util.warnings.Warning;
import com.ibm.wala.core.util.warnings.Warnings;
import com.ibm.wala.ipa.callgraph.AnalysisScope;
import com.ibm.wala.types.ClassLoaderReference;
import com.ibm.wala.types.FieldReference;
import com.ibm.wala.types.MethodReference;
import com.ibm.wala.types.Selector;
import com.ibm.wala.types.TypeName;
import com.ibm.wala.types.TypeReference;
import com.ibm.wala.util.MonitorUtil.IProgressMonitor;
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.Iterator2Iterable;
import com.ibm.wala.util.collections.MapIterator;
import com.ibm.wala.util.collections.MapUtil;
import com.ibm.wala.util.debug.Assertions;
import com.ibm.wala.util.debug.UnimplementedError;
import java.io.IOException;
import java.util.Collection;
import java.util.Collections;
import java.util.ConcurrentModificationException;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Function;
/**
* Simple implementation of a class hierarchy.
*
* <p>Note that this class hierarchy implementation is mutable. You can add classes via addClass().
* You can add a class even if c.getClassLoader() does not appear in getLoaders().
*/
public class ClassHierarchy implements IClassHierarchy {
private static final boolean DEBUG = false;
public enum MissingSuperClassHandling {
NONE,
ROOT,
PHANTOM
}
/**
* Languages that contribute classes to the set represented in this hierarchy. The languages may
* for example be related by inheritance (e.g. X10 derives from Java, and shares a common type
* hierarchy rooted at java.lang.Object).
*/
private final Set<Language> languages = HashSetFactory.make();
/**
* For each {@link IClass} c in this class hierarchy, this map maps c.getReference() to the {@link
* Node}
*
* <p>Note that this class provides an iterator() over this map, and that some WALA utilities
* (e.g. ReferenceCleanser) must iterate over all classes. But also note that the class hierarchy
* is mutable (addClass()). So, when trying to run multiple threads, we could see a race condition
* between iterator() and addClass(). With a normal {@link HashMap}, this would result in a {@link
* ConcurrentModificationException}. But with a {@link ConcurrentHashMap}, at least the code
* merrily chugs along, tolerating the race.
*/
private final Map<TypeReference, Node> map;
/** {@link TypeReference} for the root type */
private TypeReference rootTypeRef;
/** root node of the class hierarchy */
private Node root;
/** An object which defines class loaders. */
private final ClassLoaderFactory factory;
/** The loaders used to define this class hierarchy. */
private final IClassLoader[] loaders;
/** A mapping from IClass -> Selector -> Set of IMethod */
private final HashMap<IClass, Object> targetCache = HashMapFactory.make();
/** Governing analysis scope */
private final AnalysisScope scope;
/**
* A mapping from IClass (representing an interface) -> Set of IClass that implement that
* interface
*/
private final Map<IClass, Set<IClass>> implementors = HashMapFactory.make();
/** A temporary hack : TODO: do intelligent caching somehow */
private Collection<IClass> subclassesOfError;
/** A temporary hack : TODO: do intelligent caching somehow */
private Collection<TypeReference> subTypeRefsOfError;
/** A temporary hack : TODO: do intelligent caching somehow */
private Collection<IClass> runtimeExceptionClasses;
/** A temporary hack : TODO: do intelligent caching somehow */
private Collection<TypeReference> runtimeExceptionTypeRefs;
/**
* How should we handle missing superclasses? DEFAULT: no special handling, class will be excluded
* from class hierarchy ROOT: replace the missing superclass with the hierarchy root PHANTOM:
* create a phantom superclass and add the subclass to the hierarchy. Note that we can only create
* phantom superclass when the class is a {@link com.ibm.wala.classLoader.BytecodeClass}
*/
private final MissingSuperClassHandling superClassHandling;
/**
* Return a set of {@link IClass} that holds all superclasses of klass
*
* @param klass class in question
* @return Set the result set
*/
private Set<IClass> computeSuperclasses(IClass klass) {
if (DEBUG) {
System.err.println("computeSuperclasses: " + klass);
}
Set<IClass> result = HashSetFactory.make(3);
try {
klass = klass.getSuperclass();
while (klass != null) {
if (DEBUG) {
System.err.println("got superclass " + klass);
}
boolean added = result.add(klass);
if (!added) {
// oops. we have A is a sub-class of B and B is a sub-class of A. blow up.
throw new IllegalStateException("cycle in the extends relation for class " + klass);
}
klass = klass.getSuperclass();
if (klass != null && klass.getReference().getName().equals(rootTypeRef.getName())) {
if (!klass.getReference().getClassLoader().equals(rootTypeRef.getClassLoader())) {
throw new IllegalStateException(
"class " + klass + " is invalid, unexpected classloader");
}
}
}
} catch (NoSuperclassFoundException e) {
if (!superClassHandling.equals(MissingSuperClassHandling.NONE)
&& klass instanceof BytecodeClass) {
if (superClassHandling.equals(MissingSuperClassHandling.PHANTOM)) {
// create a phantom superclass. add it and the root class to the result
IClass phantom = getPhantomSuperclass((BytecodeClass<?>) klass);
result.add(phantom);
}
result.add(getRootClass());
} else {
throw e;
}
}
return result;
}
ClassHierarchy(
AnalysisScope scope,
ClassLoaderFactory factory,
Language language,
IProgressMonitor progressMonitor,
Map<TypeReference, Node> map,
MissingSuperClassHandling superClassHandling)
throws ClassHierarchyException, IllegalArgumentException {
this(scope, factory, Collections.singleton(language), progressMonitor, map, superClassHandling);
}
ClassHierarchy(
AnalysisScope scope,
ClassLoaderFactory factory,
IProgressMonitor progressMonitor,
Map<TypeReference, Node> map,
MissingSuperClassHandling superClassHandling)
throws ClassHierarchyException, IllegalArgumentException {
this(scope, factory, scope.getLanguages(), progressMonitor, map, superClassHandling);
}
ClassHierarchy(
AnalysisScope scope,
ClassLoaderFactory factory,
Collection<Language> languages,
IProgressMonitor progressMonitor,
Map<TypeReference, Node> map,
MissingSuperClassHandling superClassHandling)
throws ClassHierarchyException, IllegalArgumentException {
// now is a good time to clear the warnings globally.
// TODO: think of a better way to guard against warning leaks.
Warnings.clear();
this.map = map;
this.superClassHandling = superClassHandling;
if (factory == null) {
throw new IllegalArgumentException();
}
if (scope.getLanguages().size() == 0) {
throw new IllegalArgumentException("AnalysisScope must contain at least 1 language");
}
this.scope = scope;
this.factory = factory;
Set<Atom> langNames = HashSetFactory.make();
for (Language lang : languages) {
this.languages.add(lang);
this.languages.addAll(lang.getDerivedLanguages());
langNames.add(lang.getName());
}
for (Language lang : this.languages) {
if (lang.getRootType() != null && lang.getRootType() != this.rootTypeRef) {
if (this.rootTypeRef != null) {
throw new IllegalArgumentException(
"AnalysisScope must have only 1 root type: "
+ lang.getRootType()
+ ", "
+ rootTypeRef);
} else {
this.rootTypeRef = lang.getRootType();
}
}
}
try {
int numLoaders = 0;
for (ClassLoaderReference ref : scope.getLoaders()) {
if (langNames.contains(ref.getLanguage())) {
numLoaders++;
}
}
loaders = new IClassLoader[numLoaders];
int idx = 0;
if (progressMonitor != null) {
progressMonitor.beginTask("Build Class Hierarchy", numLoaders * 2 - 1);
}
for (ClassLoaderReference ref : scope.getLoaders()) {
if (progressMonitor != null) {
if (progressMonitor.isCanceled()) {
throw new CancelCHAConstructionException();
}
}
if (langNames.contains(ref.getLanguage())) {
IClassLoader icl = factory.getLoader(ref, this, scope);
loaders[idx++] = icl;
if (progressMonitor != null) {
progressMonitor.worked(idx);
}
}
}
for (IClassLoader icl : loaders) {
if (progressMonitor != null) {
progressMonitor.subTask("From " + icl.getName().toString());
}
addAllClasses(icl, progressMonitor);
if (progressMonitor != null) {
progressMonitor.worked(idx++);
}
}
} catch (Exception e) {
throw new ClassHierarchyException("factory.getLoader failed", e);
} finally {
if (progressMonitor != null) {
progressMonitor.done(); // In case an exception is thrown.
}
}
if (root == null) {
throw new ClassHierarchyException(
"failed to load root " + rootTypeRef + " of class hierarchy");
}
// perform numbering for subclass tests.
numberTree();
ReferenceCleanser.registerClassHierarchy(this);
}
/** Add all classes in a class loader to the hierarchy. */
private void addAllClasses(IClassLoader loader, IProgressMonitor progressMonitor)
throws CancelCHAConstructionException {
if (DEBUG) {
System.err.println(("Add all classes from loader " + loader));
}
Collection<IClass> toRemove = HashSetFactory.make();
for (IClass klass : Iterator2Iterable.make(loader.iterateAllClasses())) {
if (progressMonitor != null) {
if (progressMonitor.isCanceled()) {
throw new CancelCHAConstructionException();
}
}
boolean added = addClass(klass);
if (!added) {
toRemove.add(klass);
}
}
loader.removeAll(toRemove);
}
/**
* @return true if the add succeeded; false if it failed for some reason
* @throws IllegalArgumentException if klass is null
*/
@Override
public boolean addClass(IClass klass) {
if (klass == null) {
throw new IllegalArgumentException("klass is null");
}
if (klass.getReference().getName().equals(rootTypeRef.getName())) {
if (!klass.getReference().getClassLoader().equals(rootTypeRef.getClassLoader())) {
throw new IllegalArgumentException(
"class " + klass + " is invalid, unexpected classloader");
}
}
if (DEBUG) {
System.err.println(("Attempt to add class " + klass));
}
Set<IClass> loadedSuperclasses = null;
Collection<IClass> loadedSuperInterfaces;
try {
loadedSuperclasses = computeSuperclasses(klass);
loadedSuperInterfaces = klass.getAllImplementedInterfaces();
} catch (Exception e) {
if (!superClassHandling.equals(MissingSuperClassHandling.NONE)
&& e instanceof NoSuperclassFoundException) {
// this must have been thrown by the getAllImplementedInterfaces() call.
// for now, just pretend it implements no interfaces
loadedSuperInterfaces = Collections.emptySet();
} else {
// a little cleanup
if (klass instanceof ShrikeClass) {
if (DEBUG) {
System.err.println(("Exception. Clearing " + klass));
}
}
Warnings.add(ClassExclusion.create(klass.getReference(), e.getMessage()));
return false;
}
}
Node node = findOrCreateNode(klass);
if (klass.getReference().equals(this.rootTypeRef)) {
// there is only one root
assert root == null || root == node;
root = node;
}
HashSet<IClass> workingSuperclasses = HashSetFactory.make(loadedSuperclasses);
while (node != null) {
IClass c = node.getJavaClass();
IClass superclass;
try {
superclass = c.getSuperclass();
} catch (NoSuperclassFoundException e) {
assert !superClassHandling.equals(MissingSuperClassHandling.NONE);
if (superClassHandling.equals(MissingSuperClassHandling.ROOT)) superclass = getRootClass();
else superclass = getPhantomSuperclass((BytecodeClass<?>) c);
}
if (superclass != null) {
workingSuperclasses.remove(superclass);
Node supernode = findOrCreateNode(superclass);
if (DEBUG) {
System.err.println(
("addChild " + node.getJavaClass() + " to " + supernode.getJavaClass()));
}
supernode.addChild(node);
if (supernode.getJavaClass().getReference().equals(rootTypeRef)) {
assert root == null || root == supernode;
root = supernode;
node = null;
} else {
node = supernode;
}
} else {
node = null;
}
}
if (loadedSuperInterfaces != null) {
for (IClass iface : loadedSuperInterfaces) {
try {
// make sure we'll be able to load the interface!
computeSuperclasses(iface);
} catch (IllegalStateException e) {
Warnings.add(ClassExclusion.create(iface.getReference(), e.getMessage()));
continue;
}
if (!iface.isInterface()) {
Warnings.add(
new Warning() {
@Override
public String getMsg() {
return "class implements non-interface "
+ iface.getReference()
+ " as an interface";
}
});
continue;
}
recordImplements(klass, iface);
}
}
return true;
}
private IClass getPhantomSuperclass(BytecodeClass<?> klass) {
ClassLoaderReference loader = klass.getReference().getClassLoader();
TypeName superName = klass.getSuperName();
TypeReference superRef = TypeReference.findOrCreate(loader, superName);
IClass superClass = lookupClass(superRef);
if (superClass == null) {
superClass = new PhantomClass(superRef, this);
addClass(superClass);
}
return superClass;
}
/** Record that a klass implements a particular interface */
private void recordImplements(IClass klass, IClass iface) {
Set<IClass> impls = MapUtil.findOrCreateSet(implementors, iface);
impls.add(klass);
}
/**
* Find the possible targets of a call to a method reference. Note that if the reference is to an
* instance initialization method, we assume the method was called with invokespecial rather than
* invokevirtual.
*
* @param ref method reference
* @return the set of IMethods that this call can resolve to.
* @throws IllegalArgumentException if ref is null
*/
@Override
public Set<IMethod> getPossibleTargets(MethodReference ref) {
if (ref == null) {
throw new IllegalArgumentException("ref is null");
}
IClassLoader loader;
try {
loader = factory.getLoader(ref.getDeclaringClass().getClassLoader(), this, scope);
} catch (IOException e) {
throw new UnimplementedError("factory.getLoader failed " + e);
}
IClass declaredClass;
declaredClass = loader.lookupClass(ref.getDeclaringClass().getName());
if (declaredClass == null) {
return Collections.emptySet();
}
Set<IMethod> targets = HashSetFactory.make();
targets.addAll(findOrCreateTargetSet(declaredClass, ref));
return targets;
}
/**
* Find the possible targets of a call to a method reference
*
* @param ref method reference
* @return the set of IMethods that this call can resolve to.
*/
@SuppressWarnings("unchecked")
private Set<IMethod> findOrCreateTargetSet(IClass declaredClass, MethodReference ref) {
Map<MethodReference, Set<IMethod>> classCache =
(Map<MethodReference, Set<IMethod>>) CacheReference.get(targetCache.get(declaredClass));
if (classCache == null) {
classCache = HashMapFactory.make(3);
targetCache.put(declaredClass, CacheReference.make(classCache));
}
Set<IMethod> result = classCache.get(ref);
if (result == null) {
result = getPossibleTargets(declaredClass, ref);
classCache.put(ref, result);
}
return result;
}
/**
* Find the possible receivers of a call to a method reference
*
* @param ref method reference
* @return the set of IMethods that this call can resolve to.
*/
@Override
public Set<IMethod> getPossibleTargets(IClass declaredClass, MethodReference ref) {
if (ref.getName().equals(MethodReference.initAtom)) {
// for an object init method, use the method alone as a possible target,
// rather than inspecting subclasses
IMethod resolvedMethod = resolveMethod(ref);
assert resolvedMethod != null;
return Collections.singleton(resolvedMethod);
}
if (declaredClass.isInterface()) {
HashSet<IMethod> result = HashSetFactory.make(3);
Set<IClass> impls = implementors.get(declaredClass);
if (impls == null) {
// give up and return no receivers
return Collections.emptySet();
}
for (IClass klass : impls) {
if (!klass.isInterface() && !klass.isAbstract()) {
result.addAll(computeTargetsNotInterface(ref, klass));
}
}
return result;
} else {
return computeTargetsNotInterface(ref, declaredClass);
}
}
/**
* Get the targets for a method ref invoked on a class klass. The klass had better not be an
* interface.
*
* @param ref method to invoke
* @param klass declaringClass of receiver
* @return Set the set of method implementations that might receive the message
*/
private Set<IMethod> computeTargetsNotInterface(MethodReference ref, IClass klass) {
Node n = findNode(klass);
HashSet<IMethod> result = HashSetFactory.make(3);
// if n is null, then for some reason this class is excluded
// from the analysis. Return a result of no targets.
if (n == null) return result;
Selector selector = ref.getSelector();
// try to resolve the method by walking UP the class hierarchy
IMethod resolved = resolveMethod(klass, selector);
if (resolved != null) {
result.add(resolved);
}
// find any receivers that override the method with inheritance
result.addAll(computeOverriders(n, selector));
return result;
}
@Override
public IMethod resolveMethod(MethodReference m) {
if (m == null) {
throw new IllegalArgumentException("m is null");
}
IClass receiver = lookupClass(m.getDeclaringClass());
if (receiver == null) {
return null;
}
Selector selector = m.getSelector();
return resolveMethod(receiver, selector);
}
/**
* @return the canonical IField that represents a given field , or null if none found
* @throws IllegalArgumentException if f is null
*/
@Override
public IField resolveField(FieldReference f) {
if (f == null) {
throw new IllegalArgumentException("f is null");
}
IClass klass = lookupClass(f.getDeclaringClass());
if (klass == null) {
return null;
}
return resolveField(klass, f);
}
/**
* @return the canonical IField that represents a given field , or null if none found
* @throws IllegalArgumentException if f is null
* @throws IllegalArgumentException if klass is null
*/
@Override
public IField resolveField(IClass klass, FieldReference f) {
if (klass == null) {
throw new IllegalArgumentException("klass is null");
}
if (f == null) {
throw new IllegalArgumentException("f is null");
}
return klass.getField(f.getName(), f.getFieldType().getName());
}
@Override
public IMethod resolveMethod(IClass receiverClass, Selector selector) {
if (receiverClass == null) {
throw new IllegalArgumentException("receiverClass is null");
}
IMethod result = findMethod(receiverClass, selector);
if (result != null) {
return result;
} else {
IClass superclass = receiverClass.getSuperclass();
if (superclass == null) {
if (DEBUG) {
System.err.println(("resolveMethod(" + selector + ") failed: method not found"));
}
return null;
} else {
if (DEBUG) {
System.err.println(
("Attempt to resolve for "
+ receiverClass
+ " in superclass: "
+ superclass
+ ' '
+ selector));
}
return resolveMethod(superclass, selector);
}
}
}
/**
* Does a particular class contain (implement) a particular method?
*
* @param clazz class in question
* @param selector method selector
* @return the method if found, else null
*/
private static IMethod findMethod(IClass clazz, Selector selector) {
return clazz.getMethod(selector);
}
/**
* Get the set of subclasses of a class that provide implementations of a method
*
* @param node abstraction of class in question
* @param selector method signature
* @return Set set of IMethods that override the method
*/
private Set<IMethod> computeOverriders(Node node, Selector selector) {
HashSet<IMethod> result = HashSetFactory.make(3);
for (Node child : Iterator2Iterable.make(node.getChildren())) {
IMethod m = findMethod(child.getJavaClass(), selector);
if (m != null) {
result.add(m);
}
result.addAll(computeOverriders(child, selector));
}
return result;
}
private Node findNode(IClass klass) {
return map.get(klass.getReference());
}
private Node findOrCreateNode(IClass klass) {
Node result = map.get(klass.getReference());
if (result == null) {
result = new Node(klass);
map.put(klass.getReference(), result);
}
return result;
}
@Override
public String toString() {
StringBuilder result = new StringBuilder(100);
recursiveStringify(root, result);
return result.toString();
}
private void recursiveStringify(Node n, StringBuilder buffer) {
buffer.append(n.toString()).append('\n');
for (Node child : Iterator2Iterable.make(n.getChildren())) {
recursiveStringify(child, buffer);
}
}
/**
* Number the class hierarchy tree to support efficient subclass tests. After numbering the tree,
* n1 is a child of n2 iff n2.left <= n1.left ^ n1.left <= n2.right. Described as "relative
* numbering" by Vitek, Horspool, and Krall, OOPSLA 97
*
* <p>TODO: this implementation is recursive; un-recursify if needed
*/
private int nextNumber = 1;
private void numberTree() {
assert root != null;
visitForNumbering(root);
}
private void visitForNumbering(Node N) {
N.left = nextNumber++;
for (Node C : N.children) {
visitForNumbering(C);
}
N.right = nextNumber++;
}
/** internal representation of a node in the class hiearachy, representing one java class. */
static final class Node {
private final IClass klass;
private final Set<Node> children = HashSetFactory.make(3);
// the following two fields are used for efficient subclass tests.
// After numbering the tree, n1 is a child of n2 iff
// n2.left <= n1.left ^ n1.left <= n2.right.
// Described as "relative numbering" by Vitek, Horspool, and Krall, OOPSLA
// 97
private int left = -1;
private int right = -1;
Node(IClass klass) {
this.klass = klass;
}
boolean isInterface() {
return klass.isInterface();
}
IClass getJavaClass() {
return klass;
}
void addChild(Node child) {
children.add(child);
}
Iterator<Node> getChildren() {
return children.iterator();
}
@Override
public String toString() {
StringBuilder result = new StringBuilder(100);
result.append(klass.toString()).append(':');
for (Iterator<Node> i = children.iterator(); i.hasNext(); ) {
Node n = i.next();
result.append(n.klass.toString());
if (i.hasNext()) result.append(',');
}
return result.toString();
}
@Override
public int hashCode() {
return klass.hashCode() * 929;
}
@Override
public boolean equals(Object obj) {
return this == obj;
}
}
@Override
public ClassLoaderFactory getFactory() {
return factory;
}
/** @throws IllegalArgumentException if A is null */
@Override
public IClass getLeastCommonSuperclass(IClass a, IClass b) {
assert a.getClassLoader().getLanguage().equals(b.getClassLoader().getLanguage());
Language lang = a.getClassLoader().getLanguage();
TypeReference tempA = a.getReference();
if (a.equals(b)) {
return a;
} else if (tempA.equals(TypeReference.Null)) {
return b;
} else if (b.getReference().equals(TypeReference.Null)) {
return a;
} else if (b.getReference().equals(lang.getRootType())) {
return b;
} else {
Node n = map.get(b.getReference());
assert n != null : "null n for " + b;
Set<IClass> superB;
superB = getSuperclasses(b);
IClass aa = a;
while (aa != null) {
if (b.equals(aa) || superB.contains(aa)) {
return aa;
}
aa = aa.getSuperclass();
}
Set<IClass> superA;
superA = getSuperclasses(a);
Assertions.UNREACHABLE(
"getLeastCommonSuperclass " + tempA + ' ' + b + ": " + superA + ", " + superB);
return null;
}
}
private static Set<IClass> getSuperclasses(IClass c) {
HashSet<IClass> result = HashSetFactory.make(3);
while (c.getSuperclass() != null) {
result.add(c.getSuperclass());
c = c.getSuperclass();
}
return result;
}
@Override
public TypeReference getLeastCommonSuperclass(TypeReference a, TypeReference b) {
if (a == null) {
throw new IllegalArgumentException("a is null");
}
if (a.equals(b)) return a;
IClass aClass = lookupClass(a);
IClass bClass = lookupClass(b);
if (aClass == null || bClass == null) {
// One of the classes is not in scope. Give up.
if (aClass != null) {
return aClass.getClassLoader().getLanguage().getRootType();
} else if (bClass != null) {
return bClass.getClassLoader().getLanguage().getRootType();
} else {
return getRootClass().getReference();
}
}
return getLeastCommonSuperclass(aClass, bClass).getReference();
}
/**
* Find a class in this class hierarchy.
*
* @return the {@link IClass} for a if found; null if can't find the class.
* @throws IllegalArgumentException if A is null
*/
@Override
public IClass lookupClass(TypeReference a) {
if (a == null) {
throw new IllegalArgumentException("a is null");
}
/* BEGIN Custom change: remember unresolved classes */
final IClass cls = lookupClassRecursive(a);
if (cls == null) {
unresolved.add(a);
}
return cls;
}
private IClass lookupClassRecursive(TypeReference a) {
/* END Custom change: remember unresolved classes */
ClassLoaderReference loader = a.getClassLoader();
ClassLoaderReference parent = loader.getParent();
// first delegate lookup to the parent loader.
if (parent != null) {
TypeReference p = TypeReference.findOrCreate(parent, a.getName());
IClass c = lookupClassRecursive(p);
if (c != null) {
return c;
}
}
// lookup in the parent failed. lookup based on the declared loader of a.
if (a.isArrayType()) {
TypeReference elt = a.getInnermostElementType();
if (elt.isPrimitiveType()) {
// look it up with the primordial loader.
return getRootClass().getClassLoader().lookupClass(a.getName());
} else {
IClass c = lookupClassRecursive(elt);
if (c == null) {
// can't load the element class, so give up.
return null;
} else {
// we know it comes from c's class loader.
return c.getClassLoader().lookupClass(a.getName());
}
}
} else {
Node n = map.get(a);
if (n != null) {
return n.klass;
} else {
return null;
}
}
}
private boolean slowIsSubclass(IClass sub, IClass sup) {
if (sub == sup) {
return true;
} else {
IClass parent = sub.getSuperclass();
if (parent == null) {
return false;
} else {
return slowIsSubclass(parent, sup);
}
}
}
/**
* Is c a subclass of T?
*
* @throws IllegalArgumentException if c is null
*/
@Override
public boolean isSubclassOf(IClass c, IClass t) {
if (c == null) {
throw new IllegalArgumentException("c is null");
}
assert t != null : "null T";
if (c.isArrayClass()) {
if (t.getReference() == TypeReference.JavaLangObject) {
return true;
} else if (t.getReference().isArrayType()) {
TypeReference elementType = t.getReference().getArrayElementType();
if (elementType.isPrimitiveType()) {
return elementType.equals(c.getReference().getArrayElementType());
} else {
IClass elementKlass = lookupClass(elementType);
if (elementKlass == null) {
// uh oh.
Warnings.add(ClassHierarchyWarning.create("could not find " + elementType));
return false;
}
IClass ce = ((ArrayClass) c).getElementClass();
if (ce == null) {
return false;
}
if (elementKlass.isInterface()) {
return implementsInterface(ce, elementKlass);
} else {
return isSubclassOf(ce, elementKlass);
}
}
} else {
return false;
}
} else {
if (t.getReference().isArrayType()) {
return false;
}
if (c.getReference().equals(t.getReference())) {
return true;
}
Node n1 = map.get(c.getReference());
if (n1 == null) {
// some wacky case, like a FakeRootClass
return false;
}
Node n2 = map.get(t.getReference());
if (n2 == null) {
// some wacky case, like a FakeRootClass
return false;
}
if (n1.left == -1) {
return slowIsSubclass(c, t);
} else if (n2.left == -1) {
return slowIsSubclass(c, t);
} else {
return (n2.left <= n1.left) && (n1.left <= n2.right);
}
}
}
/**
* Does c implement i?
*
* @return true iff i is an interface and c is a class that implements i, or c is an interface
* that extends i.
*/
@Override
public boolean implementsInterface(IClass c, IClass i) {
if (i == null) {
throw new IllegalArgumentException("Cannot ask implementsInterface with i == null");
}
if (c == null) {
throw new IllegalArgumentException("Cannot ask implementsInterface with c == null");
}
if (!i.isInterface()) {
return false;
}
if (c.equals(i)) {
return true;
}
if (c.isArrayClass()) {
// arrays implement Cloneable and Serializable
return i.equals(lookupClass(TypeReference.JavaLangCloneable))
|| i.equals(lookupClass(TypeReference.JavaIoSerializable));
}
Set<IClass> impls = implementors.get(i);
if (impls != null && impls.contains(c)) {
return true;
}
return false;
}
/**
* Return set of all subclasses of type in the Class Hierarchy TODO: Tune this implementation.
* Consider caching if necessary.
*/
@Override
public Collection<IClass> computeSubClasses(TypeReference type) {
IClass t = lookupClass(type);
if (t == null) {
throw new IllegalArgumentException("could not find class for TypeReference " + type);
}
// a hack: TODO: work on better caching
if (t.getReference().equals(TypeReference.JavaLangError)) {
if (subclassesOfError == null) {
subclassesOfError = computeSubClassesInternal(t);
}
return subclassesOfError;
} else if (t.getReference().equals(TypeReference.JavaLangRuntimeException)) {
if (runtimeExceptionClasses == null) {
runtimeExceptionClasses = computeSubClassesInternal(t);
}
return runtimeExceptionClasses;
} else {
return computeSubClassesInternal(t);
}
}
/**
* Solely for optimization; return a Collection<TypeReference> representing the subclasses
* of Error
*
* <p>kind of ugly. a better scheme?
*/
@Override
public Collection<TypeReference> getJavaLangErrorTypes() {
if (subTypeRefsOfError == null) {
computeSubClasses(TypeReference.JavaLangError);
subTypeRefsOfError = HashSetFactory.make(subclassesOfError.size());
for (IClass klass : subclassesOfError) {
subTypeRefsOfError.add(klass.getReference());
}
}
return Collections.unmodifiableCollection(subTypeRefsOfError);
}
/**
* Solely for optimization; return a Collection<TypeReference> representing the subclasses
* of RuntimeException
*
* <p>kind of ugly. a better scheme?
*/
@Override
public Collection<TypeReference> getJavaLangRuntimeExceptionTypes() {
if (runtimeExceptionTypeRefs == null) {
computeSubClasses(TypeReference.JavaLangRuntimeException);
runtimeExceptionTypeRefs = HashSetFactory.make(runtimeExceptionClasses.size());
for (IClass klass : runtimeExceptionClasses) {
runtimeExceptionTypeRefs.add(klass.getReference());
}
}
return Collections.unmodifiableCollection(runtimeExceptionTypeRefs);
}
/**
* Return set of all subclasses of type in the Class Hierarchy TODO: Tune this implementation.
* Consider caching if necessary.
*
* @return Set of IClasses
*/
private Set<IClass> computeSubClassesInternal(IClass T) {
if (T.isArrayClass()) {
return Collections.singleton(T);
}
Node node = findNode(T);
assert node != null : "null node for class " + T;
HashSet<IClass> result = HashSetFactory.make(3);
result.add(T);
for (Node child : Iterator2Iterable.make(node.getChildren())) {
result.addAll(computeSubClasses(child.klass.getReference()));
}
return result;
}
@Override
public boolean isInterface(TypeReference type) {
IClass T = lookupClass(type);
assert T != null : "Null lookup for " + type;
return T.isInterface();
}
/**
* TODO: tune this if necessary
*
* @param type an interface
* @return Set of IClass that represent implementors of the interface
*/
@Override
public Set<IClass> getImplementors(TypeReference type) {
IClass T = lookupClass(type);
Set<IClass> result = implementors.get(T);
if (result == null) {
return Collections.emptySet();
}
return Collections.unmodifiableSet(result);
}
@Override
public Iterator<IClass> iterator() {
Function<Node, IClass> toClass = n -> n.klass;
return new MapIterator<>(map.values().iterator(), toClass);
}
/** @return The number of classes present in the class hierarchy. */
@Override
public int getNumberOfClasses() {
return map.keySet().size();
}
@Override
public IClassLoader[] getLoaders() {
return loaders;
}
@Override
public IClassLoader getLoader(ClassLoaderReference loaderRef) {
for (IClassLoader loader : loaders) {
if (loader.getReference().equals(loaderRef)) {
return loader;
}
}
Assertions.UNREACHABLE();
return null;
}
@Override
public AnalysisScope getScope() {
return scope;
}
/**
* @return the number of classes that immediately extend klass. if klass is an array class
* A[][]...[], we return number of immediate subclasses of A. If A is primitive, we return 0.
*/
@Override
public int getNumberOfImmediateSubclasses(IClass klass) {
if (klass.isArrayClass()) {
IClass innermost = getInnermostTypeOfArrayClass(klass);
return innermost == null ? 0 : getNumberOfImmediateSubclasses(innermost);
}
Node node = findNode(klass);
return node.children.size();
}
/**
* @return the classes that immediately extend klass. if klass is an array class A[][]...[], we
* return array classes B[][]...[] (same dimensionality) where B is an immediate subclass of
* A. If A is primitive, we return the empty set.
*/
@Override
public Collection<IClass> getImmediateSubclasses(IClass klass) {
if (klass.isArrayClass()) {
return getImmediateArraySubclasses((ArrayClass) klass);
}
Function<Node, IClass> node2Class = n -> n.klass;
return Iterator2Collection.toSet(
new MapIterator<>(findNode(klass).children.iterator(), node2Class));
}
private Collection<IClass> getImmediateArraySubclasses(ArrayClass klass) {
IClass innermost = getInnermostTypeOfArrayClass(klass);
if (innermost == null) {
return Collections.emptySet();
}
Collection<IClass> innermostSubclasses = getImmediateSubclasses(innermost);
int dim = klass.getDimensionality();
Collection<IClass> result = HashSetFactory.make();
for (IClass k : innermostSubclasses) {
TypeReference ref = k.getReference();
for (int i = 0; i < dim; i++) {
ref = ref.getArrayTypeForElementType();
}
result.add(lookupClass(ref));
}
return result;
}
/** for an array class, get the innermost type, or null if it's primitive */
private IClass getInnermostTypeOfArrayClass(IClass klass) {
TypeReference result = klass.getReference();
while (result.isArrayType()) {
result = result.getArrayElementType();
}
return result.isPrimitiveType() ? null : lookupClass(result);
}
@Override
public IClass getRootClass() {
return root.getJavaClass();
}
@Override
public boolean isRootClass(IClass c) throws IllegalArgumentException {
if (c == null) {
throw new IllegalArgumentException("c == null");
}
return c.equals(root.getJavaClass());
}
@Override
public int getNumber(IClass c) {
return map.get(c.getReference()).left;
}
/** A warning for when we fail to resolve the type for a checkcast */
private static class ClassExclusion extends Warning {
final TypeReference klass;
final String message;
ClassExclusion(TypeReference klass, String message) {
super(Warning.MODERATE);
this.klass = klass;
this.message = message;
}
@Override
public String getMsg() {
return getClass().toString() + " : " + klass + ' ' + message;
}
public static ClassExclusion create(TypeReference klass, String message) {
return new ClassExclusion(klass, message);
}
}
/**
* Does an expression c1 x := c2 y typecheck?
*
* <p>i.e. is c2 a subtype of c1?
*
* @throws IllegalArgumentException if c1 is null
* @throws IllegalArgumentException if c2 is null
*/
@Override
public boolean isAssignableFrom(IClass c1, IClass c2) {
if (c2 == null) {
throw new IllegalArgumentException("c2 is null");
}
if (c1 == null) {
throw new IllegalArgumentException("c1 is null");
}
if (c1.isInterface()) {
return implementsInterface(c2, c1);
} else {
if (c2.isInterface()) {
return c1.equals(getRootClass());
} else {
return isSubclassOf(c2, c1);
}
}
}
/* BEGIN Custom change: remember unresolved classes */
private final Set<TypeReference> unresolved = HashSetFactory.make();
@Override
public final Set<TypeReference> getUnresolvedClasses() {
return unresolved;
}
/* END Custom change: remember unresolved classes */
public MissingSuperClassHandling getSuperClassHandling() {
return superClassHandling;
}
}
| 41,520
| 30.816858
| 100
|
java
|
WALA
|
WALA-master/core/src/main/java/com/ibm/wala/ipa/cha/ClassHierarchyException.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.cha;
import com.ibm.wala.util.WalaException;
/** An exception that means something went wrong when constructing a {@link ClassHierarchy}. */
public class ClassHierarchyException extends WalaException {
public static final long serialVersionUID = 381093189198391L;
public ClassHierarchyException(String string) {
super(string);
}
public ClassHierarchyException(String s, Throwable cause) {
super(s, cause);
}
}
| 832
| 29.851852
| 95
|
java
|
WALA
|
WALA-master/core/src/main/java/com/ibm/wala/ipa/cha/ClassHierarchyFactory.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.cha;
import com.ibm.wala.classLoader.ClassLoaderFactory;
import com.ibm.wala.classLoader.ClassLoaderFactoryImpl;
import com.ibm.wala.classLoader.Language;
import com.ibm.wala.ipa.callgraph.AnalysisScope;
import com.ibm.wala.util.MonitorUtil.IProgressMonitor;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
public class ClassHierarchyFactory {
/** @return a ClassHierarchy object representing the analysis scope */
public static ClassHierarchy make(AnalysisScope scope) throws ClassHierarchyException {
if (scope == null) {
throw new IllegalArgumentException("null scope");
}
return make(scope, new ClassLoaderFactoryImpl(scope.getExclusions()));
}
/**
* NOTE: phantom classes are a work-in-progress and this functionality has <a
* href="https://github.com/wala/WALA/pull/335">known bugs</a>. At this point, we recommend using
* {@link #makeWithRoot(AnalysisScope)} instead.
*
* @return a ClassHierarchy object representing the analysis scope, where phantom classes are
* created when superclasses are missing
*/
public static ClassHierarchy makeWithPhantom(AnalysisScope scope) throws ClassHierarchyException {
if (scope == null) {
throw new IllegalArgumentException("null scope");
}
return makeWithPhantom(scope, new ClassLoaderFactoryImpl(scope.getExclusions()));
}
/**
* @return a ClassHierarchy object representing the analysis scope, missing superclasses are
* replaced by the ClassHierarchy root, i.e. java.lang.Object
*/
public static ClassHierarchy makeWithRoot(AnalysisScope scope) throws ClassHierarchyException {
if (scope == null) {
throw new IllegalArgumentException("null scope");
}
return makeWithRoot(scope, new ClassLoaderFactoryImpl(scope.getExclusions()));
}
/**
* temporarily marking this internal to avoid infinite sleep with randomly chosen
* IProgressMonitor.
*/
public static ClassHierarchy make(AnalysisScope scope, IProgressMonitor monitor)
throws ClassHierarchyException {
if (scope == null) {
throw new IllegalArgumentException("null scope");
}
return make(scope, new ClassLoaderFactoryImpl(scope.getExclusions()), monitor);
}
public static ClassHierarchy make(AnalysisScope scope, ClassLoaderFactory factory)
throws ClassHierarchyException {
return make(scope, factory, ClassHierarchy.MissingSuperClassHandling.NONE);
}
private static ClassHierarchy make(
AnalysisScope scope,
ClassLoaderFactory factory,
ClassHierarchy.MissingSuperClassHandling superClassHandling)
throws ClassHierarchyException {
if (scope == null) {
throw new IllegalArgumentException("null scope");
}
if (factory == null) {
throw new IllegalArgumentException("null factory");
}
return new ClassHierarchy(scope, factory, null, new ConcurrentHashMap<>(), superClassHandling);
}
public static ClassHierarchy makeWithPhantom(AnalysisScope scope, ClassLoaderFactory factory)
throws ClassHierarchyException {
return make(scope, factory, ClassHierarchy.MissingSuperClassHandling.PHANTOM);
}
public static ClassHierarchy makeWithRoot(AnalysisScope scope, ClassLoaderFactory factory)
throws ClassHierarchyException {
return make(scope, factory, ClassHierarchy.MissingSuperClassHandling.ROOT);
}
/**
* temporarily marking this internal to avoid infinite sleep with randomly chosen
* IProgressMonitor.
*/
public static ClassHierarchy make(
AnalysisScope scope, ClassLoaderFactory factory, IProgressMonitor monitor)
throws ClassHierarchyException {
return new ClassHierarchy(
scope,
factory,
monitor,
new ConcurrentHashMap<>(),
ClassHierarchy.MissingSuperClassHandling.NONE);
}
public static ClassHierarchy make(
AnalysisScope scope, ClassLoaderFactory factory, Set<Language> languages)
throws ClassHierarchyException {
return new ClassHierarchy(
scope,
factory,
languages,
null,
new ConcurrentHashMap<>(),
ClassHierarchy.MissingSuperClassHandling.NONE);
}
public static ClassHierarchy make(
AnalysisScope scope, ClassLoaderFactory factory, Language language)
throws ClassHierarchyException {
return new ClassHierarchy(
scope,
factory,
language,
null,
new ConcurrentHashMap<>(),
ClassHierarchy.MissingSuperClassHandling.NONE);
}
/**
* temporarily marking this internal to avoid infinite sleep with randomly chosen
* IProgressMonitor. TODO: nanny for testgen
*/
public static ClassHierarchy make(
AnalysisScope scope, ClassLoaderFactory factory, Language language, IProgressMonitor monitor)
throws ClassHierarchyException {
if (factory == null) {
throw new IllegalArgumentException("null factory");
}
return new ClassHierarchy(
scope,
factory,
language,
monitor,
new ConcurrentHashMap<>(),
ClassHierarchy.MissingSuperClassHandling.NONE);
}
}
| 5,509
| 34.320513
| 100
|
java
|
WALA
|
WALA-master/core/src/main/java/com/ibm/wala/ipa/cha/ClassHierarchyStats.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.cha;
import com.ibm.wala.classLoader.IClassLoader;
/** Statistics about a class hierarchy. */
public class ClassHierarchyStats {
/** Dump stats about the class hierarchy to stdout. */
public static void printStats(IClassHierarchy cha) throws IllegalArgumentException {
if (cha == null) {
throw new IllegalArgumentException("cha cannot be null");
}
IClassLoader[] loaders = cha.getLoaders();
for (IClassLoader loader : loaders) {
System.out.println("loader: " + loader);
System.out.println(" classes: " + loader.getNumberOfClasses());
System.out.println(" methods: " + loader.getNumberOfMethods());
}
}
}
| 1,059
| 33.193548
| 86
|
java
|
WALA
|
WALA-master/core/src/main/java/com/ibm/wala/ipa/cha/ClassHierarchyUtil.java
|
/*
* Copyright (c) 2009 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.ipa.cha;
import com.ibm.wala.classLoader.IClass;
import com.ibm.wala.classLoader.IMethod;
import com.ibm.wala.types.MethodReference;
/** Utilities for querying a class hierarchy */
public class ClassHierarchyUtil {
/** find the root of the inheritance tree for method m. */
public static IMethod getRootOfInheritanceTree(IMethod m) {
IClass c = m.getDeclaringClass();
IClass parent = c.getSuperclass();
if (parent != null) {
MethodReference ref = MethodReference.findOrCreate(parent.getReference(), m.getSelector());
IMethod m2 = m.getClassHierarchy().resolveMethod(ref);
if (m2 != null && !m2.equals(m)) {
return getRootOfInheritanceTree(m2);
}
}
return m;
}
/** Return the method that m overrides, or null if none */
public static IMethod getOverriden(IMethod m) {
IClass c = m.getDeclaringClass();
IClass parent = c.getSuperclass();
if (parent != null) {
MethodReference ref = MethodReference.findOrCreate(parent.getReference(), m.getSelector());
IMethod m2 = m.getClassHierarchy().resolveMethod(ref);
if (m2 != null && !m2.equals(m)) {
return m2;
}
}
return null;
}
}
| 1,581
| 31.958333
| 97
|
java
|
WALA
|
WALA-master/core/src/main/java/com/ibm/wala/ipa/cha/ClassHierarchyWarning.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.cha;
import com.ibm.wala.core.util.warnings.Warning;
/** A warning for when we get a class not found exception */
public class ClassHierarchyWarning extends Warning {
final String message;
ClassHierarchyWarning(String message) {
super(Warning.SEVERE);
this.message = message;
}
@Override
public String getMsg() {
return getClass().toString() + " : " + message;
}
public static ClassHierarchyWarning create(String message) {
return new ClassHierarchyWarning(message);
}
}
| 909
| 25.764706
| 72
|
java
|
WALA
|
WALA-master/core/src/main/java/com/ibm/wala/ipa/cha/IClassHierarchy.java
|
/*
* Copyright (c) 2013 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.ipa.cha;
import com.ibm.wala.classLoader.ClassLoaderFactory;
import com.ibm.wala.classLoader.IClass;
import com.ibm.wala.classLoader.IClassLoader;
import com.ibm.wala.classLoader.IField;
import com.ibm.wala.classLoader.IMethod;
import com.ibm.wala.ipa.callgraph.AnalysisScope;
import com.ibm.wala.types.ClassLoaderReference;
import com.ibm.wala.types.FieldReference;
import com.ibm.wala.types.MethodReference;
import com.ibm.wala.types.Selector;
import com.ibm.wala.types.TypeReference;
import java.util.Collection;
import java.util.Set;
/** General interface for a type hierarchy */
public interface IClassHierarchy extends Iterable<IClass> {
ClassLoaderFactory getFactory();
AnalysisScope getScope();
IClassLoader[] getLoaders();
IClassLoader getLoader(ClassLoaderReference loaderRef);
/**
* @return true if the add succeeded; false if it failed for some reason
* @throws IllegalArgumentException if klass is null
*/
boolean addClass(IClass klass);
/** @return The number of classes present in the class hierarchy. */
int getNumberOfClasses();
boolean isRootClass(IClass c);
IClass getRootClass();
int getNumber(IClass c);
/* BEGIN Custom change: remember unresolved classes */
Set<TypeReference> getUnresolvedClasses();
/* END Custom change: remember unresolved classes */
/**
* Find the possible targets of a call to a method reference
*
* @param ref method reference
* @return the set of IMethods that this call can resolve to.
* @throws IllegalArgumentException if ref is null
*/
Set<IMethod> getPossibleTargets(MethodReference ref);
/**
* Find the possible targets of a call to a method reference where the receiver is of a certain
* type
*
* @param receiverClass the class of the receiver
* @param ref method reference
* @return the set of IMethods that this call can resolve to.
*/
Set<IMethod> getPossibleTargets(IClass receiverClass, MethodReference ref);
/**
* Return the unique receiver of an invocation of method on an object of type {@code
* m.getDeclaredClass()}. Note that for Java, {@code m.getDeclaredClass()} must represent a
* <em>class</em>, <em>not</em> an interface. This method does not work for finding inherited
* methods in interfaces.
*
* @return IMethod, or null if no appropriate receiver is found.
* @throws IllegalArgumentException if m is null
*/
IMethod resolveMethod(MethodReference m);
/**
* @return the canonical IField that represents a given field , or null if none found
* @throws IllegalArgumentException if f is null
*/
IField resolveField(FieldReference f);
/**
* @return the canonical IField that represents a given field , or null if none found
* @throws IllegalArgumentException if f is null
* @throws IllegalArgumentException if klass is null
*/
IField resolveField(IClass klass, FieldReference f);
/**
* Return the unique target of an invocation of method on an object of type receiverClass
*
* @param receiverClass type of receiver. Note that for Java, {@code receiverClass} must represent
* a <em>class</em>, <em>not</em> an interface. This method does not work for finding
* inherited methods in interfaces.
* @param selector method signature
* @return Method resolved method abstraction
* @throws IllegalArgumentException if receiverClass is null
*/
IMethod resolveMethod(IClass receiverClass, Selector selector);
/**
* Load a class using one of the loaders specified for this class hierarchy
*
* @return null if can't find the class.
* @throws IllegalArgumentException if A is null
*/
IClass lookupClass(TypeReference A);
// public boolean isSyntheticClass(IClass c);
boolean isInterface(TypeReference type);
IClass getLeastCommonSuperclass(IClass A, IClass B);
TypeReference getLeastCommonSuperclass(TypeReference A, TypeReference B);
/**
* Is c a subclass of T?
*
* @throws IllegalArgumentException if c is null
*/
boolean isSubclassOf(IClass c, IClass T);
/**
* Does c implement i?
*
* @return true iff i is an interface and c is a class that implements i, or c is an interface
* that extends i.
*/
boolean implementsInterface(IClass c, IClass i);
/** Return set of all subclasses of type in the Class Hierarchy */
Collection<IClass> computeSubClasses(TypeReference type);
/**
* Solely for optimization; return a Collection<TypeReference> representing the subclasses
* of Error
*
* <p>kind of ugly. a better scheme?
*/
Collection<TypeReference> getJavaLangErrorTypes();
/**
* Solely for optimization; return a Collection<TypeReference> representing the subclasses
* of {@link RuntimeException}
*
* <p>kind of ugly. a better scheme?
*/
Collection<TypeReference> getJavaLangRuntimeExceptionTypes();
/**
* @param type an interface
* @return Set of IClass that represent implementors of the interface
*/
Set<IClass> getImplementors(TypeReference type);
/** @return the number of classes that immediately extend klass. */
int getNumberOfImmediateSubclasses(IClass klass);
/** @return the classes that immediately extend klass. */
Collection<IClass> getImmediateSubclasses(IClass klass);
/**
* Does an expression c1 x := c2 y typecheck?
*
* <p>i.e. is c2 a subtype of c1?
*
* @throws IllegalArgumentException if c1 is null
* @throws IllegalArgumentException if c2 is null
*/
boolean isAssignableFrom(IClass c1, IClass c2);
}
| 5,943
| 31.304348
| 100
|
java
|
WALA
|
WALA-master/core/src/main/java/com/ibm/wala/ipa/cha/IClassHierarchyDweller.java
|
/*
* Copyright (c) 2006 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.ipa.cha;
/** Something that lives in a class hierarchy */
public interface IClassHierarchyDweller {
IClassHierarchy getClassHierarchy();
}
| 531
| 30.294118
| 72
|
java
|
WALA
|
WALA-master/core/src/main/java/com/ibm/wala/ipa/cha/SeqClassHierarchyFactory.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.cha;
import com.ibm.wala.classLoader.ClassLoaderFactory;
import com.ibm.wala.classLoader.ClassLoaderFactoryImpl;
import com.ibm.wala.classLoader.Language;
import com.ibm.wala.ipa.callgraph.AnalysisScope;
import com.ibm.wala.util.MonitorUtil.IProgressMonitor;
import com.ibm.wala.util.collections.HashMapFactory;
import java.util.Set;
public class SeqClassHierarchyFactory {
/** @return a ClassHierarchy object representing the analysis scope */
public static ClassHierarchy make(AnalysisScope scope) throws ClassHierarchyException {
if (scope == null) {
throw new IllegalArgumentException("null scope");
}
return make(scope, new ClassLoaderFactoryImpl(scope.getExclusions()));
}
/**
* temporarily marking this internal to avoid infinite sleep with randomly chosen
* IProgressMonitor.
*/
public static ClassHierarchy make(AnalysisScope scope, IProgressMonitor monitor)
throws ClassHierarchyException {
if (scope == null) {
throw new IllegalArgumentException("null scope");
}
return make(scope, new ClassLoaderFactoryImpl(scope.getExclusions()), monitor);
}
public static ClassHierarchy make(AnalysisScope scope, ClassLoaderFactory factory)
throws ClassHierarchyException {
if (scope == null) {
throw new IllegalArgumentException("null scope");
}
if (factory == null) {
throw new IllegalArgumentException("null factory");
}
return new ClassHierarchy(
scope, factory, null, HashMapFactory.make(), ClassHierarchy.MissingSuperClassHandling.NONE);
}
/**
* temporarily marking this internal to avoid infinite sleep with randomly chosen
* IProgressMonitor.
*/
public static ClassHierarchy make(
AnalysisScope scope, ClassLoaderFactory factory, IProgressMonitor monitor)
throws ClassHierarchyException {
return new ClassHierarchy(
scope,
factory,
monitor,
HashMapFactory.make(),
ClassHierarchy.MissingSuperClassHandling.NONE);
}
public static ClassHierarchy make(
AnalysisScope scope, ClassLoaderFactory factory, Set<Language> languages)
throws ClassHierarchyException {
return new ClassHierarchy(
scope,
factory,
languages,
null,
HashMapFactory.make(),
ClassHierarchy.MissingSuperClassHandling.NONE);
}
public static ClassHierarchy make(
AnalysisScope scope, ClassLoaderFactory factory, Language language)
throws ClassHierarchyException {
return new ClassHierarchy(
scope,
factory,
language,
null,
HashMapFactory.make(),
ClassHierarchy.MissingSuperClassHandling.NONE);
}
/**
* temporarily marking this internal to avoid infinite sleep with randomly chosen
* IProgressMonitor. TODO: nanny for testgen
*/
public static ClassHierarchy make(
AnalysisScope scope, ClassLoaderFactory factory, Language language, IProgressMonitor monitor)
throws ClassHierarchyException {
if (factory == null) {
throw new IllegalArgumentException("null factory");
}
return new ClassHierarchy(
scope,
factory,
language,
monitor,
HashMapFactory.make(),
ClassHierarchy.MissingSuperClassHandling.NONE);
}
}
| 3,686
| 31.628319
| 100
|
java
|
WALA
|
WALA-master/core/src/main/java/com/ibm/wala/ipa/modref/ArrayLengthKey.java
|
/*
* Copyright (c) 2006 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.ipa.modref;
import com.ibm.wala.ipa.callgraph.propagation.AbstractFieldPointerKey;
import com.ibm.wala.ipa.callgraph.propagation.InstanceKey;
import com.ibm.wala.ipa.callgraph.propagation.PointerKey;
/** A {@link PointerKey} that represents an array length location */
public class ArrayLengthKey extends AbstractFieldPointerKey {
public ArrayLengthKey(InstanceKey i) {
super(i);
}
@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass().equals(obj.getClass())) {
ArrayLengthKey other = (ArrayLengthKey) obj;
return getInstanceKey().equals(other.getInstanceKey());
} else {
return false;
}
}
@Override
public int hashCode() {
return getInstanceKey().hashCode() * 19;
}
@Override
public String toString() {
return "arraylength:" + getInstanceKey();
}
}
| 1,265
| 25.93617
| 72
|
java
|
WALA
|
WALA-master/core/src/main/java/com/ibm/wala/ipa/modref/DelegatingExtendedHeapModel.java
|
/*
* Copyright (c) 2006 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.ipa.modref;
import com.ibm.wala.classLoader.IField;
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.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.cha.IClassHierarchy;
import com.ibm.wala.types.TypeReference;
import java.util.Iterator;
/** An implementation of {@link ExtendedHeapModel} based on a normal {@link HeapModel} */
public class DelegatingExtendedHeapModel implements ExtendedHeapModel {
private final HeapModel h;
public DelegatingExtendedHeapModel(HeapModel h) {
if (h == null) {
throw new IllegalArgumentException("null h");
}
this.h = h;
}
@Override
public IClassHierarchy getClassHierarchy() {
return h.getClassHierarchy();
}
@Override
public FilteredPointerKey getFilteredPointerKeyForLocal(
CGNode node, int valueNumber, FilteredPointerKey.TypeFilter filter) {
return h.getFilteredPointerKeyForLocal(node, valueNumber, filter);
}
@Override
public InstanceKey getInstanceKeyForAllocation(CGNode node, NewSiteReference allocation) {
return h.getInstanceKeyForAllocation(node, allocation);
}
@Override
public InstanceKey getInstanceKeyForMetadataObject(Object obj, TypeReference objType) {
return h.getInstanceKeyForMetadataObject(obj, objType);
}
@Override
public <T> InstanceKey getInstanceKeyForConstant(TypeReference type, T S) {
return h.getInstanceKeyForConstant(type, S);
}
@Override
public InstanceKey getInstanceKeyForMultiNewArray(
CGNode node, NewSiteReference allocation, int dim) {
return h.getInstanceKeyForMultiNewArray(node, allocation, dim);
}
@Override
public InstanceKey getInstanceKeyForPEI(CGNode node, ProgramCounter instr, TypeReference type) {
if (node == null) {
throw new IllegalArgumentException("null node");
}
return h.getInstanceKeyForPEI(node, instr, type);
}
@Override
public PointerKey getPointerKeyForArrayContents(InstanceKey I) {
if (I == null) {
throw new IllegalArgumentException("I is null");
}
return h.getPointerKeyForArrayContents(I);
}
@Override
public PointerKey getPointerKeyForExceptionalReturnValue(CGNode node) {
return h.getPointerKeyForExceptionalReturnValue(node);
}
@Override
public PointerKey getPointerKeyForInstanceField(InstanceKey I, IField field) {
if (field == null) {
throw new IllegalArgumentException("field is null");
}
return h.getPointerKeyForInstanceField(I, field);
}
@Override
public PointerKey getPointerKeyForLocal(CGNode node, int valueNumber) {
return h.getPointerKeyForLocal(node, valueNumber);
}
@Override
public PointerKey getPointerKeyForReturnValue(CGNode node) {
return h.getPointerKeyForReturnValue(node);
}
@Override
public PointerKey getPointerKeyForStaticField(IField f) {
return h.getPointerKeyForStaticField(f);
}
@Override
public Iterator<PointerKey> iteratePointerKeys() {
return h.iteratePointerKeys();
}
@Override
public PointerKey getPointerKeyForArrayLength(InstanceKey I) {
return new ArrayLengthKey(I);
}
}
| 3,758
| 29.560976
| 98
|
java
|
WALA
|
WALA-master/core/src/main/java/com/ibm/wala/ipa/modref/ExtendedHeapModel.java
|
/*
* Copyright (c) 2006 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.ipa.modref;
import com.ibm.wala.ipa.callgraph.propagation.HeapModel;
import com.ibm.wala.ipa.callgraph.propagation.InstanceKey;
import com.ibm.wala.ipa.callgraph.propagation.PointerKey;
/**
* An extension of a heap model that returns a {@link PointerKey} to represent an array length field
*/
public interface ExtendedHeapModel extends HeapModel {
/**
* @param I an InstanceKey representing an abstract array
* @return the PointerKey that acts as a representation for the arraylength field of this abstract
* array
*/
PointerKey getPointerKeyForArrayLength(InstanceKey I);
}
| 988
| 34.321429
| 100
|
java
|
WALA
|
WALA-master/core/src/main/java/com/ibm/wala/ipa/modref/GenReach.java
|
/*
* Copyright (c) 2006 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.ipa.modref;
import com.ibm.wala.dataflow.graph.AbstractMeetOperator;
import com.ibm.wala.dataflow.graph.BitVectorFramework;
import com.ibm.wala.dataflow.graph.BitVectorUnion;
import com.ibm.wala.dataflow.graph.BitVectorUnionVector;
import com.ibm.wala.dataflow.graph.ITransferFunctionProvider;
import com.ibm.wala.fixpoint.BitVectorVariable;
import com.ibm.wala.fixpoint.UnaryOperator;
import com.ibm.wala.util.debug.Assertions;
import com.ibm.wala.util.graph.Graph;
import com.ibm.wala.util.intset.BitVector;
import com.ibm.wala.util.intset.MutableMapping;
import com.ibm.wala.util.intset.OrdinalSetMapping;
import java.util.Collection;
import java.util.Map;
/** Generic dataflow framework to accumulate reachable gen'ned values in a graph. */
public class GenReach<T, L> extends BitVectorFramework<T, L> {
@SuppressWarnings("unchecked")
public GenReach(Graph<T> flowGraph, Map<T, Collection<L>> gen) {
super(flowGraph, new GenFunctions<>(gen), makeDomain(gen));
// ugly but necessary, in order to avoid computing the domain twice.
GenReach.GenFunctions<T, L> g = (GenReach.GenFunctions<T, L>) getTransferFunctionProvider();
g.domain = getLatticeValues();
}
private static <T, L> OrdinalSetMapping<L> makeDomain(Map<T, Collection<L>> gen) {
MutableMapping<L> result = MutableMapping.make();
if (gen == null) {
throw new IllegalArgumentException("null gen");
}
for (Collection<L> c : gen.values()) {
for (L p : c) {
result.add(p);
}
}
return result;
}
static class GenFunctions<T, L> implements ITransferFunctionProvider<T, BitVectorVariable> {
private final Map<T, Collection<L>> gen;
private OrdinalSetMapping<L> domain;
public GenFunctions(Map<T, Collection<L>> gen) {
this.gen = gen;
}
@Override
public AbstractMeetOperator<BitVectorVariable> getMeetOperator() {
return BitVectorUnion.instance();
}
@Override
public UnaryOperator<BitVectorVariable> getNodeTransferFunction(T node) {
BitVector v = getGen(node);
return new BitVectorUnionVector(v);
}
private BitVector getGen(T node) {
Collection<L> g = gen.get(node);
if (g == null) {
return new BitVector();
} else {
BitVector result = new BitVector();
for (L p : g) {
result.set(domain.getMappedIndex(p));
}
return result;
}
}
@Override
public boolean hasEdgeTransferFunctions() {
return false;
}
@Override
public boolean hasNodeTransferFunctions() {
return true;
}
@Override
public UnaryOperator<BitVectorVariable> getEdgeTransferFunction(T src, T dst) {
Assertions.UNREACHABLE();
return null;
}
}
}
| 3,144
| 29.833333
| 96
|
java
|
WALA
|
WALA-master/core/src/main/java/com/ibm/wala/ipa/modref/ModRef.java
|
/*
* Copyright (c) 2006 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.ipa.modref;
import com.ibm.wala.classLoader.IClass;
import com.ibm.wala.classLoader.IField;
import com.ibm.wala.ipa.callgraph.CGNode;
import com.ibm.wala.ipa.callgraph.CallGraph;
import com.ibm.wala.ipa.callgraph.CallGraphTransitiveClosure;
import com.ibm.wala.ipa.callgraph.propagation.HeapModel;
import com.ibm.wala.ipa.callgraph.propagation.InstanceKey;
import com.ibm.wala.ipa.callgraph.propagation.PointerAnalysis;
import com.ibm.wala.ipa.callgraph.propagation.PointerKey;
import com.ibm.wala.ipa.slicer.HeapExclusions;
import com.ibm.wala.ssa.IR;
import com.ibm.wala.ssa.SSAArrayLengthInstruction;
import com.ibm.wala.ssa.SSAArrayLoadInstruction;
import com.ibm.wala.ssa.SSAArrayStoreInstruction;
import com.ibm.wala.ssa.SSAGetInstruction;
import com.ibm.wala.ssa.SSAInstruction;
import com.ibm.wala.ssa.SSANewInstruction;
import com.ibm.wala.ssa.SSAPutInstruction;
import com.ibm.wala.util.collections.HashSetFactory;
import com.ibm.wala.util.collections.Iterator2Iterable;
import com.ibm.wala.util.intset.OrdinalSet;
import java.util.Collection;
import java.util.Map;
import java.util.Set;
/**
* Mod-ref analysis for heap locations.
*
* <p>For each call graph node, what heap locations (as determined by a heap model) may it read or
* write, including it's callees transitively
*/
public class ModRef<T extends InstanceKey> {
public static <U extends InstanceKey> ModRef<U> make() {
return new ModRef<>();
}
public ModRef() {}
/**
* For each call graph node, what heap locations (as determined by a heap model) may it write,
* including its callees transitively
*
* @throws IllegalArgumentException if cg is null
*/
public Map<CGNode, OrdinalSet<PointerKey>> computeMod(
CallGraph cg, PointerAnalysis<T> pa, HeapExclusions heapExclude) {
if (cg == null) {
throw new IllegalArgumentException("cg is null");
}
Map<CGNode, Collection<PointerKey>> scan = scanForMod(cg, pa, heapExclude);
return CallGraphTransitiveClosure.transitiveClosure(cg, scan);
}
/**
* For each call graph node, what heap locations (as determined by a heap model) may it read,
* including its callees transitively
*
* @throws IllegalArgumentException if cg is null
*/
public Map<CGNode, OrdinalSet<PointerKey>> computeRef(
CallGraph cg, PointerAnalysis<T> pa, HeapExclusions heapExclude) {
if (cg == null) {
throw new IllegalArgumentException("cg is null");
}
Map<CGNode, Collection<PointerKey>> scan = scanForRef(cg, pa, heapExclude);
return CallGraphTransitiveClosure.transitiveClosure(cg, scan);
}
/**
* For each call graph node, what heap locations (as determined by a heap model) may it write,
* including its callees transitively
*/
public Map<CGNode, OrdinalSet<PointerKey>> computeMod(CallGraph cg, PointerAnalysis<T> pa) {
return computeMod(cg, pa, null);
}
/**
* For each call graph node, what heap locations (as determined by a heap model) may it read,
* including its callees transitively
*/
public Map<CGNode, OrdinalSet<PointerKey>> computeRef(CallGraph cg, PointerAnalysis<T> pa) {
return computeRef(cg, pa, null);
}
/**
* For each call graph node, what heap locations (as determined by a heap model) may it write, <b>
* NOT </b> including its callees transitively
*/
private Map<CGNode, Collection<PointerKey>> scanForMod(
CallGraph cg, final PointerAnalysis<T> pa, final HeapExclusions heapExclude) {
return CallGraphTransitiveClosure.collectNodeResults(
cg, n -> scanNodeForMod(n, pa, heapExclude));
}
/**
* For each call graph node, what heap locations (as determined by a heap model) may it read, <b>
* NOT </b> including its callees transitively
*/
private Map<CGNode, Collection<PointerKey>> scanForRef(
CallGraph cg, final PointerAnalysis<T> pa, final HeapExclusions heapExclude) {
return CallGraphTransitiveClosure.collectNodeResults(
cg, n -> scanNodeForRef(n, pa, heapExclude));
}
public ExtendedHeapModel makeHeapModel(PointerAnalysis<T> pa) {
HeapModel heapModel = pa.getHeapModel();
if (heapModel instanceof ExtendedHeapModel) {
return (ExtendedHeapModel) heapModel;
} else {
return new DelegatingExtendedHeapModel(heapModel);
}
}
/**
* For a call graph node, what heap locations (as determined by a heap model) may it write, <b>
* NOT </b> including it's callees transitively
*/
private Collection<PointerKey> scanNodeForMod(
final CGNode n, final PointerAnalysis<T> pa, HeapExclusions heapExclude) {
Collection<PointerKey> result = HashSetFactory.make();
final ExtendedHeapModel h = makeHeapModel(pa);
SSAInstruction.Visitor v = makeModVisitor(n, result, pa, h);
IR ir = n.getIR();
if (ir != null) {
for (SSAInstruction inst : Iterator2Iterable.make(ir.iterateNormalInstructions())) {
inst.visit(v);
assert !result.contains(null);
}
}
if (heapExclude != null) {
result = heapExclude.filter(result);
}
return result;
}
/**
* For a call graph node, what heap locations (as determined by a heap model) may it read, <b> NOT
* </b> including it's callees transitively
*/
private Collection<PointerKey> scanNodeForRef(
final CGNode n, final PointerAnalysis<T> pa, HeapExclusions heapExclude) {
Collection<PointerKey> result = HashSetFactory.make();
final ExtendedHeapModel h = makeHeapModel(pa);
SSAInstruction.Visitor v = makeRefVisitor(n, result, pa, h);
IR ir = n.getIR();
if (ir != null) {
for (SSAInstruction x : Iterator2Iterable.make(ir.iterateNormalInstructions())) {
x.visit(v);
assert !result.contains(null) : x;
}
}
if (heapExclude != null) {
result = heapExclude.filter(result);
}
return result;
}
public static class RefVisitor<T extends InstanceKey, H extends ExtendedHeapModel>
extends SSAInstruction.Visitor {
protected final CGNode n;
protected final Collection<PointerKey> result;
protected final PointerAnalysis<T> pa;
protected final H h;
public RefVisitor(CGNode n, Collection<PointerKey> result, PointerAnalysis<T> pa2, H h) {
this.n = n;
this.result = result;
this.pa = pa2;
this.h = h;
}
@Override
public void visitArrayLength(SSAArrayLengthInstruction instruction) {
PointerKey ref = h.getPointerKeyForLocal(n, instruction.getArrayRef());
for (InstanceKey i : pa.getPointsToSet(ref)) {
result.add(h.getPointerKeyForArrayLength(i));
}
}
@Override
public void visitArrayLoad(SSAArrayLoadInstruction instruction) {
PointerKey ref = h.getPointerKeyForLocal(n, instruction.getArrayRef());
for (InstanceKey i : pa.getPointsToSet(ref)) {
result.add(h.getPointerKeyForArrayContents(i));
}
}
@Override
public void visitGet(SSAGetInstruction instruction) {
IField f = pa.getClassHierarchy().resolveField(instruction.getDeclaredField());
if (f != null) {
if (instruction.isStatic()) {
result.add(h.getPointerKeyForStaticField(f));
} else {
PointerKey ref = h.getPointerKeyForLocal(n, instruction.getRef());
for (InstanceKey i : pa.getPointsToSet(ref)) {
PointerKey x = h.getPointerKeyForInstanceField(i, f);
if (x != null) {
result.add(x);
}
}
}
}
}
}
public static class ModVisitor<T extends InstanceKey, H extends ExtendedHeapModel>
extends SSAInstruction.Visitor {
protected final CGNode n;
protected final Collection<PointerKey> result;
protected final H h;
protected final PointerAnalysis<T> pa;
private final boolean ignoreAllocHeapDefs;
public ModVisitor(
CGNode n,
Collection<PointerKey> result,
H h,
PointerAnalysis<T> pa,
boolean ignoreAllocHeapDefs) {
this.n = n;
this.result = result;
this.h = h;
this.pa = pa;
this.ignoreAllocHeapDefs = ignoreAllocHeapDefs;
}
@Override
public void visitNew(SSANewInstruction instruction) {
if (instruction.getConcreteType().isArrayType()) {
int dim = instruction.getConcreteType().getDimensionality();
if (dim > 1) {
// we need to handle the top-level allocation, just like the 1D case
InstanceKey ik = h.getInstanceKeyForAllocation(n, instruction.getNewSite());
// note that ik can be null depending on class hierarchy exclusions or
// for incomplete programs. If so, just ignore it and keep going.
if (ik != null) {
PointerKey pk = h.getPointerKeyForArrayContents(ik);
assert pk != null;
result.add(pk);
pk = h.getPointerKeyForArrayLength(ik);
assert pk != null;
result.add(pk);
}
// now, the inner dimensions
for (int d = 0; d < dim - 1; d++) {
InstanceKey i = h.getInstanceKeyForMultiNewArray(n, instruction.getNewSite(), d);
// note that i can be null depending on class hierarchy exclusions
// or for incomplete programs. If so, just ignore it and keep going.
if (i != null) {
PointerKey pk = h.getPointerKeyForArrayContents(i);
assert pk != null;
result.add(pk);
pk = h.getPointerKeyForArrayLength(i);
assert pk != null;
result.add(pk);
}
}
} else {
// allocation of 1D arr "writes" the contents of the array and the
// length field
InstanceKey i = h.getInstanceKeyForAllocation(n, instruction.getNewSite());
// note that i can be null depending on class hierarchy exclusions or
// for incomplete programs. If so, just ignore it and keep going.
if (i != null) {
if (!ignoreAllocHeapDefs) {
PointerKey pk = h.getPointerKeyForArrayContents(i);
assert pk != null;
result.add(pk);
}
PointerKey pk = h.getPointerKeyForArrayLength(i);
assert pk != null;
result.add(pk);
}
}
} else {
if (!ignoreAllocHeapDefs) {
// allocation of a scalar "writes" all fields in the scalar
InstanceKey i = h.getInstanceKeyForAllocation(n, instruction.getNewSite());
if (i != null) {
IClass type = i.getConcreteType();
for (IField f : type.getAllInstanceFields()) {
PointerKey pk = h.getPointerKeyForInstanceField(i, f);
assert pk != null;
result.add(pk);
}
}
}
}
}
@Override
public void visitArrayStore(SSAArrayStoreInstruction instruction) {
PointerKey ref = h.getPointerKeyForLocal(n, instruction.getArrayRef());
for (InstanceKey i : pa.getPointsToSet(ref)) {
result.add(h.getPointerKeyForArrayContents(i));
}
}
@Override
public void visitPut(SSAPutInstruction instruction) {
IField f = pa.getClassHierarchy().resolveField(instruction.getDeclaredField());
if (f != null) {
if (instruction.isStatic()) {
result.add(h.getPointerKeyForStaticField(f));
} else {
PointerKey ref = h.getPointerKeyForLocal(n, instruction.getRef());
if (ref != null) {
for (InstanceKey i : pa.getPointsToSet(ref)) {
result.add(h.getPointerKeyForInstanceField(i, f));
}
}
}
}
}
}
protected ModVisitor<T, ?> makeModVisitor(
CGNode n, Collection<PointerKey> result, PointerAnalysis<T> pa, ExtendedHeapModel h) {
return makeModVisitor(n, result, pa, h, false);
}
protected ModVisitor<T, ?> makeModVisitor(
CGNode n,
Collection<PointerKey> result,
PointerAnalysis<T> pa,
ExtendedHeapModel h,
boolean ignoreAllocHeapDefs) {
return n.getMethod()
.getDeclaringClass()
.getClassLoader()
.getLanguage()
.makeModVisitor(n, result, pa, h, ignoreAllocHeapDefs);
// return new ModVisitor<>(n, result, h, pa, ignoreAllocHeapDefs);
}
/**
* Compute the set of {@link PointerKey}s that represent pointers that instruction s may write to.
*/
public Set<PointerKey> getMod(
CGNode n,
ExtendedHeapModel h,
PointerAnalysis<T> pa,
SSAInstruction s,
HeapExclusions hexcl) {
return getMod(n, h, pa, s, hexcl, false);
}
/**
* Compute the set of {@link PointerKey}s that represent pointers that instruction s may write to.
*/
public Set<PointerKey> getMod(
CGNode n,
ExtendedHeapModel h,
PointerAnalysis<T> pa,
SSAInstruction s,
HeapExclusions hexcl,
boolean ignoreAllocHeapDefs) {
if (s == null) {
throw new IllegalArgumentException("s is null");
}
Set<PointerKey> result = HashSetFactory.make(2);
ModVisitor<T, ?> v = makeModVisitor(n, result, pa, h, ignoreAllocHeapDefs);
s.visit(v);
return hexcl == null ? result : hexcl.filter(result);
}
protected RefVisitor<T, ? extends ExtendedHeapModel> makeRefVisitor(
CGNode n, Collection<PointerKey> result, PointerAnalysis<T> pa, ExtendedHeapModel h) {
return n.getMethod()
.getDeclaringClass()
.getClassLoader()
.getLanguage()
.makeRefVisitor(n, result, pa, h);
}
/** Compute the set of {@link PointerKey}s that represent pointers that instruction s may read. */
public Set<PointerKey> getRef(
CGNode n,
ExtendedHeapModel h,
PointerAnalysis<T> pa,
SSAInstruction s,
HeapExclusions hexcl) {
if (s == null) {
throw new IllegalArgumentException("s is null");
}
Set<PointerKey> result = HashSetFactory.make(2);
RefVisitor<T, ?> v = makeRefVisitor(n, result, pa, h);
s.visit(v);
return hexcl == null ? result : hexcl.filter(result);
}
}
| 14,486
| 33.908434
| 100
|
java
|
WALA
|
WALA-master/core/src/main/java/com/ibm/wala/ipa/modref/ModRefFieldAccess.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.modref;
import com.ibm.wala.classLoader.IClass;
import com.ibm.wala.classLoader.IField;
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.SSAGetInstruction;
import com.ibm.wala.ssa.SSAInstruction;
import com.ibm.wala.ssa.SSAPutInstruction;
import com.ibm.wala.types.FieldReference;
import com.ibm.wala.util.collections.Iterator2Iterable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* Computes interprocedural field accesses for a given method.
*
* @author Martin Seidel
* @author Juergen Graf <juergen.graf@gmail.com>
*/
public final class ModRefFieldAccess {
private static class TwoMaps {
private Map<IClass, Set<IField>> mods;
private Map<IClass, Set<IField>> refs;
public TwoMaps(Map<IClass, Set<IField>> mods, Map<IClass, Set<IField>> refs) {
this.mods = mods;
this.refs = refs;
if (mods == null) {
this.mods = new HashMap<>();
}
if (refs == null) {
this.refs = new HashMap<>();
}
}
public Map<IClass, Set<IField>> getMods() {
return mods;
}
public Map<IClass, Set<IField>> getRefs() {
return refs;
}
}
private final CallGraph cg;
private final Map<CGNode, Map<IClass, Set<IField>>> mods;
private final Map<CGNode, Map<IClass, Set<IField>>> refs;
private final Map<CGNode, Map<IClass, Set<IField>>> tmods;
private final Map<CGNode, Map<IClass, Set<IField>>> trefs;
private final List<CGNode> done;
private ModRefFieldAccess(CallGraph cg) {
this.cg = cg;
this.refs = new HashMap<>();
this.mods = new HashMap<>();
this.trefs = new HashMap<>();
this.tmods = new HashMap<>();
this.done = new ArrayList<>();
}
public static ModRefFieldAccess compute(CallGraph cg) {
ModRefFieldAccess fa = new ModRefFieldAccess(cg);
fa.run();
return fa;
}
public Map<IClass, Set<IField>> getMod(CGNode node) {
return mods.get(node);
}
public Map<IClass, Set<IField>> getRef(CGNode node) {
return refs.get(node);
}
public Map<IClass, Set<IField>> getTransitiveMod(CGNode node) {
return tmods.get(node);
}
public Map<IClass, Set<IField>> getTransitiveRef(CGNode node) {
return trefs.get(node);
}
private void run() {
for (CGNode cgNode : cg) {
if (!refs.containsKey(cgNode)) {
refs.put(cgNode, new HashMap<>());
}
if (!mods.containsKey(cgNode)) {
mods.put(cgNode, new HashMap<>());
}
final IR ir = cgNode.getIR();
if (ir == null) {
continue;
}
for (SSAInstruction instr : Iterator2Iterable.make(ir.iterateNormalInstructions())) {
if (instr instanceof SSAGetInstruction) {
SSAGetInstruction get = (SSAGetInstruction) instr;
FieldReference fref = get.getDeclaredField();
IField field = cg.getClassHierarchy().resolveField(fref);
if (field != null) {
IClass cls = field.getDeclaringClass();
if (cls != null) {
if (!refs.get(cgNode).containsKey(cls)) {
refs.get(cgNode).put(cls, new HashSet<>());
}
refs.get(cgNode).get(cls).add(field);
}
}
} else if (instr instanceof SSAPutInstruction) {
SSAPutInstruction put = (SSAPutInstruction) instr;
FieldReference fput = put.getDeclaredField();
IField field = cg.getClassHierarchy().resolveField(fput);
if (field != null) {
IClass cls = field.getDeclaringClass();
if (cls != null) {
if (!mods.get(cgNode).containsKey(cls)) {
mods.get(cgNode).put(cls, new HashSet<>());
}
mods.get(cgNode).get(cls).add(field);
}
}
}
}
}
recAdd(cg.getFakeRootNode());
}
private TwoMaps recAdd(CGNode node) {
if (!trefs.containsKey(node)) {
trefs.put(node, new HashMap<>());
}
if (!tmods.containsKey(node)) {
tmods.put(node, new HashMap<>());
}
final IR ir = node.getIR();
if (ir != null) {
for (SSAInstruction instr : Iterator2Iterable.make(ir.iterateNormalInstructions())) {
if (instr instanceof SSAGetInstruction) {
SSAGetInstruction get = (SSAGetInstruction) instr;
FieldReference fref = get.getDeclaredField();
IField field = cg.getClassHierarchy().resolveField(fref);
if (field != null) {
IClass cls = field.getDeclaringClass();
if (cls != null) {
if (!trefs.get(node).containsKey(cls)) {
trefs.get(node).put(cls, new HashSet<>());
}
trefs.get(node).get(cls).add(field);
}
}
} else if (instr instanceof SSAPutInstruction) {
SSAPutInstruction put = (SSAPutInstruction) instr;
FieldReference fput = put.getDeclaredField();
IField field = cg.getClassHierarchy().resolveField(fput);
if (field != null) {
IClass cls = field.getDeclaringClass();
if (cls != null) {
if (!tmods.get(node).containsKey(cls)) {
tmods.get(node).put(cls, new HashSet<>());
}
tmods.get(node).get(cls).add(field);
}
}
}
}
}
for (CGNode n : Iterator2Iterable.make(cg.getSuccNodes(node))) {
if (!done.contains(n)) {
done.add(n);
TwoMaps t = recAdd(n);
for (IClass c : t.getRefs().keySet()) {
if (trefs.get(node).containsKey(c)) {
trefs.get(node).get(c).addAll(t.getRefs().get(c));
} else {
trefs.get(node).put(c, t.getRefs().get(c));
}
}
for (IClass c : t.getMods().keySet()) {
if (tmods.get(node).containsKey(c)) {
tmods.get(node).get(c).addAll(t.getMods().get(c));
} else {
tmods.get(node).put(c, t.getMods().get(c));
}
}
}
}
return new TwoMaps(tmods.get(node), trefs.get(node));
}
}
| 6,633
| 29.292237
| 91
|
java
|
WALA
|
WALA-master/core/src/main/java/com/ibm/wala/ipa/slicer/Dependency.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
*
* <p>Contributors: IBM Corporation - initial API and implementation
* *****************************************************************************
*/
package com.ibm.wala.ipa.slicer;
public enum Dependency {
CONTROL_DEP,
DATA_DEP,
HEAP_DATA_DEP
}
| 624
| 35.764706
| 100
|
java
|
WALA
|
WALA-master/core/src/main/java/com/ibm/wala/ipa/slicer/ExceptionalReturnCallee.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.slicer;
import com.ibm.wala.ipa.callgraph.CGNode;
/**
* A {@link Statement} representing the exceptional return value in a callee, immediately before
* returning to the caller.
*/
public class ExceptionalReturnCallee extends Statement {
public ExceptionalReturnCallee(CGNode node) {
super(node);
}
@Override
public Kind getKind() {
return Kind.EXC_RET_CALLEE;
}
}
| 782
| 25.1
| 96
|
java
|
WALA
|
WALA-master/core/src/main/java/com/ibm/wala/ipa/slicer/ExceptionalReturnCaller.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.slicer;
import com.ibm.wala.ipa.callgraph.CGNode;
import com.ibm.wala.ssa.SSAAbstractInvokeInstruction;
/**
* A {@link Statement} representing the exceptional return value in a caller, immediately after
* returning to the caller.
*/
public class ExceptionalReturnCaller extends StatementWithInstructionIndex
implements ValueNumberCarrier {
public ExceptionalReturnCaller(CGNode node, int callIndex) {
super(node, callIndex);
}
@Override
public int getValueNumber() {
return getInstruction().getException();
}
@Override
public SSAAbstractInvokeInstruction getInstruction() {
return (SSAAbstractInvokeInstruction) super.getInstruction();
}
@Override
public Kind getKind() {
return Kind.EXC_RET_CALLER;
}
}
| 1,148
| 26.357143
| 95
|
java
|
WALA
|
WALA-master/core/src/main/java/com/ibm/wala/ipa/slicer/GetCaughtExceptionStatement.java
|
/*
* Copyright (c) 2006 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.ipa.slicer;
import com.ibm.wala.ipa.callgraph.CGNode;
import com.ibm.wala.ssa.SSAGetCaughtExceptionInstruction;
/** identifier of a GetCaughtException instruction */
public class GetCaughtExceptionStatement extends Statement {
private final SSAGetCaughtExceptionInstruction st;
public GetCaughtExceptionStatement(CGNode node, SSAGetCaughtExceptionInstruction st) {
super(node);
this.st = st;
}
@Override
public Kind getKind() {
return Kind.CATCH;
}
@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass().equals(obj.getClass())) {
GetCaughtExceptionStatement other = (GetCaughtExceptionStatement) obj;
return getNode().equals(other.getNode()) && st.equals(other.st);
} else {
return false;
}
}
@Override
public int hashCode() {
return 3691 * st.hashCode() + getNode().hashCode();
}
@Override
public String toString() {
return getNode() + ":" + st;
}
public SSAGetCaughtExceptionInstruction getInstruction() {
return st;
}
}
| 1,463
| 24.684211
| 88
|
java
|
WALA
|
WALA-master/core/src/main/java/com/ibm/wala/ipa/slicer/HeapExclusions.java
|
/*
* Copyright (c) 2006 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.ipa.slicer;
import com.ibm.wala.ipa.callgraph.propagation.AbstractFieldPointerKey;
import com.ibm.wala.ipa.callgraph.propagation.PointerKey;
import com.ibm.wala.ipa.callgraph.propagation.StaticFieldKey;
import com.ibm.wala.types.TypeReference;
import com.ibm.wala.util.collections.HashSetFactory;
import com.ibm.wala.util.config.SetOfClasses;
import com.ibm.wala.util.debug.Assertions;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;
/** heap locations that should be excluded from data dependence during slicing */
public class HeapExclusions {
private static final boolean VERBOSE = false;
/** used only for verbose processing. */
private static final Collection<TypeReference> considered = HashSetFactory.make();
private final SetOfClasses set;
public HeapExclusions(SetOfClasses set) {
this.set = set;
}
/**
* @return the PointerKeys that are not excluded
* @throws IllegalArgumentException if s is null
*/
public Set<PointerKey> filter(Collection<PointerKey> s) {
if (s == null) {
throw new IllegalArgumentException("s is null");
}
HashSet<PointerKey> result = HashSetFactory.make();
for (PointerKey p : s) {
if (p instanceof AbstractFieldPointerKey) {
AbstractFieldPointerKey f = (AbstractFieldPointerKey) p;
if (f.getInstanceKey().getConcreteType() != null) {
if (!set.contains(
f.getInstanceKey()
.getConcreteType()
.getReference()
.getName()
.toString()
.substring(1))) {
result.add(p);
if (VERBOSE) {
verboseAction(p);
}
} else {
// do nothing
}
}
} else if (p instanceof StaticFieldKey) {
StaticFieldKey sf = (StaticFieldKey) p;
if (!set.contains(
sf.getField().getDeclaringClass().getReference().getName().toString().substring(1))) {
result.add(p);
if (VERBOSE) {
verboseAction(p);
}
} else {
// do nothing
}
} else {
Assertions.UNREACHABLE(s.getClass().toString());
}
}
return result;
}
private static void verboseAction(PointerKey p) {
if (p instanceof AbstractFieldPointerKey) {
AbstractFieldPointerKey f = (AbstractFieldPointerKey) p;
if (f.getInstanceKey().getConcreteType() != null) {
TypeReference t = f.getInstanceKey().getConcreteType().getReference();
if (!considered.contains(t)) {
considered.add(t);
System.err.println("Considered " + t);
}
}
} else if (p instanceof StaticFieldKey) {
StaticFieldKey sf = (StaticFieldKey) p;
TypeReference t = sf.getField().getDeclaringClass().getReference();
if (!considered.contains(t)) {
considered.add(t);
System.err.println("Considered " + t);
}
}
}
public boolean excludes(PointerKey pk) {
TypeReference t = getType(pk);
return (t == null) ? false : set.contains(t.getName().toString().substring(1));
}
public static TypeReference getType(PointerKey pk) {
if (pk instanceof AbstractFieldPointerKey) {
AbstractFieldPointerKey f = (AbstractFieldPointerKey) pk;
if (f.getInstanceKey().getConcreteType() != null) {
return f.getInstanceKey().getConcreteType().getReference();
}
} else if (pk instanceof StaticFieldKey) {
StaticFieldKey sf = (StaticFieldKey) pk;
return sf.getField().getDeclaringClass().getReference();
}
return null;
}
}
| 4,021
| 31.967213
| 98
|
java
|
WALA
|
WALA-master/core/src/main/java/com/ibm/wala/ipa/slicer/HeapReachingDefs.java
|
/*
* Copyright (c) 2006 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.ipa.slicer;
import com.ibm.wala.core.util.CancelRuntimeException;
import com.ibm.wala.dataflow.graph.AbstractMeetOperator;
import com.ibm.wala.dataflow.graph.BitVectorFramework;
import com.ibm.wala.dataflow.graph.BitVectorIdentity;
import com.ibm.wala.dataflow.graph.BitVectorKillGen;
import com.ibm.wala.dataflow.graph.BitVectorMinusVector;
import com.ibm.wala.dataflow.graph.BitVectorSolver;
import com.ibm.wala.dataflow.graph.BitVectorUnion;
import com.ibm.wala.dataflow.graph.BitVectorUnionVector;
import com.ibm.wala.dataflow.graph.ITransferFunctionProvider;
import com.ibm.wala.fixpoint.BitVectorVariable;
import com.ibm.wala.fixpoint.UnaryOperator;
import com.ibm.wala.ipa.callgraph.CGNode;
import com.ibm.wala.ipa.callgraph.CallGraph;
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.StaticFieldKey;
import com.ibm.wala.ipa.modref.ExtendedHeapModel;
import com.ibm.wala.ipa.modref.ModRef;
import com.ibm.wala.ipa.slicer.HeapStatement.HeapReturnCaller;
import com.ibm.wala.ipa.slicer.Statement.Kind;
import com.ibm.wala.ssa.IR;
import com.ibm.wala.ssa.ISSABasicBlock;
import com.ibm.wala.ssa.SSAAbstractInvokeInstruction;
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.CancelException;
import com.ibm.wala.util.collections.FilterIterator;
import com.ibm.wala.util.collections.HashMapFactory;
import com.ibm.wala.util.collections.Iterator2Collection;
import com.ibm.wala.util.collections.Iterator2Iterable;
import com.ibm.wala.util.collections.ObjectArrayMapping;
import com.ibm.wala.util.debug.Assertions;
import com.ibm.wala.util.intset.BasicNaturalRelation;
import com.ibm.wala.util.intset.BitVector;
import com.ibm.wala.util.intset.BitVectorIntSet;
import com.ibm.wala.util.intset.IBinaryNaturalRelation;
import com.ibm.wala.util.intset.IntSet;
import com.ibm.wala.util.intset.MutableIntSet;
import com.ibm.wala.util.intset.MutableSparseIntSet;
import com.ibm.wala.util.intset.OrdinalSet;
import com.ibm.wala.util.intset.OrdinalSetMapping;
import com.ibm.wala.util.intset.SparseIntSet;
import java.util.Collection;
import java.util.Collections;
import java.util.Map;
import java.util.Set;
import java.util.function.Predicate;
/** Computation of reaching definitions for heap locations, relying on pointer analysis */
public class HeapReachingDefs<T extends InstanceKey> {
private static final boolean DEBUG = false;
private static final boolean VERBOSE = false;
private final ModRef<T> modRef;
private final ExtendedHeapModel heapModel;
public HeapReachingDefs(ModRef<T> modRef, ExtendedHeapModel heapModel) {
this.modRef = modRef;
this.heapModel = heapModel;
}
/**
* For each statement s, return the set of statements that may def the heap value read by s.
*
* @param node the node we are computing heap reaching defs for
* @param ir IR for the node
* @param pa governing pointer analysis
* @param mod the set of heap locations which may be written (transitively) by this node. These
* are logically return values in the SDG.
* @param statements the statements whose def-use are considered interesting
* @param exclusions heap locations that should be excluded from data dependence tracking
* @throws IllegalArgumentException if pa is null
* @throws IllegalArgumentException if statements is null
*/
@SuppressWarnings("unused")
public Map<Statement, OrdinalSet<Statement>> computeReachingDefs(
CGNode node,
IR ir,
PointerAnalysis<T> pa,
Map<CGNode, OrdinalSet<PointerKey>> mod,
Collection<Statement> statements,
HeapExclusions exclusions,
CallGraph cg) {
if (statements == null) {
throw new IllegalArgumentException("statements is null");
}
if (pa == null) {
throw new IllegalArgumentException("pa is null");
}
if (VERBOSE | DEBUG) {
System.err.println("Reaching Defs " + node);
System.err.println(statements.size());
}
if (DEBUG) {
System.err.println(ir);
}
// create a control flow graph with one instruction per basic block.
ExplodedControlFlowGraph cfg = ExplodedControlFlowGraph.make(ir);
// create a mapping between statements and integers, used in bit vectors
// shortly
OrdinalSetMapping<Statement> domain = createStatementDomain(statements);
// map SSAInstruction indices to statements
Map<Integer, NormalStatement> ssaInstructionIndex2Statement =
mapInstructionsToStatements(domain);
// solve reaching definitions as a dataflow problem
BitVectorFramework<IExplodedBasicBlock, Statement> rd =
new BitVectorFramework<>(
cfg, new RD(node, cfg, pa, domain, ssaInstructionIndex2Statement, exclusions), domain);
if (VERBOSE) {
System.err.println("Solve ");
}
BitVectorSolver<? extends ISSABasicBlock> solver = new BitVectorSolver<>(rd);
try {
solver.solve(null);
} catch (CancelException e) {
throw new CancelRuntimeException(e);
}
if (VERBOSE) {
System.err.println("Solved. ");
}
return makeResult(
solver,
domain,
node,
heapModel,
pa,
mod,
cfg,
ssaInstructionIndex2Statement,
exclusions,
cg);
}
private class RDMap implements Map<Statement, OrdinalSet<Statement>> {
final Map<Statement, OrdinalSet<Statement>> delegate = HashMapFactory.make();
private final HeapExclusions exclusions;
private final CallGraph cg;
RDMap(
BitVectorSolver<? extends ISSABasicBlock> solver,
OrdinalSetMapping<Statement> domain,
CGNode node,
ExtendedHeapModel h,
PointerAnalysis<T> pa,
Map<CGNode, OrdinalSet<PointerKey>> mod,
ExplodedControlFlowGraph cfg,
Map<Integer, NormalStatement> ssaInstructionIndex2Statement,
HeapExclusions exclusions,
CallGraph cg) {
if (VERBOSE) {
System.err.println("Init pointer Key mod ");
}
this.exclusions = exclusions;
this.cg = cg;
Map<PointerKey, MutableIntSet> pointerKeyMod = initPointerKeyMod(domain, node, h, pa);
if (VERBOSE) {
System.err.println("Eager populate");
}
eagerPopulate(
pointerKeyMod, solver, domain, node, h, pa, mod, cfg, ssaInstructionIndex2Statement);
if (VERBOSE) {
System.err.println("Done populate");
}
}
private void eagerPopulate(
Map<PointerKey, MutableIntSet> pointerKeyMod,
BitVectorSolver<? extends ISSABasicBlock> solver,
OrdinalSetMapping<Statement> domain,
CGNode node,
ExtendedHeapModel h,
PointerAnalysis<T> pa,
Map<CGNode, OrdinalSet<PointerKey>> mod,
ExplodedControlFlowGraph cfg,
Map<Integer, NormalStatement> ssaInstruction2Statement) {
for (Statement s : domain) {
delegate.put(
s,
computeResult(
s, pointerKeyMod, solver, domain, node, h, pa, mod, cfg, ssaInstruction2Statement));
}
}
/** For each pointerKey, which statements may def it */
private Map<PointerKey, MutableIntSet> initPointerKeyMod(
OrdinalSetMapping<Statement> domain,
CGNode node,
ExtendedHeapModel h,
PointerAnalysis<T> pa) {
Map<PointerKey, MutableIntSet> pointerKeyMod = HashMapFactory.make();
for (Statement s : domain) {
switch (s.getKind()) {
case HEAP_PARAM_CALLEE:
case HEAP_RET_CALLER:
{
HeapStatement hs = (HeapStatement) s;
MutableIntSet set = findOrCreateIntSet(pointerKeyMod, hs.getLocation());
set.add(domain.getMappedIndex(s));
break;
}
default:
{
Collection<PointerKey> m = getMod(s, node, h, pa, exclusions);
for (PointerKey p : m) {
MutableIntSet set = findOrCreateIntSet(pointerKeyMod, p);
set.add(domain.getMappedIndex(s));
}
break;
}
}
}
return pointerKeyMod;
}
private MutableIntSet findOrCreateIntSet(Map<PointerKey, MutableIntSet> map, PointerKey key) {
MutableIntSet result = map.get(key);
if (result == null) {
result = MutableSparseIntSet.makeEmpty();
map.put(key, result);
}
return result;
}
@Override
public String toString() {
return delegate.toString();
}
@Override
public void clear() {
Assertions.UNREACHABLE();
delegate.clear();
}
@Override
public boolean containsKey(Object key) {
Assertions.UNREACHABLE();
return delegate.containsKey(key);
}
@Override
public boolean containsValue(Object value) {
Assertions.UNREACHABLE();
return delegate.containsValue(value);
}
@Override
public Set<Entry<Statement, OrdinalSet<Statement>>> entrySet() {
return delegate.entrySet();
}
@Override
public boolean equals(Object o) {
Assertions.UNREACHABLE();
return delegate.equals(o);
}
@Override
public OrdinalSet<Statement> get(Object key) {
return delegate.get(key);
}
@Override
public int hashCode() {
Assertions.UNREACHABLE();
return delegate.hashCode();
}
@Override
public boolean isEmpty() {
Assertions.UNREACHABLE();
return delegate.isEmpty();
}
@Override
public Set<Statement> keySet() {
return delegate.keySet();
}
@Override
public OrdinalSet<Statement> put(Statement key, OrdinalSet<Statement> value) {
Assertions.UNREACHABLE();
return delegate.put(key, value);
}
@Override
public void putAll(Map<? extends Statement, ? extends OrdinalSet<Statement>> t) {
Assertions.UNREACHABLE();
delegate.putAll(t);
}
@Override
public OrdinalSet<Statement> remove(Object key) {
Assertions.UNREACHABLE();
return delegate.remove(key);
}
@Override
public int size() {
Assertions.UNREACHABLE();
return delegate.size();
}
@Override
public Collection<OrdinalSet<Statement>> values() {
Assertions.UNREACHABLE();
return delegate.values();
}
/** For a statement s, compute the set of statements that may def the heap value read by s. */
OrdinalSet<Statement> computeResult(
Statement s,
Map<PointerKey, MutableIntSet> pointerKeyMod,
BitVectorSolver<? extends ISSABasicBlock> solver,
OrdinalSetMapping<Statement> domain,
CGNode node,
ExtendedHeapModel h,
PointerAnalysis<T> pa,
Map<CGNode, OrdinalSet<PointerKey>> mod,
ExplodedControlFlowGraph cfg,
Map<Integer, NormalStatement> ssaInstructionIndex2Statement) {
switch (s.getKind()) {
case NORMAL:
NormalStatement n = (NormalStatement) s;
Collection<PointerKey> ref = modRef.getRef(node, h, pa, n.getInstruction(), exclusions);
if (!ref.isEmpty()) {
ISSABasicBlock bb = cfg.getBlockForInstruction(n.getInstructionIndex());
BitVectorVariable v = solver.getIn(bb);
MutableSparseIntSet defs = MutableSparseIntSet.makeEmpty();
if (v.getValue() != null) {
for (PointerKey p : ref) {
if (pointerKeyMod.get(p) != null) {
defs.addAll(pointerKeyMod.get(p).intersection(v.getValue()));
}
}
}
return new OrdinalSet<>(defs, domain);
} else {
return OrdinalSet.empty();
}
case HEAP_RET_CALLEE:
{
HeapStatement.HeapReturnCallee r = (HeapStatement.HeapReturnCallee) s;
PointerKey p = r.getLocation();
BitVectorVariable v = solver.getIn(cfg.exit());
if (DEBUG) {
System.err.println(
"computeResult " + cfg.exit() + ' ' + s + ' ' + pointerKeyMod.get(p) + ' ' + v);
}
if (pointerKeyMod.get(p) == null) {
return OrdinalSet.empty();
}
return new OrdinalSet<>(pointerKeyMod.get(p).intersection(v.getValue()), domain);
}
case HEAP_RET_CALLER:
{
HeapStatement.HeapReturnCaller r = (HeapStatement.HeapReturnCaller) s;
ISSABasicBlock bb = cfg.getBlockForInstruction(r.getCallIndex());
BitVectorVariable v = solver.getIn(bb);
if (allCalleesMod(cg, r, mod)
|| pointerKeyMod.get(r.getLocation()) == null
|| v.getValue() == null) {
// do nothing ... force flow into and out of the callees
return OrdinalSet.empty();
} else {
// the defs that flow to the call may flow to this return, since
// the callees may have no relevant effect.
return new OrdinalSet<>(
pointerKeyMod.get(r.getLocation()).intersection(v.getValue()), domain);
}
}
case HEAP_PARAM_CALLER:
{
HeapStatement.HeapParamCaller r = (HeapStatement.HeapParamCaller) s;
NormalStatement call = ssaInstructionIndex2Statement.get(r.getCallIndex());
ISSABasicBlock callBlock = cfg.getBlockForInstruction(call.getInstructionIndex());
if (callBlock.isEntryBlock()) {
int x =
domain.getMappedIndex(new HeapStatement.HeapParamCallee(node, r.getLocation()));
assert x >= 0;
IntSet xset = SparseIntSet.singleton(x);
return new OrdinalSet<>(xset, domain);
}
BitVectorVariable v = solver.getIn(callBlock);
if (pointerKeyMod.get(r.getLocation()) == null || v.getValue() == null) {
// do nothing ... force flow into and out of the callees
return OrdinalSet.empty();
} else {
return new OrdinalSet<>(
pointerKeyMod.get(r.getLocation()).intersection(v.getValue()), domain);
}
}
case HEAP_PARAM_CALLEE:
// no statements in this method will def the heap being passed in
case NORMAL_RET_CALLEE:
case NORMAL_RET_CALLER:
case PARAM_CALLEE:
case PARAM_CALLER:
case EXC_RET_CALLEE:
case EXC_RET_CALLER:
case PHI:
case PI:
case CATCH:
case METHOD_ENTRY:
case METHOD_EXIT:
return OrdinalSet.empty();
default:
Assertions.UNREACHABLE(s.getKind().toString());
return null;
}
}
}
/** For each statement s, compute the set of statements that may def the heap value read by s. */
private Map<Statement, OrdinalSet<Statement>> makeResult(
BitVectorSolver<? extends ISSABasicBlock> solver,
OrdinalSetMapping<Statement> domain,
CGNode node,
ExtendedHeapModel h,
PointerAnalysis<T> pa,
Map<CGNode, OrdinalSet<PointerKey>> mod,
ExplodedControlFlowGraph cfg,
Map<Integer, NormalStatement> ssaInstructionIndex2Statement,
HeapExclusions exclusions,
CallGraph cg) {
return new RDMap(
solver, domain, node, h, pa, mod, cfg, ssaInstructionIndex2Statement, exclusions, cg);
}
/** Do all callees corresponding to the given call site def the pointer key being tracked by r? */
private static boolean allCalleesMod(
CallGraph cg, HeapReturnCaller r, Map<CGNode, OrdinalSet<PointerKey>> mod) {
Collection<CGNode> targets = cg.getPossibleTargets(r.getNode(), r.getCall().getCallSite());
if (targets.isEmpty()) {
return false;
}
for (CGNode t : targets) {
if (!mod.get(t).contains(r.getLocation())) {
return false;
}
}
return true;
}
private Collection<PointerKey> getMod(
Statement s,
CGNode n,
ExtendedHeapModel h,
PointerAnalysis<T> pa,
HeapExclusions exclusions) {
switch (s.getKind()) {
case NORMAL:
NormalStatement ns = (NormalStatement) s;
return modRef.getMod(n, h, pa, ns.getInstruction(), exclusions);
case HEAP_PARAM_CALLEE:
case HEAP_RET_CALLER:
HeapStatement hs = (HeapStatement) s;
return Collections.singleton(hs.getLocation());
case HEAP_RET_CALLEE:
case HEAP_PARAM_CALLER:
case EXC_RET_CALLEE:
case EXC_RET_CALLER:
case NORMAL_RET_CALLEE:
case NORMAL_RET_CALLER:
case PARAM_CALLEE:
case PARAM_CALLER:
case PHI:
case PI:
case METHOD_ENTRY:
case METHOD_EXIT:
case CATCH:
// doesn't mod anything in the heap.
return Collections.emptySet();
default:
Assertions.UNREACHABLE(s.getKind() + " " + s);
return null;
}
}
/** map each SSAInstruction index to the NormalStatement which represents it. */
private static Map<Integer, NormalStatement> mapInstructionsToStatements(
OrdinalSetMapping<Statement> domain) {
Map<Integer, NormalStatement> result = HashMapFactory.make();
for (Statement s : domain) {
if (s.getKind().equals(Kind.NORMAL)) {
NormalStatement n = (NormalStatement) s;
result.put(n.getInstructionIndex(), n);
}
}
return result;
}
private static OrdinalSetMapping<Statement> createStatementDomain(
Collection<Statement> statements) {
Statement[] arr = new Statement[statements.size()];
OrdinalSetMapping<Statement> domain = new ObjectArrayMapping<>(statements.toArray(arr));
return domain;
}
/** Reaching def flow functions */
private class RD implements ITransferFunctionProvider<IExplodedBasicBlock, BitVectorVariable> {
private final CGNode node;
private final ExplodedControlFlowGraph cfg;
private final OrdinalSetMapping<Statement> domain;
private final PointerAnalysis<T> pa;
private final Map<Integer, NormalStatement> ssaInstructionIndex2Statement;
private final HeapExclusions exclusions;
/**
* if (i,j) \in heapReturnCaller, then statement j is a HeapStatement.ReturnCaller for statement
* i, a NormalStatement representing an invoke
*/
private final IBinaryNaturalRelation heapReturnCaller = new BasicNaturalRelation();
public RD(
CGNode node,
ExplodedControlFlowGraph cfg,
PointerAnalysis<T> pa2,
OrdinalSetMapping<Statement> domain,
Map<Integer, NormalStatement> ssaInstructionIndex2Statement,
HeapExclusions exclusions) {
this.node = node;
this.cfg = cfg;
this.domain = domain;
this.pa = pa2;
this.ssaInstructionIndex2Statement = ssaInstructionIndex2Statement;
this.exclusions = exclusions;
initHeapReturnCaller();
}
private void initHeapReturnCaller() {
for (Statement s : domain) {
if (s.getKind().equals(Kind.HEAP_RET_CALLER)) {
if (DEBUG) {
System.err.println("initHeapReturnCaller " + s);
}
HeapStatement.HeapReturnCaller r = (HeapReturnCaller) s;
NormalStatement call = ssaInstructionIndex2Statement.get(r.getCallIndex());
int i = domain.getMappedIndex(call);
int j = domain.getMappedIndex(r);
heapReturnCaller.add(i, j);
}
}
}
@Override
public UnaryOperator<BitVectorVariable> getEdgeTransferFunction(
IExplodedBasicBlock src, IExplodedBasicBlock dst) {
if (DEBUG) {
System.err.println("getEdgeXfer: " + src + ' ' + dst + ' ' + src.isEntryBlock());
}
if (src.isEntryBlock()) {
if (DEBUG) {
System.err.println("heapEntry " + heapEntryStatements());
}
return new BitVectorUnionVector(new BitVectorIntSet(heapEntryStatements()).getBitVector());
}
if (src.getInstruction() != null
&& !(src.getInstruction() instanceof SSAAbstractInvokeInstruction)
&& !cfg.getNormalSuccessors(src).contains(dst)) {
// if the edge only happens due to exceptional control flow, then no
// heap locations
// are def'ed or used
if (DEBUG) {
System.err.println("Identity");
}
return BitVectorIdentity.instance();
} else {
BitVector kill = kill(src);
IntSet gen = gen(src);
if (DEBUG) {
System.err.println("gen: " + gen + " kill: " + kill);
}
if (kill == null) {
if (gen == null) {
return BitVectorIdentity.instance();
} else {
return new BitVectorUnionVector(new BitVectorIntSet(gen).getBitVector());
}
} else {
if (gen == null) {
return new BitVectorMinusVector(kill);
} else {
return new BitVectorKillGen(kill, new BitVectorIntSet(gen).getBitVector());
}
}
}
}
@Override
public AbstractMeetOperator<BitVectorVariable> getMeetOperator() {
return BitVectorUnion.instance();
}
@Override
public UnaryOperator<BitVectorVariable> getNodeTransferFunction(IExplodedBasicBlock node) {
return null;
}
@Override
public boolean hasEdgeTransferFunctions() {
return true;
}
@Override
public boolean hasNodeTransferFunctions() {
return false;
}
/**
* @return int set representing the heap def statements that are gen'ed by the basic block. null
* if none.
*/
IntSet gen(IExplodedBasicBlock b) {
SSAInstruction s = b.getInstruction();
if (DEBUG) {
System.err.println("gen " + b + ' ' + s);
}
if (s == null) {
return null;
} else {
if (s instanceof SSAAbstractInvokeInstruction) {
// it's a normal statement ... we better be able to find it in the
// domain.
Statement st = ssaInstructionIndex2Statement.get(b.getLastInstructionIndex());
if (st == null) {
System.err.println(ssaInstructionIndex2Statement);
Assertions.UNREACHABLE("bang " + b + ' ' + b.getLastInstructionIndex() + ' ' + s);
}
int domainIndex = domain.getMappedIndex(st);
assert (domainIndex != -1);
if (DEBUG) {
System.err.println("GEN FOR " + s + ' ' + heapReturnCaller.getRelated(domainIndex));
}
return heapReturnCaller.getRelated(domainIndex);
} else {
Collection<PointerKey> gen = modRef.getMod(node, heapModel, pa, s, exclusions);
if (gen.isEmpty()) {
return null;
} else {
NormalStatement n = ssaInstructionIndex2Statement.get(b.getLastInstructionIndex());
return SparseIntSet.singleton(domain.getMappedIndex(n));
}
}
}
}
/** @return int set representing all HEAP_PARAM_CALLEE statements in the domain. */
private IntSet heapEntryStatements() {
BitVectorIntSet result = new BitVectorIntSet();
for (Statement s : domain) {
if (s.getKind().equals(Kind.HEAP_PARAM_CALLEE)) {
result.add(domain.getMappedIndex(s));
}
}
return result;
}
/**
* @return int set representing the heap def statements that are killed by the basic block. null
* if none.
*/
BitVector kill(IExplodedBasicBlock b) {
SSAInstruction s = b.getInstruction();
if (s == null) {
return null;
} else {
Collection<PointerKey> mod = modRef.getMod(node, heapModel, pa, s, exclusions);
if (mod.isEmpty()) {
return null;
} else {
// only static fields are actually killed
Predicate<PointerKey> staticFilter = StaticFieldKey.class::isInstance;
final Collection<PointerKey> kill =
Iterator2Collection.toSet(new FilterIterator<>(mod.iterator(), staticFilter));
if (kill.isEmpty()) {
return null;
} else {
Predicate<Statement> f =
s1 -> {
Collection<PointerKey> m = getMod(s1, node, heapModel, pa, exclusions);
for (PointerKey k : kill) {
if (m.contains(k)) {
return true;
}
}
return false;
};
BitVector result = new BitVector();
for (Statement k : Iterator2Iterable.make(new FilterIterator<>(domain.iterator(), f))) {
result.set(domain.getMappedIndex(k));
}
return result;
}
}
}
}
}
}
| 25,315
| 33.490463
| 100
|
java
|
WALA
|
WALA-master/core/src/main/java/com/ibm/wala/ipa/slicer/HeapStatement.java
|
/*
* Copyright (c) 2006 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.ipa.slicer;
import com.ibm.wala.ipa.callgraph.CGNode;
import com.ibm.wala.ipa.callgraph.propagation.PointerKey;
import com.ibm.wala.ssa.SSAAbstractInvokeInstruction;
public abstract class HeapStatement extends Statement {
private final PointerKey loc;
public HeapStatement(CGNode node, PointerKey loc) {
super(node);
if (loc == null) {
throw new IllegalArgumentException("loc is null");
}
this.loc = loc;
}
public static final class HeapParamCaller extends HeapStatement {
// index into the IR instruction array of the call statements
private final int callIndex;
public HeapParamCaller(CGNode node, int callIndex, PointerKey loc) {
super(node, loc);
this.callIndex = callIndex;
}
@Override
public Kind getKind() {
return Kind.HEAP_PARAM_CALLER;
}
public int getCallIndex() {
return callIndex;
}
public SSAAbstractInvokeInstruction getCall() {
return (SSAAbstractInvokeInstruction) getNode().getIR().getInstructions()[callIndex];
}
@Override
public String toString() {
return getKind().toString() + ':' + getNode() + ' ' + getLocation() + " call:" + getCall();
}
@Override
public int hashCode() {
return getLocation().hashCode() + 4289 * callIndex + 4133 * getNode().hashCode() + 8831;
}
@Override
public boolean equals(Object obj) {
// instanceof is OK because this class is final. instanceof is more efficient than getClass
if (obj instanceof HeapParamCaller) {
HeapParamCaller other = (HeapParamCaller) obj;
return getNode().equals(other.getNode())
&& getLocation().equals(other.getLocation())
&& callIndex == other.callIndex;
} else {
return false;
}
}
}
public static final class HeapParamCallee extends HeapStatement {
public HeapParamCallee(CGNode node, PointerKey loc) {
super(node, loc);
}
@Override
public Kind getKind() {
return Kind.HEAP_PARAM_CALLEE;
}
@Override
public int hashCode() {
return getLocation().hashCode() + 7727 * getNode().hashCode() + 7841;
}
@Override
public boolean equals(Object obj) {
// instanceof is ok because this class is final. instanceof is more efficient than getClass
if (obj instanceof HeapParamCallee) {
HeapParamCallee other = (HeapParamCallee) obj;
return getNode().equals(other.getNode()) && getLocation().equals(other.getLocation());
} else {
return false;
}
}
@Override
public String toString() {
return getKind().toString() + ':' + getNode() + ' ' + getLocation();
}
}
public static final class HeapReturnCaller extends HeapStatement {
// index into the instruction array of the relevant call instruction
private final int callIndex;
// private final SSAAbstractInvokeInstruction call;
public HeapReturnCaller(CGNode node, int callIndex, PointerKey loc) {
super(node, loc);
this.callIndex = callIndex;
}
@Override
public Kind getKind() {
return Kind.HEAP_RET_CALLER;
}
public int getCallIndex() {
return callIndex;
}
public SSAAbstractInvokeInstruction getCall() {
return (SSAAbstractInvokeInstruction) getNode().getIR().getInstructions()[callIndex];
}
@Override
public String toString() {
return getKind().toString() + ':' + getNode() + ' ' + getLocation() + " call:" + getCall();
}
@Override
public int hashCode() {
return getLocation().hashCode() + 8887 * callIndex + 8731 * getNode().hashCode() + 7919;
}
@Override
public boolean equals(Object obj) {
// instanceof is ok because this class is final. instanceof is more efficient than getClass
if (obj instanceof HeapReturnCaller) {
HeapReturnCaller other = (HeapReturnCaller) obj;
return getNode().equals(other.getNode())
&& getLocation().equals(other.getLocation())
&& callIndex == other.callIndex;
} else {
return false;
}
}
}
public static final class HeapReturnCallee extends HeapStatement {
public HeapReturnCallee(CGNode node, PointerKey loc) {
super(node, loc);
}
@Override
public Kind getKind() {
return Kind.HEAP_RET_CALLEE;
}
@Override
public int hashCode() {
return getLocation().hashCode() + 9533 * getNode().hashCode() + 9631;
}
@Override
public boolean equals(Object obj) {
// instanceof is ok because this class is final. instanceof is more efficient than getClass
if (obj instanceof HeapReturnCallee) {
HeapReturnCallee other = (HeapReturnCallee) obj;
return getNode().equals(other.getNode()) && getLocation().equals(other.getLocation());
} else {
return false;
}
}
@Override
public String toString() {
return getKind().toString() + ':' + getNode() + ' ' + getLocation();
}
}
public PointerKey getLocation() {
return loc;
}
}
| 5,475
| 27.520833
| 98
|
java
|
WALA
|
WALA-master/core/src/main/java/com/ibm/wala/ipa/slicer/ISDG.java
|
/*
* Copyright (c) 2006 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.ipa.slicer;
import com.ibm.wala.ipa.callgraph.CGNode;
import com.ibm.wala.ipa.callgraph.propagation.InstanceKey;
import com.ibm.wala.ipa.cha.IClassHierarchyDweller;
import com.ibm.wala.ipa.slicer.Slicer.ControlDependenceOptions;
import com.ibm.wala.util.graph.NumberedGraph;
import java.util.Iterator;
/**
* Interface for an SDG (loosely defined here as a graph of {@link Statement}s. This interface
* implies that the underlying graph is computed lazily on demand.
*/
public interface ISDG extends NumberedGraph<Statement>, IClassHierarchyDweller {
/** {@link ControlDependenceOptions} used to construct this graph. */
ControlDependenceOptions getCOptions();
/** Get the program dependence graph constructed for a particular node. */
PDG<? extends InstanceKey> getPDG(CGNode node);
/**
* Iterate over the nodes which have been discovered so far, but do <em>NOT</em> eagerly construct
* the entire graph.
*/
Iterator<? extends Statement> iterateLazyNodes();
}
| 1,378
| 35.289474
| 100
|
java
|
WALA
|
WALA-master/core/src/main/java/com/ibm/wala/ipa/slicer/MethodEntryStatement.java
|
/*
* Copyright (c) 2006 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.ipa.slicer;
import com.ibm.wala.ipa.callgraph.CGNode;
/**
* A statement representing method entry, used for managing control dependence.
*
* <p>This is also used as a dummy entry for starting propagation to a seed statement.
*/
public class MethodEntryStatement extends Statement {
public MethodEntryStatement(CGNode node) {
super(node);
}
@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass().equals(obj.getClass())) {
MethodEntryStatement other = (MethodEntryStatement) obj;
return getNode().equals(other.getNode());
} else {
return false;
}
}
@Override
public Kind getKind() {
return Kind.METHOD_ENTRY;
}
@Override
public int hashCode() {
return getKind().hashCode() + 9901 * getNode().hashCode();
}
@Override
public String toString() {
return getKind() + ":" + getNode();
}
}
| 1,310
| 23.277778
| 86
|
java
|
WALA
|
WALA-master/core/src/main/java/com/ibm/wala/ipa/slicer/MethodExitStatement.java
|
/*
* Copyright (c) 2006 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.ipa.slicer;
import com.ibm.wala.ipa.callgraph.CGNode;
/**
* A {@link Statement} representing method exit used as a dummy exit for starting propagation to a
* seed statement in backwards slicing.
*/
public class MethodExitStatement extends Statement {
public MethodExitStatement(CGNode node) {
super(node);
}
@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass().equals(obj.getClass())) {
MethodExitStatement other = (MethodExitStatement) obj;
return getNode().equals(other.getNode());
} else {
return false;
}
}
@Override
public Kind getKind() {
return Kind.METHOD_EXIT;
}
@Override
public int hashCode() {
return getKind().hashCode() + 9901 * getNode().hashCode();
}
@Override
public String toString() {
return getKind() + ":" + getNode();
}
}
| 1,274
| 23.056604
| 98
|
java
|
WALA
|
WALA-master/core/src/main/java/com/ibm/wala/ipa/slicer/NormalReturnCallee.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.slicer;
import com.ibm.wala.ipa.callgraph.CGNode;
/**
* A {@link Statement} representing the normal return value in a callee, immediately before
* returning to the caller.
*/
public class NormalReturnCallee extends Statement {
public NormalReturnCallee(CGNode node) {
super(node);
}
@Override
public Kind getKind() {
return Kind.NORMAL_RET_CALLEE;
}
}
| 770
| 24.7
| 91
|
java
|
WALA
|
WALA-master/core/src/main/java/com/ibm/wala/ipa/slicer/NormalReturnCaller.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.slicer;
import com.ibm.wala.ipa.callgraph.CGNode;
import com.ibm.wala.ssa.SSAAbstractInvokeInstruction;
/**
* A {@link Statement} representing the normal return value in a caller, immediately after returning
* to the caller.
*/
public class NormalReturnCaller extends StatementWithInstructionIndex
implements ValueNumberCarrier {
public NormalReturnCaller(CGNode node, int callIndex) {
super(node, callIndex);
}
@Override
public int getValueNumber() {
return getInstruction().getReturnValue(0);
}
@Override
public SSAAbstractInvokeInstruction getInstruction() {
return (SSAAbstractInvokeInstruction) super.getInstruction();
}
@Override
public Kind getKind() {
return Kind.NORMAL_RET_CALLER;
}
}
| 1,139
| 26.142857
| 100
|
java
|
WALA
|
WALA-master/core/src/main/java/com/ibm/wala/ipa/slicer/NormalStatement.java
|
/*
* Copyright (c) 2006 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.ipa.slicer;
import com.ibm.wala.ipa.callgraph.CGNode;
/** A statement that has a corresponding index in the SSA IR */
public class NormalStatement extends StatementWithInstructionIndex {
public NormalStatement(CGNode node, int instructionIndex) {
super(node, instructionIndex);
}
@Override
public Kind getKind() {
return Kind.NORMAL;
}
@Override
public String toString() {
StringBuilder name = new StringBuilder();
if (getInstruction().hasDef()) {
String[] names =
getNode().getIR().getLocalNames(getInstructionIndex(), getInstruction().getDef());
if (names != null && names.length > 0) {
name = new StringBuilder("[").append(names[0]);
for (int i = 1; i < names.length; i++) {
name.append(", ").append(names[i]);
}
name.append("]: ");
}
}
return "NORMAL "
+ getNode().getMethod().getName()
+ ':'
+ name
+ getInstruction().toString()
+ ' '
+ getNode();
}
}
| 1,410
| 26.666667
| 92
|
java
|
WALA
|
WALA-master/core/src/main/java/com/ibm/wala/ipa/slicer/PDG.java
|
/*
* Copyright (c) 2006 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.ipa.slicer;
import com.ibm.wala.analysis.stackMachine.AbstractIntStackMachine;
import com.ibm.wala.cfg.ControlFlowGraph;
import com.ibm.wala.cfg.cdg.ControlDependenceGraph;
import com.ibm.wala.classLoader.CallSiteReference;
import com.ibm.wala.ipa.callgraph.CGNode;
import com.ibm.wala.ipa.callgraph.CallGraph;
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.cfg.ExceptionPrunedCFG;
import com.ibm.wala.ipa.cfg.PrunedCFG;
import com.ibm.wala.ipa.modref.ExtendedHeapModel;
import com.ibm.wala.ipa.modref.ModRef;
import com.ibm.wala.ipa.slicer.Slicer.ControlDependenceOptions;
import com.ibm.wala.ipa.slicer.Slicer.DataDependenceOptions;
import com.ibm.wala.ipa.slicer.Statement.Kind;
import com.ibm.wala.ssa.DefUse;
import com.ibm.wala.ssa.IR;
import com.ibm.wala.ssa.ISSABasicBlock;
import com.ibm.wala.ssa.SSAAbstractInvokeInstruction;
import com.ibm.wala.ssa.SSAAbstractThrowInstruction;
import com.ibm.wala.ssa.SSAArrayLengthInstruction;
import com.ibm.wala.ssa.SSAArrayReferenceInstruction;
import com.ibm.wala.ssa.SSACFG;
import com.ibm.wala.ssa.SSACheckCastInstruction;
import com.ibm.wala.ssa.SSAFieldAccessInstruction;
import com.ibm.wala.ssa.SSAGetCaughtExceptionInstruction;
import com.ibm.wala.ssa.SSAInstanceofInstruction;
import com.ibm.wala.ssa.SSAInstruction;
import com.ibm.wala.ssa.SSANewInstruction;
import com.ibm.wala.ssa.SSAPhiInstruction;
import com.ibm.wala.ssa.SSAPiInstruction;
import com.ibm.wala.ssa.SSAReturnInstruction;
import com.ibm.wala.types.TypeReference;
import com.ibm.wala.util.collections.FilterIterator;
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.Iterator2Iterable;
import com.ibm.wala.util.collections.MapIterator;
import com.ibm.wala.util.collections.MapUtil;
import com.ibm.wala.util.config.SetOfClasses;
import com.ibm.wala.util.debug.Assertions;
import com.ibm.wala.util.debug.UnimplementedError;
import com.ibm.wala.util.graph.GraphUtil;
import com.ibm.wala.util.graph.dominators.Dominators;
import com.ibm.wala.util.graph.labeled.NumberedLabeledGraph;
import com.ibm.wala.util.graph.labeled.SlowSparseNumberedLabeledGraph;
import com.ibm.wala.util.intset.BitVectorIntSet;
import com.ibm.wala.util.intset.IntIterator;
import com.ibm.wala.util.intset.IntSet;
import com.ibm.wala.util.intset.OrdinalSet;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.function.Predicate;
import java.util.stream.Stream;
/** Program dependence graph for a single call graph node */
public class PDG<T extends InstanceKey> implements NumberedLabeledGraph<Statement, Dependency> {
private final SlowSparseNumberedLabeledGraph<Statement, Dependency> delegate =
new SlowSparseNumberedLabeledGraph<>();
/* END Custom change: control deps */
private static final boolean VERBOSE = false;
private final CGNode node;
private Statement[] paramCalleeStatements;
private Statement[] returnStatements;
/** TODO: using CallSiteReference is sloppy. clean it up. */
private final Map<CallSiteReference, Statement> callSite2Statement = HashMapFactory.make();
private final Map<CallSiteReference, Set<Statement>> callerParamStatements =
HashMapFactory.make();
private final Map<CallSiteReference, Set<Statement>> callerReturnStatements =
HashMapFactory.make();
private final HeapExclusions exclusions;
private final Collection<PointerKey> locationsHandled = HashSetFactory.make();
private final PointerAnalysis<T> pa;
private final ExtendedHeapModel heapModel;
private final Map<CGNode, OrdinalSet<PointerKey>> mod;
private final DataDependenceOptions dOptions;
private final ControlDependenceOptions cOptions;
private final CallGraph cg;
private final ModRef<T> modRef;
private final Map<CGNode, OrdinalSet<PointerKey>> ref;
private final boolean ignoreAllocHeapDefs;
private boolean isPopulated = false;
/**
* @param mod the set of heap locations which may be written (transitively) by this node. These
* are logically return values in the SDG.
* @param ref the set of heap locations which may be read (transitively) by this node. These are
* logically parameters in the SDG.
* @throws IllegalArgumentException if node is null
*/
public PDG(
final CGNode node,
PointerAnalysis<T> pa,
Map<CGNode, OrdinalSet<PointerKey>> mod,
Map<CGNode, OrdinalSet<PointerKey>> ref,
DataDependenceOptions dOptions,
ControlDependenceOptions cOptions,
HeapExclusions exclusions,
CallGraph cg,
ModRef<T> modRef) {
this(node, pa, mod, ref, dOptions, cOptions, exclusions, cg, modRef, false);
}
/**
* @param mod the set of heap locations which may be written (transitively) by this node. These
* are logically return values in the SDG.
* @param ref the set of heap locations which may be read (transitively) by this node. These are
* logically parameters in the SDG.
* @throws IllegalArgumentException if node is null
*/
public PDG(
final CGNode node,
PointerAnalysis<T> pa,
Map<CGNode, OrdinalSet<PointerKey>> mod,
Map<CGNode, OrdinalSet<PointerKey>> ref,
DataDependenceOptions dOptions,
ControlDependenceOptions cOptions,
HeapExclusions exclusions,
CallGraph cg,
ModRef<T> modRef,
boolean ignoreAllocHeapDefs) {
super();
if (node == null) {
throw new IllegalArgumentException("node is null");
}
this.cg = cg;
this.node = node;
this.heapModel = pa != null ? modRef.makeHeapModel(pa) : null;
this.pa = pa;
this.dOptions = dOptions;
this.cOptions = cOptions;
this.mod = mod;
this.exclusions = exclusions;
this.modRef = modRef;
this.ref = ref;
this.ignoreAllocHeapDefs = ignoreAllocHeapDefs;
}
/**
* WARNING: Since we're using a {@link HashMap} of {@link SSAInstruction}s, and equals() of {@link
* SSAInstruction} assumes a canonical representative for each instruction, we <b>must</b> ensure
* that we use the same IR object throughout initialization!!
*/
private void populate() {
if (!isPopulated) {
// ensure that we keep the single, canonical IR live throughout initialization, while the
// instructionIndices map
// is live.
IR ir = node.getIR();
isPopulated = true;
Map<SSAInstruction, Integer> instructionIndices = computeInstructionIndices(ir);
createNodes(ref, ir);
createScalarEdges(cOptions, ir, instructionIndices);
}
}
private void createScalarEdges(
ControlDependenceOptions cOptions, IR ir, Map<SSAInstruction, Integer> instructionIndices) {
createScalarDataDependenceEdges(ir, instructionIndices);
createControlDependenceEdges(cOptions, ir, instructionIndices);
}
/**
* return the set of all PARAM_CALLER and HEAP_PARAM_CALLER statements associated with a given
* call
*/
public Set<Statement> getCallerParamStatements(SSAAbstractInvokeInstruction call)
throws IllegalArgumentException {
if (call == null) {
throw new IllegalArgumentException("call == null");
}
populate();
return callerParamStatements.get(call.getCallSite());
}
/**
* return the set of all PARAM_CALLER, HEAP_PARAM_CALLER, and NORMAL statements (i.e., the actual
* call statement) associated with a given call
*/
public Set<Statement> getCallStatements(SSAAbstractInvokeInstruction call)
throws IllegalArgumentException {
Set<Statement> callerParamStatements = getCallerParamStatements(call);
Set<Statement> result = HashSetFactory.make(callerParamStatements.size() + 1);
result.addAll(callerParamStatements);
result.add(callSite2Statement.get(call.getCallSite()));
return result;
}
/**
* return the set of all NORMAL_RETURN_CALLER and HEAP_RETURN_CALLER statements associated with a
* given call.
*/
public Set<Statement> getCallerReturnStatements(SSAAbstractInvokeInstruction call)
throws IllegalArgumentException {
if (call == null) {
throw new IllegalArgumentException("call == null");
}
populate();
return callerReturnStatements.get(call.getCallSite());
}
/** Create all control dependence edges in this PDG. */
private void createControlDependenceEdges(
ControlDependenceOptions cOptions, IR ir, Map<SSAInstruction, Integer> instructionIndices) {
if (cOptions.equals(ControlDependenceOptions.NONE)) {
return;
}
if (ir == null) {
return;
}
ControlFlowGraph<SSAInstruction, ISSABasicBlock> controlFlowGraph = ir.getControlFlowGraph();
if (cOptions.isIgnoreExceptions()) {
PrunedCFG<SSAInstruction, ISSABasicBlock> prunedCFG =
ExceptionPrunedCFG.make(controlFlowGraph);
// In case the CFG has only the entry and exit nodes left
// and no edges because the only control dependencies
// were exceptional, simply return because at this point there are no nodes.
// Otherwise, later this may raise an Exception.
if (prunedCFG.getNumberOfNodes() == 2
&& prunedCFG.containsNode(controlFlowGraph.entry())
&& prunedCFG.containsNode(controlFlowGraph.exit())
&& GraphUtil.countEdges(prunedCFG) == 0) {
return;
}
controlFlowGraph = prunedCFG;
}
ControlDependenceGraph<ISSABasicBlock> cdg = new ControlDependenceGraph<>(controlFlowGraph);
for (ISSABasicBlock bb : cdg) {
if (bb.isExitBlock()) {
// nothing should be control-dependent on the exit block.
continue;
}
Statement src = null;
if (bb.isEntryBlock()) {
src = new MethodEntryStatement(node);
} else {
SSAInstruction s = ir.getInstructions()[bb.getLastInstructionIndex()];
if (s == null) {
// should have no control dependent successors.
// leave src null.
} else {
src = ssaInstruction2Statement(s, ir, instructionIndices);
// add edges from call statements to parameter passing and return
// SJF: Alexey and I think that we should just define ParamStatements
// as
// being control dependent on nothing ... they only represent pure
// data dependence. So, I'm commenting out the following.
// if (s instanceof SSAAbstractInvokeInstruction) {
// SSAAbstractInvokeInstruction call = (SSAAbstractInvokeInstruction)
// s;
// for (Statement st : callerParamStatements.get(call.getCallSite()))
// {
// addEdge(src, st);
// }
// for (Statement st : callerReturnStatements.get(call.getCallSite()))
// {
// addEdge(src, st);
// }
// }
}
}
// add edges for every control-dependent statement in the IR, if there are
// any
// control-dependent successors
if (src != null) {
for (ISSABasicBlock bb2 : Iterator2Iterable.make(cdg.getSuccNodes(bb))) {
for (SSAInstruction st : bb2) {
if (st != null) {
Statement dest = ssaInstruction2Statement(st, ir, instructionIndices);
assert src != null;
delegate.addEdge(src, dest, Dependency.CONTROL_DEP);
}
}
}
}
}
// the CDG does not represent control dependences from the entry node.
// add these manually
// We add control dependences to all instructions in all basic blocks B that _must_ execute.
// B is the set of blocks that dominate the exit basic block
Statement methodEntry = new MethodEntryStatement(node);
Dominators<ISSABasicBlock> dom = Dominators.make(controlFlowGraph, controlFlowGraph.entry());
for (ISSABasicBlock exitDom : Iterator2Iterable.make(dom.dominators(controlFlowGraph.exit()))) {
for (SSAInstruction st : exitDom) {
Statement dest = ssaInstruction2Statement(st, ir, instructionIndices);
delegate.addEdge(methodEntry, dest, Dependency.CONTROL_DEP);
}
}
// add CD from method entry to all callee parameter assignments
// SJF: Alexey and I think that we should just define ParamStatements as
// being control dependent on nothing ... they only represent pure
// data dependence. So, I'm commenting out the following.
// for (int i = 0; i < paramCalleeStatements.length; i++) {
// addEdge(methodEntry, paramCalleeStatements[i]);
// }
/*
* JTD: While phi nodes live in a particular basic block, they represent a meet of values from
* multiple blocks. Hence, they are really like multiple statements that are control dependent
* in the manner of the predecessor blocks. When the slicer is following both data and control
* dependences, it therefore seems right to add control dependence edges to represent how a phi
* node depends on predecessor blocks.
*/
if (!dOptions.equals(DataDependenceOptions.NONE)) {
for (ISSABasicBlock bb : cdg) {
for (SSAPhiInstruction phi : Iterator2Iterable.make(bb.iteratePhis())) {
Statement phiSt = ssaInstruction2Statement(phi, ir, instructionIndices);
int phiUseIndex = 0;
for (ISSABasicBlock pb : Iterator2Iterable.make(controlFlowGraph.getPredNodes(bb))) {
int use = phi.getUse(phiUseIndex);
if (use == AbstractIntStackMachine.TOP) {
// the predecessor is part of some infeasible bytecode. we probably don't want slices
// to include such code, so ignore.
continue;
}
if (controlFlowGraph.getSuccNodeCount(pb) > 1) {
// in this case, there is more than one edge from the
// predecessor block, hence the phi node actually
// depends on the last instruction in the previous
// block, rather than having the same dependences as
// statements in that block.
SSAInstruction pss = ir.getInstructions()[pb.getLastInstructionIndex()];
assert pss != null;
Statement pst = ssaInstruction2Statement(pss, ir, instructionIndices);
delegate.addEdge(pst, phiSt, Dependency.CONTROL_DEP);
} else {
for (ISSABasicBlock cpb : Iterator2Iterable.make(cdg.getPredNodes(pb))) {
/* BEGIN Custom change: control deps */
if (cpb.getLastInstructionIndex() < 0) {
continue;
}
/* END Custom change: control deps */
SSAInstruction cps = ir.getInstructions()[cpb.getLastInstructionIndex()];
assert cps != null
: "unexpected null final instruction for CDG predecessor "
+ cpb
+ " in node "
+ node;
Statement cpst = ssaInstruction2Statement(cps, ir, instructionIndices);
delegate.addEdge(cpst, phiSt, Dependency.CONTROL_DEP);
}
}
phiUseIndex++;
}
}
}
}
}
/**
* Create all data dependence edges in this PDG.
*
* <p>Scalar dependences are taken from SSA def-use information.
*
* <p>Heap dependences are computed by a reaching defs analysis.
*/
private void createScalarDataDependenceEdges(
IR ir, Map<SSAInstruction, Integer> instructionIndices) {
if (dOptions.equals(DataDependenceOptions.NONE)) {
return;
}
if (ir == null) {
return;
}
// this is tricky .. I'm explicitly creating a new DefUse to make sure it refers to the
// instructions we need from
// the "one true" ir of the moment.
DefUse DU = new DefUse(ir);
SSAInstruction[] instructions = ir.getInstructions();
//
// TODO: teach some other bit of code about the uses of
// GetCaughtException, and then delete this code.
//
if (!dOptions.isIgnoreExceptions()) {
for (ISSABasicBlock bb : ir.getControlFlowGraph()) {
if (bb.isCatchBlock()) {
SSACFG.ExceptionHandlerBasicBlock ehbb = (SSACFG.ExceptionHandlerBasicBlock) bb;
if (ehbb.getCatchInstruction() != null) {
Statement c =
ssaInstruction2Statement(ehbb.getCatchInstruction(), ir, instructionIndices);
for (ISSABasicBlock pb : ir.getControlFlowGraph().getExceptionalPredecessors(ehbb)) {
SSAInstruction st = instructions[pb.getLastInstructionIndex()];
if (st instanceof SSAAbstractInvokeInstruction) {
delegate.addEdge(
new ExceptionalReturnCaller(node, pb.getLastInstructionIndex()),
c,
Dependency.DATA_DEP);
} else if (st instanceof SSAAbstractThrowInstruction) {
delegate.addEdge(
ssaInstruction2Statement(st, ir, instructionIndices), c, Dependency.DATA_DEP);
}
}
}
}
}
}
for (Statement s : this) {
switch (s.getKind()) {
case NORMAL:
case CATCH:
case PI:
case PHI:
{
SSAInstruction statement = statement2SSAInstruction(instructions, s);
// note that data dependencies from invoke instructions will pass
// interprocedurally
if (!(statement instanceof SSAAbstractInvokeInstruction)) {
if (dOptions.isTerminateAtCast() && (statement instanceof SSACheckCastInstruction)) {
break;
}
if (dOptions.isTerminateAtCast() && (statement instanceof SSAInstanceofInstruction)) {
break;
}
// add edges from this statement to every use of the def of this
// statement
for (int i = 0; i < statement.getNumberOfDefs(); i++) {
int def = statement.getDef(i);
for (SSAInstruction use : Iterator2Iterable.make(DU.getUses(def))) {
if (dOptions.isIgnoreBasePtrs()) {
if (use instanceof SSANewInstruction) {
// cut out array length parameters
continue;
}
if (hasBasePointer(use)) {
int base = getBasePointer(use);
if (def == base) {
// skip the edge to the base pointer
continue;
}
if (use instanceof SSAArrayReferenceInstruction) {
SSAArrayReferenceInstruction arr = (SSAArrayReferenceInstruction) use;
if (def == arr.getIndex()) {
// skip the edge to the array index
continue;
}
}
}
}
Statement u = ssaInstruction2Statement(use, ir, instructionIndices);
delegate.addEdge(s, u, Dependency.DATA_DEP);
}
}
}
break;
}
case EXC_RET_CALLER:
case NORMAL_RET_CALLER:
case PARAM_CALLEE:
{
if (dOptions.isIgnoreExceptions()) {
assert !s.getKind().equals(Kind.EXC_RET_CALLER);
}
ValueNumberCarrier a = (ValueNumberCarrier) s;
for (SSAInstruction use : Iterator2Iterable.make(DU.getUses(a.getValueNumber()))) {
if (dOptions.isIgnoreBasePtrs()) {
if (use instanceof SSANewInstruction) {
// cut out array length parameters
continue;
}
if (hasBasePointer(use)) {
int base = getBasePointer(use);
if (a.getValueNumber() == base) {
// skip the edge to the base pointer
continue;
}
if (use instanceof SSAArrayReferenceInstruction) {
SSAArrayReferenceInstruction arr = (SSAArrayReferenceInstruction) use;
if (a.getValueNumber() == arr.getIndex()) {
// skip the edge to the array index
continue;
}
}
}
}
Statement u = ssaInstruction2Statement(use, ir, instructionIndices);
delegate.addEdge(s, u, Dependency.DATA_DEP);
}
break;
}
case NORMAL_RET_CALLEE:
for (NormalStatement ret : computeReturnStatements(ir)) {
delegate.addEdge(ret, s, Dependency.DATA_DEP);
}
break;
case EXC_RET_CALLEE:
if (dOptions.isIgnoreExceptions()) {
Assertions.UNREACHABLE();
}
// TODO: this is overly conservative. deal with catch blocks?
for (IntIterator ii = getPEIs(ir).intIterator(); ii.hasNext(); ) {
int index = ii.next();
SSAInstruction pei = ir.getInstructions()[index];
if (dOptions.isTerminateAtCast() && (pei instanceof SSACheckCastInstruction)) {
continue;
}
if (pei instanceof SSAAbstractInvokeInstruction) {
if (!dOptions.isIgnoreExceptions()) {
Statement st = new ExceptionalReturnCaller(node, index);
delegate.addEdge(st, s, Dependency.DATA_DEP);
}
} else {
delegate.addEdge(new NormalStatement(node, index), s, Dependency.DATA_DEP);
}
}
break;
case PARAM_CALLER:
{
ParamCaller pac = (ParamCaller) s;
int vn = pac.getValueNumber();
// note that if the caller is the fake root method and the parameter
// type is primitive,
// it's possible to have a value number of -1. If so, just ignore it.
if (vn > -1) {
if (ir.getSymbolTable().isParameter(vn)) {
Statement a = new ParamCallee(node, vn);
delegate.addEdge(a, pac, Dependency.DATA_DEP);
} else {
SSAInstruction d = DU.getDef(vn);
if (dOptions.isTerminateAtCast() && (d instanceof SSACheckCastInstruction)) {
break;
}
if (d != null) {
if (d instanceof SSAAbstractInvokeInstruction) {
SSAAbstractInvokeInstruction call = (SSAAbstractInvokeInstruction) d;
if (vn == call.getException()) {
if (!dOptions.isIgnoreExceptions()) {
Statement st = new ExceptionalReturnCaller(node, instructionIndices.get(d));
delegate.addEdge(st, pac, Dependency.DATA_DEP);
}
} else {
Statement st = new NormalReturnCaller(node, instructionIndices.get(d));
delegate.addEdge(st, pac, Dependency.DATA_DEP);
}
} else {
Statement ds = ssaInstruction2Statement(d, ir, instructionIndices);
delegate.addEdge(ds, pac, Dependency.DATA_DEP);
}
}
}
}
}
break;
case HEAP_RET_CALLEE:
case HEAP_RET_CALLER:
case HEAP_PARAM_CALLER:
case HEAP_PARAM_CALLEE:
case METHOD_ENTRY:
case METHOD_EXIT:
// do nothing
break;
default:
Assertions.UNREACHABLE(s.toString());
break;
}
}
}
private static class SingletonSet extends SetOfClasses implements Serializable {
/* Serial version */
private static final long serialVersionUID = -3256390509887654324L;
private final TypeReference t;
SingletonSet(TypeReference t) {
this.t = t;
}
@Override
public void add(String klass) {
Assertions.UNREACHABLE();
}
@Override
public boolean contains(String klassName) {
return t.getName().toString().substring(1).equals(klassName);
}
}
private static class SetComplement extends SetOfClasses implements Serializable {
/* Serial version */
private static final long serialVersionUID = -3256390509887654323L;
private final SetOfClasses set;
SetComplement(SetOfClasses set) {
this.set = set;
}
static SetComplement complement(SetOfClasses set) {
return new SetComplement(set);
}
@Override
public void add(String klass) {
Assertions.UNREACHABLE();
}
@Override
public boolean contains(String klassName) {
return !set.contains(klassName);
}
}
/** Create heap data dependence edges in this PDG relevant to a particular {@link PointerKey}. */
private void createHeapDataDependenceEdges(final PointerKey pk) {
if (locationsHandled.contains(pk)) {
return;
} else {
locationsHandled.add(pk);
}
if (dOptions.isIgnoreHeap() || (exclusions != null && exclusions.excludes(pk))) {
return;
}
TypeReference t = HeapExclusions.getType(pk);
if (t == null) {
return;
}
// It's OK to create a new IR here; we're not keeping any hashing live up to this point
IR ir = node.getIR();
if (ir == null) {
return;
}
if (VERBOSE) {
System.err.println("Location " + pk);
}
// in reaching defs calculation, exclude heap statements that are
// irrelevant.
Predicate<Statement> f =
o -> {
if (o instanceof HeapStatement) {
HeapStatement h = (HeapStatement) o;
return h.getLocation().equals(pk);
} else {
return true;
}
};
Collection<Statement> relevantStatements =
Iterator2Collection.toSet(new FilterIterator<>(iterator(), f));
Map<Statement, OrdinalSet<Statement>> heapReachingDefs =
new HeapReachingDefs<>(modRef, heapModel)
.computeReachingDefs(
node,
ir,
pa,
mod,
relevantStatements,
new HeapExclusions(SetComplement.complement(new SingletonSet(t))),
cg);
for (Map.Entry<Statement, OrdinalSet<Statement>> entry : heapReachingDefs.entrySet()) {
switch (entry.getKey().getKind()) {
case NORMAL:
case CATCH:
case PHI:
case PI:
{
OrdinalSet<Statement> defs = entry.getValue();
if (defs != null) {
for (Statement def : defs) {
delegate.addEdge(def, entry.getKey(), Dependency.HEAP_DATA_DEP);
}
}
}
break;
case EXC_RET_CALLER:
case NORMAL_RET_CALLER:
case PARAM_CALLEE:
case NORMAL_RET_CALLEE:
case PARAM_CALLER:
case EXC_RET_CALLEE:
break;
case HEAP_RET_CALLEE:
case HEAP_RET_CALLER:
case HEAP_PARAM_CALLER:
{
OrdinalSet<Statement> defs = entry.getValue();
if (defs != null) {
for (Statement def : defs) {
delegate.addEdge(def, entry.getKey(), Dependency.DATA_DEP);
}
}
break;
}
case HEAP_PARAM_CALLEE:
case METHOD_ENTRY:
case METHOD_EXIT:
// do nothing .. there are no incoming edges
break;
default:
Assertions.UNREACHABLE(entry.getKey().toString());
break;
}
}
}
private static boolean hasBasePointer(SSAInstruction use) {
if (use instanceof SSAFieldAccessInstruction) {
SSAFieldAccessInstruction f = (SSAFieldAccessInstruction) use;
return !f.isStatic();
} else if (use instanceof SSAArrayReferenceInstruction) {
return true;
} else if (use instanceof SSAArrayLengthInstruction) {
return true;
} else {
return false;
}
}
private static int getBasePointer(SSAInstruction use) {
if (use instanceof SSAFieldAccessInstruction) {
SSAFieldAccessInstruction f = (SSAFieldAccessInstruction) use;
return f.getRef();
} else if (use instanceof SSAArrayReferenceInstruction) {
SSAArrayReferenceInstruction a = (SSAArrayReferenceInstruction) use;
return a.getArrayRef();
} else if (use instanceof SSAArrayLengthInstruction) {
SSAArrayLengthInstruction s = (SSAArrayLengthInstruction) use;
return s.getArrayRef();
} else {
Assertions.UNREACHABLE("BOOM");
return -1;
}
}
/** @return Statements representing each return instruction in the ir */
private Collection<NormalStatement> computeReturnStatements(final IR ir) {
Predicate<Statement> filter =
o -> {
if (o instanceof NormalStatement) {
NormalStatement s = (NormalStatement) o;
SSAInstruction st = ir.getInstructions()[s.getInstructionIndex()];
return st instanceof SSAReturnInstruction;
} else {
return false;
}
};
return Iterator2Collection.toSet(
new MapIterator<>(new FilterIterator<>(iterator(), filter), NormalStatement.class::cast));
}
/** @return {@link IntSet} representing instruction indices of each PEI in the ir */
private static IntSet getPEIs(final IR ir) {
BitVectorIntSet result = new BitVectorIntSet();
for (int i = 0; i < ir.getInstructions().length; i++) {
if (ir.getInstructions()[i] != null && ir.getInstructions()[i].isPEI()) {
result.add(i);
}
}
return result;
}
/**
* Wrap an {@link SSAInstruction} in a {@link Statement}. WARNING: Since we're using a {@link
* HashMap} of {@link SSAInstruction}s, and equals() of {@link SSAInstruction} assumes a canonical
* representative for each instruction, we <b>must</b> ensure that we use the same IR object
* throughout initialization!!
*/
private Statement ssaInstruction2Statement(
SSAInstruction s, IR ir, Map<SSAInstruction, Integer> instructionIndices) {
return ssaInstruction2Statement(node, s, instructionIndices, ir);
}
public static synchronized Statement ssaInstruction2Statement(
CGNode node, SSAInstruction s, Map<SSAInstruction, Integer> instructionIndices, IR ir) {
if (node == null) {
throw new IllegalArgumentException("null node");
}
if (s == null) {
throw new IllegalArgumentException("null s");
}
if (s instanceof SSAPhiInstruction) {
SSAPhiInstruction phi = (SSAPhiInstruction) s;
return new PhiStatement(node, phi);
} else if (s instanceof SSAPiInstruction) {
SSAPiInstruction pi = (SSAPiInstruction) s;
return new PiStatement(node, pi);
} else if (s instanceof SSAGetCaughtExceptionInstruction) {
return new GetCaughtExceptionStatement(node, ((SSAGetCaughtExceptionInstruction) s));
} else {
Integer x = instructionIndices.get(s);
if (x == null) {
Assertions.UNREACHABLE(s + "\nnot found in map of\n" + ir);
}
return new NormalStatement(node, x);
}
}
/** @return for each SSAInstruction, its instruction index in the ir instruction array */
public static Map<SSAInstruction, Integer> computeInstructionIndices(IR ir) {
Map<SSAInstruction, Integer> result = HashMapFactory.make();
if (ir != null) {
SSAInstruction[] instructions = ir.getInstructions();
for (int i = 0; i < instructions.length; i++) {
SSAInstruction s = instructions[i];
if (s != null) {
result.put(s, i);
}
}
}
return result;
}
/** Convert a NORMAL or PHI Statement to an SSAInstruction */
private static SSAInstruction statement2SSAInstruction(
SSAInstruction[] instructions, Statement s) {
SSAInstruction statement = null;
switch (s.getKind()) {
case NORMAL:
NormalStatement n = (NormalStatement) s;
statement = instructions[n.getInstructionIndex()];
break;
case PHI:
PhiStatement p = (PhiStatement) s;
statement = p.getPhi();
break;
case PI:
PiStatement ps = (PiStatement) s;
statement = ps.getPi();
break;
case CATCH:
GetCaughtExceptionStatement g = (GetCaughtExceptionStatement) s;
statement = g.getInstruction();
break;
default:
Assertions.UNREACHABLE(s.toString());
}
return statement;
}
/** Create all nodes in this PDG. Each node is a Statement. */
private void createNodes(Map<CGNode, OrdinalSet<PointerKey>> ref, IR ir) {
if (ir != null) {
createNormalStatements(ir, ref);
createSpecialStatements(ir);
}
createCalleeParams();
createReturnStatements();
delegate.addNode(new MethodEntryStatement(node));
delegate.addNode(new MethodExitStatement(node));
}
/** create nodes representing defs of the return values */
private void createReturnStatements() {
ArrayList<Statement> list = new ArrayList<>();
if (!node.getMethod().getReturnType().equals(TypeReference.Void)) {
NormalReturnCallee n = new NormalReturnCallee(node);
delegate.addNode(n);
list.add(n);
}
if (!dOptions.isIgnoreExceptions()) {
ExceptionalReturnCallee e = new ExceptionalReturnCallee(node);
delegate.addNode(e);
list.add(e);
}
if (!dOptions.isIgnoreHeap()) {
for (PointerKey p : mod.get(node)) {
Statement h = new HeapStatement.HeapReturnCallee(node, p);
delegate.addNode(h);
list.add(h);
}
}
returnStatements = new Statement[list.size()];
list.toArray(returnStatements);
}
/** create nodes representing defs of formal parameters */
private void createCalleeParams() {
if (paramCalleeStatements == null) {
ArrayList<Statement> list = new ArrayList<>();
int paramCount = node.getMethod().getNumberOfParameters();
for (int i = 1; i <= paramCount; i++) {
ParamCallee s = new ParamCallee(node, i);
delegate.addNode(s);
list.add(s);
}
if (!dOptions.isIgnoreHeap()) {
for (PointerKey p : ref.get(node)) {
Statement h = new HeapStatement.HeapParamCallee(node, p);
delegate.addNode(h);
list.add(h);
}
}
paramCalleeStatements = new Statement[list.size()];
list.toArray(paramCalleeStatements);
}
}
/**
* Create nodes corresponding to
*
* <ul>
* <li>phi instructions
* <li>getCaughtExceptions
* </ul>
*/
private void createSpecialStatements(IR ir) {
// create a node for instructions which do not correspond to bytecode
for (SSAInstruction s : Iterator2Iterable.make(ir.iterateAllInstructions())) {
if (s instanceof SSAPhiInstruction) {
delegate.addNode(new PhiStatement(node, (SSAPhiInstruction) s));
} else if (s instanceof SSAGetCaughtExceptionInstruction) {
delegate.addNode(
new GetCaughtExceptionStatement(node, (SSAGetCaughtExceptionInstruction) s));
} else if (s instanceof SSAPiInstruction) {
delegate.addNode(new PiStatement(node, (SSAPiInstruction) s));
}
}
}
/** Create nodes in the graph corresponding to "normal" (bytecode) instructions */
private void createNormalStatements(IR ir, Map<CGNode, OrdinalSet<PointerKey>> ref) {
// create a node for every normal instruction in the IR
SSAInstruction[] instructions = ir.getInstructions();
for (int i = 0; i < instructions.length; i++) {
SSAInstruction s = instructions[i];
if (s instanceof SSAGetCaughtExceptionInstruction) {
continue;
}
if (s != null) {
final NormalStatement statement = new NormalStatement(node, i);
delegate.addNode(statement);
if (s instanceof SSAAbstractInvokeInstruction) {
callSite2Statement.put(((SSAAbstractInvokeInstruction) s).getCallSite(), statement);
addParamPassingStatements(i, ref, ir);
}
}
}
}
/** Create nodes in the graph corresponding to in/out parameter passing for a call instruction */
private void addParamPassingStatements(
int callIndex, Map<CGNode, OrdinalSet<PointerKey>> ref, IR ir) {
SSAAbstractInvokeInstruction call =
(SSAAbstractInvokeInstruction) ir.getInstructions()[callIndex];
Collection<Statement> params =
MapUtil.findOrCreateSet(callerParamStatements, call.getCallSite());
Collection<Statement> rets =
MapUtil.findOrCreateSet(callerReturnStatements, call.getCallSite());
for (int j = 0; j < call.getNumberOfUses(); j++) {
Statement st = new ParamCaller(node, callIndex, call.getUse(j));
delegate.addNode(st);
params.add(st);
}
if (!call.getDeclaredResultType().equals(TypeReference.Void)) {
Statement st = new NormalReturnCaller(node, callIndex);
delegate.addNode(st);
rets.add(st);
}
{
if (!dOptions.isIgnoreExceptions()) {
Statement st = new ExceptionalReturnCaller(node, callIndex);
delegate.addNode(st);
rets.add(st);
}
}
if (!dOptions.isIgnoreHeap()) {
OrdinalSet<PointerKey> uref = unionHeapLocations(cg, node, call, ref);
for (PointerKey p : uref) {
Statement st = new HeapStatement.HeapParamCaller(node, callIndex, p);
delegate.addNode(st);
params.add(st);
}
OrdinalSet<PointerKey> umod = unionHeapLocations(cg, node, call, mod);
for (PointerKey p : umod) {
Statement st = new HeapStatement.HeapReturnCaller(node, callIndex, p);
delegate.addNode(st);
rets.add(st);
}
}
}
/** @return the set of all locations read by any callee at a call site. */
private static OrdinalSet<PointerKey> unionHeapLocations(
CallGraph cg,
CGNode n,
SSAAbstractInvokeInstruction call,
Map<CGNode, OrdinalSet<PointerKey>> loc) {
BitVectorIntSet bv = new BitVectorIntSet();
for (CGNode t : cg.getPossibleTargets(n, call.getCallSite())) {
bv.addAll(loc.get(t).getBackingSet());
}
return new OrdinalSet<>(bv, loc.get(n).getMapping());
}
@Override
public String toString() {
populate();
return "PDG for " + node + ":\n" + super.toString();
}
public Statement[] getParamCalleeStatements() {
if (paramCalleeStatements == null) {
createCalleeParams();
}
Statement[] result = new Statement[paramCalleeStatements.length];
System.arraycopy(paramCalleeStatements, 0, result, 0, result.length);
return result;
}
public Statement[] getReturnStatements() {
populate();
Statement[] result = new Statement[returnStatements.length];
System.arraycopy(returnStatements, 0, result, 0, result.length);
return result;
}
public CGNode getCallGraphNode() {
return node;
}
@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass().equals(obj.getClass())) {
return node.equals(((PDG<?>) obj).node);
} else {
return false;
}
}
@Override
public int hashCode() {
return 103 * node.hashCode();
}
@Override
public int getPredNodeCount(Statement N) throws UnimplementedError {
populate();
Assertions.UNREACHABLE();
return delegate.getPredNodeCount(N);
}
@Override
public Iterator<Statement> getPredNodes(Statement N) {
populate();
if (!dOptions.isIgnoreHeap()) {
computeIncomingHeapDependencies(N);
}
return delegate.getPredNodes(N);
}
private void computeIncomingHeapDependencies(Statement N) {
switch (N.getKind()) {
case NORMAL:
NormalStatement st = (NormalStatement) N;
if (!(ignoreAllocHeapDefs && st.getInstruction() instanceof SSANewInstruction)) {
Collection<PointerKey> ref =
modRef.getRef(node, heapModel, pa, st.getInstruction(), exclusions);
for (PointerKey pk : ref) {
createHeapDataDependenceEdges(pk);
}
}
break;
case HEAP_PARAM_CALLEE:
case HEAP_PARAM_CALLER:
case HEAP_RET_CALLEE:
case HEAP_RET_CALLER:
HeapStatement h = (HeapStatement) N;
createHeapDataDependenceEdges(h.getLocation());
break;
default:
// do nothing
}
}
private void computeOutgoingHeapDependencies(Statement N) {
switch (N.getKind()) {
case NORMAL:
NormalStatement st = (NormalStatement) N;
if (!(ignoreAllocHeapDefs && st.getInstruction() instanceof SSANewInstruction)) {
Collection<PointerKey> mod =
modRef.getMod(node, heapModel, pa, st.getInstruction(), exclusions);
for (PointerKey pk : mod) {
createHeapDataDependenceEdges(pk);
}
}
break;
case HEAP_PARAM_CALLEE:
case HEAP_PARAM_CALLER:
case HEAP_RET_CALLEE:
case HEAP_RET_CALLER:
HeapStatement h = (HeapStatement) N;
createHeapDataDependenceEdges(h.getLocation());
break;
default:
// do nothing
}
}
@Override
public int getSuccNodeCount(Statement N) throws UnimplementedError {
populate();
Assertions.UNREACHABLE();
return delegate.getSuccNodeCount(N);
}
@Override
public Iterator<Statement> getSuccNodes(Statement N) {
populate();
if (!dOptions.isIgnoreHeap()) {
computeOutgoingHeapDependencies(N);
}
return delegate.getSuccNodes(N);
}
@Override
public boolean hasEdge(Statement src, Statement dst) throws UnimplementedError {
populate();
return delegate.hasEdge(src, dst);
}
@Override
public void removeNodeAndEdges(Statement N) throws UnsupportedOperationException {
Assertions.UNREACHABLE();
}
@Override
public void addNode(Statement n) {
Assertions.UNREACHABLE();
}
@Override
public boolean containsNode(Statement N) {
populate();
return delegate.containsNode(N);
}
@Override
public int getNumberOfNodes() {
populate();
return delegate.getNumberOfNodes();
}
@Override
public Iterator<Statement> iterator() {
populate();
return delegate.iterator();
}
@Override
public Stream<Statement> stream() {
populate();
return delegate.stream();
}
@Override
public void removeNode(Statement n) {
Assertions.UNREACHABLE();
}
@Override
public void addEdge(Statement src, Statement dst) {
Assertions.UNREACHABLE();
}
@Override
public void removeAllIncidentEdges(Statement node) throws UnsupportedOperationException {
Assertions.UNREACHABLE();
}
@Override
public void removeEdge(Statement src, Statement dst) throws UnsupportedOperationException {
Assertions.UNREACHABLE();
}
@Override
public void removeIncomingEdges(Statement node) throws UnsupportedOperationException {
Assertions.UNREACHABLE();
}
@Override
public void removeOutgoingEdges(Statement node) throws UnsupportedOperationException {
Assertions.UNREACHABLE();
}
@Override
public int getMaxNumber() {
populate();
return delegate.getMaxNumber();
}
@Override
public Statement getNode(int number) {
populate();
return delegate.getNode(number);
}
@Override
public int getNumber(Statement N) {
populate();
return delegate.getNumber(N);
}
@Override
public Iterator<Statement> iterateNodes(IntSet s) {
Assertions.UNREACHABLE();
return null;
}
@Override
public IntSet getPredNodeNumbers(Statement node) {
Assertions.UNREACHABLE();
return null;
}
@Override
public IntSet getSuccNodeNumbers(Statement node) {
Assertions.UNREACHABLE();
return null;
}
@Override
public IntSet getPredNodeNumbers(Statement node, Dependency label)
throws IllegalArgumentException {
populate();
return delegate.getPredNodeNumbers(node, label);
}
@Override
public IntSet getSuccNodeNumbers(Statement node, Dependency label)
throws IllegalArgumentException {
populate();
return delegate.getSuccNodeNumbers(node, label);
}
@Override
public Dependency getDefaultLabel() {
assert false;
return null;
}
@Override
public Iterator<Statement> getPredNodes(Statement N, Dependency label) {
populate();
return delegate.getPredNodes(N, label);
}
@Override
public Iterator<? extends Dependency> getPredLabels(Statement N) {
populate();
return delegate.getPredLabels(N);
}
@Override
public int getPredNodeCount(Statement N, Dependency label) {
populate();
return delegate.getPredNodeCount(N, label);
}
@Override
public Iterator<? extends Statement> getSuccNodes(Statement N, Dependency label) {
populate();
return delegate.getSuccNodes(N, label);
}
@Override
public Iterator<? extends Dependency> getSuccLabels(Statement N) {
populate();
return delegate.getSuccLabels(N);
}
@Override
public int getSuccNodeCount(Statement N, Dependency label) {
populate();
return delegate.getSuccNodeCount(N, label);
}
@Override
public void addEdge(Statement src, Statement dst, Dependency label) {
assert false;
}
@Override
public void removeEdge(Statement src, Statement dst, Dependency label)
throws UnsupportedOperationException {
assert false;
}
@Override
public boolean hasEdge(Statement src, Statement dst, Dependency label) {
populate();
return delegate.hasEdge(src, dst, label);
}
@Override
public Set<? extends Dependency> getEdgeLabels(Statement src, Statement dst) {
populate();
return delegate.getEdgeLabels(src, dst);
}
}
| 46,518
| 33.205147
| 100
|
java
|
WALA
|
WALA-master/core/src/main/java/com/ibm/wala/ipa/slicer/ParamCallee.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.slicer;
import com.ibm.wala.ipa.callgraph.CGNode;
/** A {@link Statement} representing a formal parameter */
public class ParamCallee extends Statement implements ValueNumberCarrier {
/** Value number of the parameter */
protected final int valueNumber;
public ParamCallee(CGNode node, int valueNumber) {
super(node);
this.valueNumber = valueNumber;
}
@Override
public Kind getKind() {
return Kind.PARAM_CALLEE;
}
@Override
public int getValueNumber() {
return valueNumber;
}
@Override
public String toString() {
return super.toString() + " v" + valueNumber;
}
@Override
public int hashCode() {
final int prime = 31;
int result = super.hashCode();
result = prime * result + valueNumber;
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (!super.equals(obj)) return false;
if (getClass() != obj.getClass()) return false;
final ParamCallee other = (ParamCallee) obj;
if (valueNumber != other.valueNumber) return false;
return true;
}
}
| 1,479
| 24.517241
| 74
|
java
|
WALA
|
WALA-master/core/src/main/java/com/ibm/wala/ipa/slicer/ParamCaller.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.slicer;
import com.ibm.wala.ipa.callgraph.CGNode;
import com.ibm.wala.ssa.SSAAbstractInvokeInstruction;
/** A {@link Statement} representing an actual parameter */
public class ParamCaller extends StatementWithInstructionIndex implements ValueNumberCarrier {
/** Value number of the actual parameter */
protected final int valueNumber;
public ParamCaller(CGNode node, int callIndex, int valueNumber) {
super(node, callIndex);
this.valueNumber = valueNumber;
}
@Override
public Kind getKind() {
return Kind.PARAM_CALLER;
}
@Override
public SSAAbstractInvokeInstruction getInstruction() {
return (SSAAbstractInvokeInstruction) super.getInstruction();
}
@Override
public String toString() {
return super.toString() + " v" + getValueNumber();
}
@Override
public int getValueNumber() {
return valueNumber;
}
@Override
public int hashCode() {
final int prime = 31;
int result = super.hashCode();
result = prime * result + valueNumber;
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (!super.equals(obj)) return false;
if (getClass() != obj.getClass()) return false;
final ParamCaller other = (ParamCaller) obj;
if (valueNumber != other.valueNumber) return false;
return true;
}
}
| 1,732
| 26.078125
| 94
|
java
|
WALA
|
WALA-master/core/src/main/java/com/ibm/wala/ipa/slicer/PhiStatement.java
|
/*
* Copyright (c) 2006 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.ipa.slicer;
import com.ibm.wala.ipa.callgraph.CGNode;
import com.ibm.wala.ssa.SSAPhiInstruction;
/** identifier of a phi instruction */
public class PhiStatement extends Statement {
private final SSAPhiInstruction phi;
public PhiStatement(CGNode node, SSAPhiInstruction phi) {
super(node);
this.phi = phi;
}
@Override
public Kind getKind() {
return Kind.PHI;
}
@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass().equals(obj.getClass())) {
PhiStatement other = (PhiStatement) obj;
return getNode().equals(other.getNode()) && phi.getDef() == other.phi.getDef();
} else {
return false;
}
}
@Override
public int hashCode() {
return 3691 * phi.getDef() + getNode().hashCode();
}
@Override
public String toString() {
return "PHI " + getNode() + ':' + phi;
}
public SSAPhiInstruction getPhi() {
return phi;
}
}
| 1,347
| 22.649123
| 85
|
java
|
WALA
|
WALA-master/core/src/main/java/com/ibm/wala/ipa/slicer/PiStatement.java
|
/*
* Copyright (c) 2006 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.ipa.slicer;
import com.ibm.wala.ipa.callgraph.CGNode;
import com.ibm.wala.ssa.SSAPiInstruction;
/** identifier of a Pi instruction */
public class PiStatement extends Statement {
private final SSAPiInstruction pi;
public PiStatement(CGNode node, SSAPiInstruction pi) {
super(node);
this.pi = pi;
}
@Override
public Kind getKind() {
return Kind.PI;
}
@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass().equals(obj.getClass())) {
PiStatement other = (PiStatement) obj;
return getNode().equals(other.getNode()) && pi.getDef() == other.getPi().getDef();
} else {
return false;
}
}
@Override
public int hashCode() {
return 3691 * pi.getDef() + getNode().hashCode();
}
@Override
public String toString() {
return getNode() + ":" + pi;
}
public SSAPiInstruction getPi() {
return pi;
}
}
| 1,323
| 22.22807
| 88
|
java
|
WALA
|
WALA-master/core/src/main/java/com/ibm/wala/ipa/slicer/ReachabilityFunctions.java
|
/*
* Copyright (c) 2006 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.ipa.slicer;
import com.ibm.wala.dataflow.IFDS.IFlowFunction;
import com.ibm.wala.dataflow.IFDS.IFlowFunctionMap;
import com.ibm.wala.dataflow.IFDS.IUnaryFlowFunction;
import com.ibm.wala.dataflow.IFDS.VectorGenFlowFunction;
import com.ibm.wala.util.intset.SparseIntSet;
/** Trivial flow functions to represent simple reachability. All functions simply return "0" */
public class ReachabilityFunctions<T> implements IFlowFunctionMap<T> {
public static final VectorGenFlowFunction FLOW_REACHES =
VectorGenFlowFunction.make(SparseIntSet.singleton(0));
public static final IUnaryFlowFunction KILL_FLOW =
new IUnaryFlowFunction() {
@Override
public SparseIntSet getTargets(int d1) {
// kill even the reachability predicate 0.
return new SparseIntSet();
}
@Override
public String toString() {
return "killFlow";
}
};
public static <T> ReachabilityFunctions<T> createReachabilityFunctions() {
return new ReachabilityFunctions<>();
}
private ReachabilityFunctions() {}
@Override
public IUnaryFlowFunction getCallNoneToReturnFlowFunction(T src, T dest) {
return FLOW_REACHES;
}
@Override
public IUnaryFlowFunction getCallToReturnFlowFunction(T src, T dest) {
// force flow into callee and back.
return KILL_FLOW;
}
@Override
public IUnaryFlowFunction getNormalFlowFunction(T src, T dest) {
return FLOW_REACHES;
}
@Override
public IFlowFunction getReturnFlowFunction(T call, T src, T dest) {
return FLOW_REACHES;
}
@SuppressWarnings("unused")
public IFlowFunction getReturnFlowFunction(T src, T dest) {
return FLOW_REACHES;
}
@Override
public IUnaryFlowFunction getCallFlowFunction(T src, T dest, T ret) {
return FLOW_REACHES;
}
}
| 2,197
| 27.921053
| 95
|
java
|
WALA
|
WALA-master/core/src/main/java/com/ibm/wala/ipa/slicer/SDG.java
|
/*
* Copyright (c) 2006 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.ipa.slicer;
import com.ibm.wala.classLoader.CallSiteReference;
import com.ibm.wala.ipa.callgraph.CGNode;
import com.ibm.wala.ipa.callgraph.CallGraph;
import com.ibm.wala.ipa.callgraph.propagation.InstanceKey;
import com.ibm.wala.ipa.callgraph.propagation.PointerAnalysis;
import com.ibm.wala.ipa.callgraph.propagation.PointerKey;
import com.ibm.wala.ipa.cha.IClassHierarchy;
import com.ibm.wala.ipa.modref.ModRef;
import com.ibm.wala.ipa.slicer.Slicer.ControlDependenceOptions;
import com.ibm.wala.ipa.slicer.Slicer.DataDependenceOptions;
import com.ibm.wala.ipa.slicer.Statement.Kind;
import com.ibm.wala.ssa.IR;
import com.ibm.wala.ssa.SSAAbstractInvokeInstruction;
import com.ibm.wala.types.MethodReference;
import com.ibm.wala.types.TypeReference;
import com.ibm.wala.util.collections.CompoundIterator;
import com.ibm.wala.util.collections.EmptyIterator;
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.Iterator2Iterable;
import com.ibm.wala.util.collections.IteratorUtil;
import com.ibm.wala.util.debug.Assertions;
import com.ibm.wala.util.graph.AbstractNumberedGraph;
import com.ibm.wala.util.graph.NumberedEdgeManager;
import com.ibm.wala.util.graph.NumberedNodeManager;
import com.ibm.wala.util.graph.impl.SlowNumberedNodeManager;
import com.ibm.wala.util.intset.IntIterator;
import com.ibm.wala.util.intset.IntSet;
import com.ibm.wala.util.intset.MutableSparseIntSet;
import com.ibm.wala.util.intset.OrdinalSet;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
/**
* System dependence graph.
*
* <p>An SDG comprises a set of PDGs, one for each method. We compute these lazily.
*
* <p>Prototype implementation. Not efficient.
*/
public class SDG<T extends InstanceKey> extends AbstractNumberedGraph<Statement> implements ISDG {
/** Turn this flag on if you don't want eagerConstruction() to be called. */
private static final boolean DEBUG_LAZY = false;
/** node manager for graph API */
private final Nodes nodeMgr = new Nodes();
/** edge manager for graph API */
private final Edges edgeMgr = new Edges();
/** governing call graph */
private final CallGraph cg;
/** governing pointer analysis */
private final PointerAnalysis<T> pa;
/** keeps track of PDG for each call graph node */
private final Map<CGNode, PDG<T>> pdgMap = HashMapFactory.make();
/** governs data dependence edges in the graph */
private final DataDependenceOptions dOptions;
/** governs control dependence edges in the graph */
private final ControlDependenceOptions cOptions;
/**
* the set of heap locations which may be written (transitively) by each node. These are logically
* return values in the SDG.
*/
private final Map<CGNode, OrdinalSet<PointerKey>> mod;
/**
* the set of heap locations which may be read (transitively) by each node. These are logically
* parameters in the SDG.
*/
private final Map<CGNode, OrdinalSet<PointerKey>> ref;
/** CGNodes for which we have added all statements */
private final Collection<CGNode> statementsAdded = HashSetFactory.make();
/** If non-null, represents the heap locations to exclude from data dependence */
private final HeapExclusions heapExclude;
private final ModRef<T> modRef;
/** Have we eagerly populated all nodes of this SDG? */
private boolean eagerComputed = false;
public SDG(
final CallGraph cg,
PointerAnalysis<T> pa,
DataDependenceOptions dOptions,
ControlDependenceOptions cOptions) {
this(cg, pa, new ModRef<>(), dOptions, cOptions, null);
}
public SDG(
final CallGraph cg,
PointerAnalysis<T> pa,
ModRef<T> modRef,
DataDependenceOptions dOptions,
ControlDependenceOptions cOptions) {
this(cg, pa, modRef, dOptions, cOptions, null);
}
public SDG(
CallGraph cg,
PointerAnalysis<T> pa,
ModRef<T> modRef,
DataDependenceOptions dOptions,
ControlDependenceOptions cOptions,
HeapExclusions heapExclude)
throws IllegalArgumentException {
super();
if (dOptions == null) {
throw new IllegalArgumentException("dOptions must not be null");
}
this.modRef = modRef;
this.cg = cg;
this.pa = pa;
this.mod = dOptions.isIgnoreHeap() ? null : modRef.computeMod(cg, pa, heapExclude);
this.ref = dOptions.isIgnoreHeap() ? null : modRef.computeRef(cg, pa, heapExclude);
this.dOptions = dOptions;
this.cOptions = cOptions;
this.heapExclude = heapExclude;
}
/**
* Use this with care. This forces eager construction of the SDG, and SDGs can be big.
*
* @see com.ibm.wala.util.graph.AbstractGraph#toString()
*/
@Override
public String toString() {
eagerConstruction();
return super.toString();
}
/** force eager construction of the entire SDG */
private void eagerConstruction() {
if (DEBUG_LAZY) {
Assertions.UNREACHABLE();
}
// Assertions.UNREACHABLE();
if (!eagerComputed) {
eagerComputed = true;
computeAllPDGs();
for (PDG<?> pdg : pdgMap.values()) {
addPDGStatementNodes(pdg.getCallGraphNode());
}
}
}
private void addPDGStatementNodes(CGNode node) {
if (!statementsAdded.contains(node)) {
statementsAdded.add(node);
PDG<?> pdg = getPDG(node);
for (Statement statement : pdg) {
addNode(statement);
}
}
}
/** force computation of all PDGs in the SDG */
private void computeAllPDGs() {
for (CGNode n : cg) {
getPDG(n);
}
}
/**
* iterate over the nodes <b>without</b> constructing any new ones. Use with extreme care. May
* break graph traversals that lazily add more nodes.
*/
@Override
public Iterator<? extends Statement> iterateLazyNodes() {
return nodeMgr.iterateLazyNodes();
}
private class Nodes extends SlowNumberedNodeManager<Statement> {
private static final long serialVersionUID = -1450214776332091211L;
@Override
public boolean containsNode(Statement N) {
if (super.containsNode(N)) {
// first try it without eager construction.
return true;
}
// this may be bad. Are you sure you want to call this?
eagerConstruction();
return super.containsNode(N);
}
@Override
public int getMaxNumber() {
// this may be bad. Are you sure you want to call this?
eagerConstruction();
return super.getMaxNumber();
}
@Override
public Statement getNode(int number) {
Statement s = getNodeLazy(number);
if (s != null) {
// found it. don't do eager construction.
return s;
} else {
// this may be bad. Are you sure you want to do this?
eagerConstruction();
return super.getNode(number);
}
}
@Override
public int getNumber(Statement s) {
CGNode n = s.getNode();
addPDGStatementNodes(n);
return super.getNumber(s);
}
@Override
public Iterator<Statement> iterateNodes(IntSet s) {
Assertions.UNREACHABLE();
return super.iterateNodes(s);
}
@Override
public Iterator<Statement> iterator() {
eagerConstruction();
return super.iterator();
}
/**
* iterate over the nodes <b>without</b> constructing any new ones. Use with extreme care. May
* break graph traversals that lazily add more nodes.
*/
Iterator<? extends Statement> iterateLazyNodes() {
return super.iterator();
}
/** get the node with the given number if it already exists. Use with extreme care. */
public Statement getNodeLazy(int number) {
return super.getNode(number);
}
@Override
public int getNumberOfNodes() {
eagerConstruction();
return super.getNumberOfNodes();
}
}
private class Edges implements NumberedEdgeManager<Statement> {
@Override
public void addEdge(Statement src, Statement dst) {
Assertions.UNREACHABLE();
}
@Override
public int getPredNodeCount(Statement N) {
return IteratorUtil.count(getPredNodes(N));
}
@Override
public Iterator<Statement> getPredNodes(Statement N) {
if (dOptions.isIgnoreExceptions()) {
assert !N.getKind().equals(Kind.EXC_RET_CALLEE);
assert !N.getKind().equals(Kind.EXC_RET_CALLER);
}
addPDGStatementNodes(N.getNode());
switch (N.getKind()) {
case NORMAL:
case PHI:
case PI:
case EXC_RET_CALLEE:
case NORMAL_RET_CALLEE:
case PARAM_CALLER:
case HEAP_PARAM_CALLER:
case HEAP_RET_CALLEE:
case CATCH:
case METHOD_EXIT:
return getPDG(N.getNode()).getPredNodes(N);
case EXC_RET_CALLER:
{
ExceptionalReturnCaller nrc = (ExceptionalReturnCaller) N;
SSAAbstractInvokeInstruction call = nrc.getInstruction();
Collection<Statement> result =
Iterator2Collection.toSet(getPDG(N.getNode()).getPredNodes(N));
if (!dOptions.equals(DataDependenceOptions.NONE)) {
// data dependence predecessors
for (CGNode t : cg.getPossibleTargets(N.getNode(), call.getCallSite())) {
Statement s = new ExceptionalReturnCallee(t);
addNode(s);
result.add(s);
}
}
return result.iterator();
}
case NORMAL_RET_CALLER:
{
NormalReturnCaller nrc = (NormalReturnCaller) N;
SSAAbstractInvokeInstruction call = nrc.getInstruction();
Collection<Statement> result =
Iterator2Collection.toSet(getPDG(N.getNode()).getPredNodes(N));
if (!dOptions.equals(DataDependenceOptions.NONE)) {
// data dependence predecessors
for (CGNode t : cg.getPossibleTargets(N.getNode(), call.getCallSite())) {
Statement s = new NormalReturnCallee(t);
addNode(s);
result.add(s);
}
}
return result.iterator();
}
case HEAP_RET_CALLER:
{
HeapStatement.HeapReturnCaller r = (HeapStatement.HeapReturnCaller) N;
SSAAbstractInvokeInstruction call = r.getCall();
Collection<Statement> result =
Iterator2Collection.toSet(getPDG(N.getNode()).getPredNodes(N));
if (!dOptions.equals(DataDependenceOptions.NONE)) {
// data dependence predecessors
for (CGNode t : cg.getPossibleTargets(N.getNode(), call.getCallSite())) {
if (mod.get(t).contains(r.getLocation())) {
Statement s = new HeapStatement.HeapReturnCallee(t, r.getLocation());
addNode(s);
result.add(s);
}
}
}
return result.iterator();
}
case PARAM_CALLEE:
{
ParamCallee pac = (ParamCallee) N;
int parameterIndex = pac.getValueNumber() - 1;
Collection<Statement> result = HashSetFactory.make(5);
if (!dOptions.equals(DataDependenceOptions.NONE)) {
if (dOptions.isTerminateAtCast()
&& !pac.getNode().getMethod().isStatic()
&& pac.getValueNumber() == 1) {
// a virtual dispatch is just like a cast. No flow.
return EmptyIterator.instance();
}
if (dOptions.isTerminateAtCast() && isUninformativeForReflection(pac.getNode())) {
// don't track flow for reflection
return EmptyIterator.instance();
}
// data dependence predecessors
for (CGNode caller : Iterator2Iterable.make(cg.getPredNodes(N.getNode()))) {
for (CallSiteReference site :
Iterator2Iterable.make(cg.getPossibleSites(caller, N.getNode()))) {
IR ir = caller.getIR();
IntSet indices = ir.getCallInstructionIndices(site);
for (IntIterator ii = indices.intIterator(); ii.hasNext(); ) {
int i = ii.next();
SSAAbstractInvokeInstruction call =
(SSAAbstractInvokeInstruction) ir.getInstructions()[i];
if (call.getNumberOfUses() > parameterIndex) {
int p = call.getUse(parameterIndex);
Statement s = new ParamCaller(caller, i, p);
addNode(s);
result.add(s);
}
}
}
}
}
// if (!cOptions.equals(ControlDependenceOptions.NONE)) {
// Statement s = new MethodEntryStatement(N.getNode());
// addNode(s);
// result.add(s);
// }
return result.iterator();
}
case HEAP_PARAM_CALLEE:
{
HeapStatement.HeapParamCallee hpc = (HeapStatement.HeapParamCallee) N;
Collection<Statement> result = HashSetFactory.make(5);
if (!dOptions.equals(DataDependenceOptions.NONE)) {
// data dependence predecessors
for (CGNode caller : Iterator2Iterable.make(cg.getPredNodes(N.getNode()))) {
for (CallSiteReference site :
Iterator2Iterable.make(cg.getPossibleSites(caller, N.getNode()))) {
IR ir = caller.getIR();
IntSet indices = ir.getCallInstructionIndices(site);
for (IntIterator ii = indices.intIterator(); ii.hasNext(); ) {
int i = ii.next();
Statement s = new HeapStatement.HeapParamCaller(caller, i, hpc.getLocation());
addNode(s);
result.add(s);
}
}
}
}
// if (!cOptions.equals(ControlDependenceOptions.NONE)) {
// Statement s = new MethodEntryStatement(N.getNode());
// addNode(s);
// result.add(s);
// }
return result.iterator();
}
case METHOD_ENTRY:
Collection<Statement> result = HashSetFactory.make(5);
if (!cOptions.isIgnoreInterproc()) {
for (CGNode caller : Iterator2Iterable.make(cg.getPredNodes(N.getNode()))) {
for (CallSiteReference site :
Iterator2Iterable.make(cg.getPossibleSites(caller, N.getNode()))) {
IR ir = caller.getIR();
IntSet indices = ir.getCallInstructionIndices(site);
for (IntIterator ii = indices.intIterator(); ii.hasNext(); ) {
int i = ii.next();
Statement s = new NormalStatement(caller, i);
addNode(s);
result.add(s);
}
}
}
}
return result.iterator();
default:
Assertions.UNREACHABLE(N.getKind().toString());
return null;
}
}
@Override
public int getSuccNodeCount(Statement N) {
return IteratorUtil.count(getSuccNodes(N));
}
@Override
public Iterator<Statement> getSuccNodes(Statement N) {
if (dOptions.isTerminateAtCast() && isUninformativeForReflection(N.getNode())) {
return EmptyIterator.instance();
}
addPDGStatementNodes(N.getNode());
switch (N.getKind()) {
case NORMAL:
if (cOptions.isIgnoreInterproc()) {
return getPDG(N.getNode()).getSuccNodes(N);
} else {
NormalStatement ns = (NormalStatement) N;
if (ns.getInstruction() instanceof SSAAbstractInvokeInstruction) {
HashSet<Statement> result = HashSetFactory.make();
SSAAbstractInvokeInstruction call =
(SSAAbstractInvokeInstruction) ns.getInstruction();
for (CGNode t : cg.getPossibleTargets(N.getNode(), call.getCallSite())) {
Statement s = new MethodEntryStatement(t);
addNode(s);
result.add(s);
}
return new CompoundIterator<>(result.iterator(), getPDG(N.getNode()).getSuccNodes(N));
} else {
return getPDG(N.getNode()).getSuccNodes(N);
}
}
case PHI:
case PI:
case CATCH:
case EXC_RET_CALLER:
case NORMAL_RET_CALLER:
case PARAM_CALLEE:
case HEAP_PARAM_CALLEE:
case HEAP_RET_CALLER:
case METHOD_ENTRY:
case METHOD_EXIT:
return getPDG(N.getNode()).getSuccNodes(N);
case EXC_RET_CALLEE:
{
Collection<Statement> result = HashSetFactory.make(5);
if (!dOptions.equals(DataDependenceOptions.NONE)) {
// data dependence predecessors
for (CGNode caller : Iterator2Iterable.make(cg.getPredNodes(N.getNode()))) {
for (CallSiteReference site :
Iterator2Iterable.make(cg.getPossibleSites(caller, N.getNode()))) {
IR ir = caller.getIR();
IntSet indices = ir.getCallInstructionIndices(site);
for (IntIterator ii = indices.intIterator(); ii.hasNext(); ) {
int i = ii.next();
Statement s = new ExceptionalReturnCaller(caller, i);
addNode(s);
result.add(s);
}
}
}
}
return result.iterator();
}
case NORMAL_RET_CALLEE:
{
Collection<Statement> result = HashSetFactory.make(5);
if (!dOptions.equals(DataDependenceOptions.NONE)) {
// data dependence predecessors
for (CGNode caller : Iterator2Iterable.make(cg.getPredNodes(N.getNode()))) {
for (CallSiteReference site :
Iterator2Iterable.make(cg.getPossibleSites(caller, N.getNode()))) {
IR ir = caller.getIR();
IntSet indices = ir.getCallInstructionIndices(site);
for (IntIterator ii = indices.intIterator(); ii.hasNext(); ) {
int i = ii.next();
Statement s = new NormalReturnCaller(caller, i);
addNode(s);
result.add(s);
}
}
}
}
return result.iterator();
}
case HEAP_RET_CALLEE:
{
HeapStatement.HeapReturnCallee r = (HeapStatement.HeapReturnCallee) N;
Collection<Statement> result = HashSetFactory.make(5);
if (!dOptions.equals(DataDependenceOptions.NONE)) {
// data dependence predecessors
for (CGNode caller : Iterator2Iterable.make(cg.getPredNodes(N.getNode()))) {
for (CallSiteReference site :
Iterator2Iterable.make(cg.getPossibleSites(caller, N.getNode()))) {
IR ir = caller.getIR();
IntSet indices = ir.getCallInstructionIndices(site);
for (IntIterator ii = indices.intIterator(); ii.hasNext(); ) {
int i = ii.next();
Statement s = new HeapStatement.HeapReturnCaller(caller, i, r.getLocation());
addNode(s);
result.add(s);
}
}
}
}
return result.iterator();
}
case PARAM_CALLER:
{
ParamCaller pac = (ParamCaller) N;
SSAAbstractInvokeInstruction call = pac.getInstruction();
int numParamsPassed = call.getNumberOfUses();
Collection<Statement> result = HashSetFactory.make(5);
if (!dOptions.equals(DataDependenceOptions.NONE)) {
// data dependence successors
for (CGNode t : cg.getPossibleTargets(N.getNode(), call.getCallSite())) {
// in some languages (*cough* JavaScript *cough*) you can pass
// fewer parameters than the number of formals. So, only loop
// over the parameters actually being passed here
for (int i = 0;
i < t.getMethod().getNumberOfParameters() && i < numParamsPassed;
i++) {
if (dOptions.isTerminateAtCast()
&& call.isDispatch()
&& pac.getValueNumber() == call.getReceiver()) {
// a virtual dispatch is just like a cast.
continue;
}
if (dOptions.isTerminateAtCast() && isUninformativeForReflection(t)) {
// don't track reflection into reflective invokes
continue;
}
if (call.getUse(i) == pac.getValueNumber()) {
Statement s = new ParamCallee(t, i + 1);
addNode(s);
result.add(s);
}
}
}
}
return result.iterator();
}
case HEAP_PARAM_CALLER:
HeapStatement.HeapParamCaller pc = (HeapStatement.HeapParamCaller) N;
SSAAbstractInvokeInstruction call = pc.getCall();
Collection<Statement> result = HashSetFactory.make(5);
if (!dOptions.equals(DataDependenceOptions.NONE)) {
// data dependence successors
for (CGNode t : cg.getPossibleTargets(N.getNode(), call.getCallSite())) {
if (ref.get(t).contains(pc.getLocation())) {
Statement s = new HeapStatement.HeapParamCallee(t, pc.getLocation());
addNode(s);
result.add(s);
}
}
}
return result.iterator();
default:
Assertions.UNREACHABLE(N.getKind().toString());
return null;
}
}
/** Should we cut off flow into node t when processing reflection? */
private boolean isUninformativeForReflection(CGNode t) {
if (t.getMethod()
.getDeclaringClass()
.getReference()
.equals(TypeReference.JavaLangReflectMethod)) {
return true;
}
if (t.getMethod()
.getDeclaringClass()
.getReference()
.equals(TypeReference.JavaLangReflectConstructor)) {
return true;
}
if (t.getMethod().getSelector().equals(MethodReference.equalsSelector)) {
return true;
}
return false;
}
@Override
public boolean hasEdge(Statement src, Statement dst) {
return !getEdgeLabels(src, dst).isEmpty();
}
public Set<? extends Dependency> getEdgeLabels(Statement src, Statement dst) {
addPDGStatementNodes(src.getNode());
addPDGStatementNodes(dst.getNode());
switch (src.getKind()) {
case NORMAL:
if (cOptions.isIgnoreInterproc()) {
return getPDG(src.getNode()).getEdgeLabels(src, dst);
} else {
NormalStatement ns = (NormalStatement) src;
if (dst instanceof MethodEntryStatement) {
if (ns.getInstruction() instanceof SSAAbstractInvokeInstruction) {
SSAAbstractInvokeInstruction call =
(SSAAbstractInvokeInstruction) ns.getInstruction();
if (cg.getPossibleTargets(src.getNode(), call.getCallSite())
.contains(dst.getNode())) {
return Collections.singleton(Dependency.CONTROL_DEP);
} else {
return Collections.emptySet();
}
} else {
return Collections.emptySet();
}
} else {
return getPDG(src.getNode()).getEdgeLabels(src, dst);
}
}
case CATCH:
assert src.getNode().equals(dst.getNode());
return getPDG(src.getNode()).getEdgeLabels(src, dst);
case PHI:
case PI:
case EXC_RET_CALLER:
case NORMAL_RET_CALLER:
case PARAM_CALLEE:
case HEAP_PARAM_CALLEE:
case HEAP_RET_CALLER:
case METHOD_ENTRY:
case METHOD_EXIT:
return getPDG(src.getNode()).getEdgeLabels(src, dst);
case EXC_RET_CALLEE:
{
if (dOptions.equals(DataDependenceOptions.NONE)) {
return Collections.emptySet();
}
if (dst.getKind().equals(Kind.EXC_RET_CALLER)) {
ExceptionalReturnCaller r = (ExceptionalReturnCaller) dst;
if (cg.getPossibleTargets(r.getNode(), r.getInstruction().getCallSite())
.contains(src.getNode())) {
return Collections.singleton(Dependency.DATA_DEP);
} else {
return Collections.emptySet();
}
} else {
return Collections.emptySet();
}
}
case NORMAL_RET_CALLEE:
{
if (dOptions.equals(DataDependenceOptions.NONE)) {
return Collections.emptySet();
}
if (dst.getKind().equals(Kind.NORMAL_RET_CALLER)) {
NormalReturnCaller r = (NormalReturnCaller) dst;
if (cg.getPossibleTargets(r.getNode(), r.getInstruction().getCallSite())
.contains(src.getNode())) {
return Collections.singleton(Dependency.DATA_DEP);
} else {
return Collections.emptySet();
}
} else {
return Collections.emptySet();
}
}
case HEAP_RET_CALLEE:
{
if (dOptions.equals(DataDependenceOptions.NONE)) {
return Collections.emptySet();
}
if (dst.getKind().equals(Kind.HEAP_RET_CALLER)) {
HeapStatement.HeapReturnCaller r = (HeapStatement.HeapReturnCaller) dst;
HeapStatement h = (HeapStatement) src;
if (h.getLocation().equals(r.getLocation())
&& cg.getPossibleTargets(r.getNode(), r.getCall().getCallSite())
.contains(src.getNode())) {
return Collections.singleton(Dependency.HEAP_DATA_DEP);
} else {
return Collections.emptySet();
}
} else {
return Collections.emptySet();
}
}
case PARAM_CALLER:
{
if (dOptions.equals(DataDependenceOptions.NONE)) {
return Collections.emptySet();
}
if (dst.getKind().equals(Kind.PARAM_CALLEE)) {
ParamCallee callee = (ParamCallee) dst;
ParamCaller caller = (ParamCaller) src;
SSAAbstractInvokeInstruction call = caller.getInstruction();
final CGNode calleeNode = callee.getNode();
if (!cg.getPossibleTargets(caller.getNode(), call.getCallSite())
.contains(calleeNode)) {
return Collections.emptySet();
}
if (dOptions.isTerminateAtCast()
&& call.isDispatch()
&& caller.getValueNumber() == call.getReceiver()) {
// a virtual dispatch is just like a cast.
return Collections.emptySet();
}
if (dOptions.isTerminateAtCast() && isUninformativeForReflection(calleeNode)) {
// don't track reflection into reflective invokes
return Collections.emptySet();
}
for (int i = 0; i < call.getNumberOfUses(); i++) {
if (call.getUse(i) == caller.getValueNumber()) {
if (callee.getValueNumber() == i + 1) {
return Collections.singleton(Dependency.DATA_DEP);
}
}
}
return Collections.emptySet();
} else {
return Collections.emptySet();
}
}
case HEAP_PARAM_CALLER:
if (dOptions.equals(DataDependenceOptions.NONE)) {
return Collections.emptySet();
}
if (dst.getKind().equals(Kind.HEAP_PARAM_CALLEE)) {
HeapStatement.HeapParamCallee callee = (HeapStatement.HeapParamCallee) dst;
HeapStatement.HeapParamCaller caller = (HeapStatement.HeapParamCaller) src;
if (caller.getLocation().equals(callee.getLocation())
&& cg.getPossibleTargets(caller.getNode(), caller.getCall().getCallSite())
.contains(callee.getNode())) {
return Collections.singleton(Dependency.HEAP_DATA_DEP);
} else {
return Collections.emptySet();
}
} else {
return Collections.emptySet();
}
default:
Assertions.UNREACHABLE(src.getKind());
return Collections.emptySet();
}
}
@Override
public void removeAllIncidentEdges(Statement node) {
Assertions.UNREACHABLE();
}
@Override
public void removeEdge(Statement src, Statement dst) {
Assertions.UNREACHABLE();
}
@Override
public void removeIncomingEdges(Statement node) {
Assertions.UNREACHABLE();
}
@Override
public void removeOutgoingEdges(Statement node) {
Assertions.UNREACHABLE();
}
@Override
public IntSet getPredNodeNumbers(Statement node) {
// TODO: optimize me.
MutableSparseIntSet result = MutableSparseIntSet.makeEmpty();
for (Statement s : Iterator2Iterable.make(getPredNodes(node))) {
result.add(getNumber(s));
}
return result;
}
@Override
public IntSet getSuccNodeNumbers(Statement node) {
// TODO: optimize me.
MutableSparseIntSet result = MutableSparseIntSet.makeEmpty();
for (Statement s : Iterator2Iterable.make(getSuccNodes(node))) {
result.add(getNumber(s));
}
return result;
}
}
@Override
protected NumberedEdgeManager<Statement> getEdgeManager() {
return edgeMgr;
}
@Override
public NumberedNodeManager<Statement> getNodeManager() {
return nodeMgr;
}
@Override
public PDG<T> getPDG(CGNode node) {
PDG<T> result = pdgMap.get(node);
if (result == null) {
result = new PDG<>(node, pa, mod, ref, dOptions, cOptions, heapExclude, cg, modRef);
pdgMap.put(node, result);
// Let's not eagerly add nodes, shall we?
// for (Iterator<? extends Statement> it = result.iterator(); it.hasNext();) {
// nodeMgr.addNode(it.next());
// }
}
return result;
}
@Override
public ControlDependenceOptions getCOptions() {
return cOptions;
}
public DataDependenceOptions getDOptions() {
return dOptions;
}
public CallGraph getCallGraph() {
return cg;
}
@Override
public IClassHierarchy getClassHierarchy() {
return cg.getClassHierarchy();
}
public PointerAnalysis<T> getPointerAnalysis() {
return pa;
}
public Set<? extends Dependency> getEdgeLabels(Statement src, Statement dst) {
return edgeMgr.getEdgeLabels(src, dst);
}
}
| 31,922
| 35.317406
| 100
|
java
|
WALA
|
WALA-master/core/src/main/java/com/ibm/wala/ipa/slicer/SDGSupergraph.java
|
/*
* Copyright (c) 2006 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.ipa.slicer;
import com.ibm.wala.dataflow.IFDS.ISupergraph;
import com.ibm.wala.ipa.callgraph.CGNode;
import com.ibm.wala.ipa.callgraph.propagation.InstanceKey;
import com.ibm.wala.ssa.SSAAbstractInvokeInstruction;
import com.ibm.wala.util.collections.EmptyIterator;
import com.ibm.wala.util.collections.FilterIterator;
import com.ibm.wala.util.debug.Assertions;
import com.ibm.wala.util.graph.Graph;
import com.ibm.wala.util.intset.IntSet;
import java.util.Iterator;
import java.util.stream.Stream;
/** A wrapper around an SDG to make it look like a supergraph for tabulation. */
class SDGSupergraph implements ISupergraph<Statement, PDG<? extends InstanceKey>> {
private final ISDG sdg;
/** Do a backward slice? */
private final boolean backward;
public SDGSupergraph(ISDG sdg, boolean backward) {
this.sdg = sdg;
this.backward = backward;
}
@Override
public Graph<PDG<? extends InstanceKey>> getProcedureGraph() {
Assertions.UNREACHABLE();
return null;
}
public Object[] getEntry() {
Assertions.UNREACHABLE();
return null;
}
@Override
public byte classifyEdge(Statement src, Statement dest) {
Assertions.UNREACHABLE();
return 0;
}
@Override
public Iterator<? extends Statement> getCallSites(
Statement r, PDG<? extends InstanceKey> callee) {
switch (r.getKind()) {
case EXC_RET_CALLER:
{
ExceptionalReturnCaller n = (ExceptionalReturnCaller) r;
SSAAbstractInvokeInstruction call = n.getInstruction();
PDG<?> pdg = getProcOf(r);
return pdg.getCallStatements(call).iterator();
}
case NORMAL_RET_CALLER:
{
NormalReturnCaller n = (NormalReturnCaller) r;
SSAAbstractInvokeInstruction call = n.getInstruction();
PDG<?> pdg = getProcOf(r);
return pdg.getCallStatements(call).iterator();
}
case HEAP_RET_CALLER:
{
HeapStatement.HeapReturnCaller n = (HeapStatement.HeapReturnCaller) r;
SSAAbstractInvokeInstruction call = n.getCall();
PDG<?> pdg = getProcOf(r);
return pdg.getCallStatements(call).iterator();
}
default:
Assertions.UNREACHABLE(r.getKind().toString());
return null;
}
}
@Override
public Iterator<? extends Statement> getCalledNodes(Statement call) {
switch (call.getKind()) {
case NORMAL:
return new FilterIterator<>(getSuccNodes(call), this::isEntry);
case PARAM_CALLER:
case HEAP_PARAM_CALLER:
return getSuccNodes(call);
default:
Assertions.UNREACHABLE(call.getKind().toString());
return null;
}
}
@Override
public Statement[] getEntriesForProcedure(PDG<? extends InstanceKey> procedure) {
Statement[] normal = procedure.getParamCalleeStatements();
Statement[] result = new Statement[normal.length + 1];
result[0] = new MethodEntryStatement(procedure.getCallGraphNode());
System.arraycopy(normal, 0, result, 1, normal.length);
return result;
}
@Override
public Statement[] getExitsForProcedure(PDG<? extends InstanceKey> procedure) {
Statement[] normal = procedure.getReturnStatements();
Statement[] result = new Statement[normal.length + 1];
result[0] = new MethodExitStatement(procedure.getCallGraphNode());
System.arraycopy(normal, 0, result, 1, normal.length);
return result;
}
@Override
public Statement getLocalBlock(PDG<? extends InstanceKey> procedure, int i) {
return procedure.getNode(i);
}
@Override
public int getLocalBlockNumber(Statement n) {
PDG<?> pdg = getProcOf(n);
return pdg.getNumber(n);
}
@Override
public Iterator<Statement> getNormalSuccessors(Statement call) {
if (!backward) {
return EmptyIterator.instance();
} else {
Assertions.UNREACHABLE();
return null;
}
}
@Override
public int getNumberOfBlocks(PDG<? extends InstanceKey> procedure) {
Assertions.UNREACHABLE();
return 0;
}
@Override
public PDG<? extends InstanceKey> getProcOf(Statement n) {
CGNode node = n.getNode();
PDG<? extends InstanceKey> result = sdg.getPDG(node);
if (result == null) {
Assertions.UNREACHABLE("panic: " + n + ' ' + node);
}
return result;
}
@Override
public Iterator<? extends Statement> getReturnSites(
Statement call, PDG<? extends InstanceKey> callee) {
switch (call.getKind()) {
case PARAM_CALLER:
{
ParamCaller n = (ParamCaller) call;
SSAAbstractInvokeInstruction st = n.getInstruction();
PDG<?> pdg = getProcOf(call);
return pdg.getCallerReturnStatements(st).iterator();
}
case HEAP_PARAM_CALLER:
{
HeapStatement.HeapParamCaller n = (HeapStatement.HeapParamCaller) call;
SSAAbstractInvokeInstruction st = n.getCall();
PDG<?> pdg = getProcOf(call);
return pdg.getCallerReturnStatements(st).iterator();
}
case NORMAL:
{
NormalStatement n = (NormalStatement) call;
SSAAbstractInvokeInstruction st = (SSAAbstractInvokeInstruction) n.getInstruction();
PDG<?> pdg = getProcOf(call);
return pdg.getCallerReturnStatements(st).iterator();
}
default:
Assertions.UNREACHABLE(call.getKind().toString());
return null;
}
}
@Override
public boolean isCall(Statement n) {
switch (n.getKind()) {
case EXC_RET_CALLEE:
case EXC_RET_CALLER:
case HEAP_PARAM_CALLEE:
case NORMAL_RET_CALLEE:
case NORMAL_RET_CALLER:
case PARAM_CALLEE:
case PHI:
case HEAP_RET_CALLEE:
case HEAP_RET_CALLER:
case METHOD_ENTRY:
case METHOD_EXIT:
case CATCH:
case PI:
return false;
case HEAP_PARAM_CALLER:
case PARAM_CALLER:
return true;
case NORMAL:
if (sdg.getCOptions().isIgnoreInterproc()) {
return false;
} else {
NormalStatement s = (NormalStatement) n;
return s.getInstruction() instanceof SSAAbstractInvokeInstruction;
}
default:
Assertions.UNREACHABLE(n.getKind() + " " + n);
return false;
}
}
@Override
public boolean isEntry(Statement n) {
switch (n.getKind()) {
case PARAM_CALLEE:
case HEAP_PARAM_CALLEE:
case METHOD_ENTRY:
return true;
case PHI:
case PI:
case NORMAL_RET_CALLER:
case PARAM_CALLER:
case HEAP_RET_CALLER:
case NORMAL:
case EXC_RET_CALLEE:
case EXC_RET_CALLER:
case HEAP_PARAM_CALLER:
case HEAP_RET_CALLEE:
case NORMAL_RET_CALLEE:
case CATCH:
return false;
default:
Assertions.UNREACHABLE(n.toString());
return false;
}
}
@Override
public boolean isExit(Statement n) {
switch (n.getKind()) {
case PARAM_CALLEE:
case HEAP_PARAM_CALLEE:
case HEAP_PARAM_CALLER:
case PHI:
case PI:
case NORMAL_RET_CALLER:
case PARAM_CALLER:
case HEAP_RET_CALLER:
case NORMAL:
case EXC_RET_CALLER:
case METHOD_ENTRY:
case CATCH:
return false;
case HEAP_RET_CALLEE:
case EXC_RET_CALLEE:
case NORMAL_RET_CALLEE:
case METHOD_EXIT:
return true;
default:
Assertions.UNREACHABLE(n.toString());
return false;
}
}
@Override
public boolean isReturn(Statement n) {
switch (n.getKind()) {
case EXC_RET_CALLER:
case NORMAL_RET_CALLER:
case HEAP_RET_CALLER:
return true;
case EXC_RET_CALLEE:
case HEAP_PARAM_CALLEE:
case HEAP_PARAM_CALLER:
case HEAP_RET_CALLEE:
case NORMAL:
case NORMAL_RET_CALLEE:
case PARAM_CALLEE:
case PARAM_CALLER:
case PHI:
case PI:
case METHOD_ENTRY:
case CATCH:
return false;
default:
Assertions.UNREACHABLE(n.getKind().toString());
return false;
}
}
@Override
public void removeNodeAndEdges(Statement N) {
Assertions.UNREACHABLE();
}
@Override
public void addNode(Statement n) {
Assertions.UNREACHABLE();
}
@Override
public boolean containsNode(Statement N) {
return sdg.containsNode(N);
}
@Override
public int getNumberOfNodes() {
Assertions.UNREACHABLE();
return 0;
}
@Override
public Iterator<Statement> iterator() {
return sdg.iterator();
}
@Override
public Stream<Statement> stream() {
return sdg.stream();
}
@Override
public void removeNode(Statement n) {
Assertions.UNREACHABLE();
}
@Override
public void addEdge(Statement src, Statement dst) {
Assertions.UNREACHABLE();
}
@Override
public int getPredNodeCount(Statement N) {
Assertions.UNREACHABLE();
return 0;
}
@Override
public Iterator<Statement> getPredNodes(Statement N) {
return sdg.getPredNodes(N);
}
@Override
public int getSuccNodeCount(Statement N) {
Assertions.UNREACHABLE();
return 0;
}
@Override
public Iterator<Statement> getSuccNodes(Statement N) {
return sdg.getSuccNodes(N);
}
@Override
public boolean hasEdge(Statement src, Statement dst) {
return sdg.hasEdge(src, dst);
}
@Override
public void removeAllIncidentEdges(Statement node) {
Assertions.UNREACHABLE();
}
@Override
public void removeEdge(Statement src, Statement dst) {
Assertions.UNREACHABLE();
}
@Override
public void removeIncomingEdges(Statement node) {
Assertions.UNREACHABLE();
}
@Override
public void removeOutgoingEdges(Statement node) {
Assertions.UNREACHABLE();
}
@Override
public int getMaxNumber() {
return sdg.getMaxNumber();
}
@Override
public Statement getNode(int number) {
return sdg.getNode(number);
}
@Override
public int getNumber(Statement N) {
return sdg.getNumber(N);
}
@Override
public Iterator<Statement> iterateNodes(IntSet s) {
Assertions.UNREACHABLE();
return null;
}
@Override
public IntSet getPredNodeNumbers(Statement node) {
return sdg.getPredNodeNumbers(node);
}
/** @see com.ibm.wala.util.graph.NumberedEdgeManager#getSuccNodeNumbers(java.lang.Object) */
@Override
public IntSet getSuccNodeNumbers(Statement node) {
return sdg.getSuccNodeNumbers(node);
}
}
| 10,782
| 24.796651
| 94
|
java
|
WALA
|
WALA-master/core/src/main/java/com/ibm/wala/ipa/slicer/SliceFunctions.java
|
/*
* Copyright (c) 2006 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.ipa.slicer;
import com.ibm.wala.dataflow.IFDS.IFlowFunction;
import com.ibm.wala.dataflow.IFDS.IPartiallyBalancedFlowFunctions;
import com.ibm.wala.dataflow.IFDS.IUnaryFlowFunction;
import com.ibm.wala.dataflow.IFDS.IdentityFlowFunction;
import com.ibm.wala.util.debug.Assertions;
/** flow functions for flow-sensitive context-sensitive slicer */
public class SliceFunctions implements IPartiallyBalancedFlowFunctions<Statement> {
@Override
public IUnaryFlowFunction getCallFlowFunction(Statement src, Statement dest, Statement ret) {
return ReachabilityFunctions.createReachabilityFunctions().getCallFlowFunction(src, dest, ret);
}
@Override
public IUnaryFlowFunction getCallNoneToReturnFlowFunction(Statement src, Statement dest) {
if (src == null) {
throw new IllegalArgumentException("src is null");
}
Statement s = src;
switch (s.getKind()) {
case NORMAL_RET_CALLER:
case PARAM_CALLER:
case EXC_RET_CALLER:
// uh oh. anything that flows into the missing function will be killed.
case NORMAL:
// only control dependence flows into the missing function.
// this control dependence does not flow back to the caller.
return ReachabilityFunctions.KILL_FLOW;
case HEAP_PARAM_CALLEE:
case HEAP_PARAM_CALLER:
case HEAP_RET_CALLEE:
case HEAP_RET_CALLER:
if (dest instanceof HeapStatement) {
HeapStatement hd = (HeapStatement) dest;
HeapStatement hs = (HeapStatement) src;
if (hs.getLocation().equals(hd.getLocation())) {
return IdentityFlowFunction.identity();
} else {
return ReachabilityFunctions.KILL_FLOW;
}
} else {
return ReachabilityFunctions.KILL_FLOW;
}
default:
Assertions.UNREACHABLE(s.getKind().toString());
return null;
}
}
@Override
public IUnaryFlowFunction getCallToReturnFlowFunction(Statement src, Statement dest) {
return ReachabilityFunctions.createReachabilityFunctions()
.getCallToReturnFlowFunction(src, dest);
}
@Override
public IUnaryFlowFunction getNormalFlowFunction(Statement src, Statement dest) {
return ReachabilityFunctions.createReachabilityFunctions().getNormalFlowFunction(src, dest);
}
@Override
public IFlowFunction getReturnFlowFunction(Statement call, Statement src, Statement dest) {
return ReachabilityFunctions.createReachabilityFunctions()
.getReturnFlowFunction(call, src, dest);
}
public IFlowFunction getReturnFlowFunction(Statement src, Statement dest) {
return ReachabilityFunctions.createReachabilityFunctions().getReturnFlowFunction(src, dest);
}
@Override
public IFlowFunction getUnbalancedReturnFlowFunction(Statement src, Statement dest) {
return getReturnFlowFunction(src, dest);
}
}
| 3,248
| 35.505618
| 99
|
java
|
WALA
|
WALA-master/core/src/main/java/com/ibm/wala/ipa/slicer/Slicer.java
|
/*
* Copyright (c) 2006 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.ipa.slicer;
import com.ibm.wala.dataflow.IFDS.BackwardsSupergraph;
import com.ibm.wala.dataflow.IFDS.IMergeFunction;
import com.ibm.wala.dataflow.IFDS.IPartiallyBalancedFlowFunctions;
import com.ibm.wala.dataflow.IFDS.ISupergraph;
import com.ibm.wala.dataflow.IFDS.PartiallyBalancedTabulationProblem;
import com.ibm.wala.dataflow.IFDS.PartiallyBalancedTabulationSolver;
import com.ibm.wala.dataflow.IFDS.PathEdge;
import com.ibm.wala.dataflow.IFDS.TabulationDomain;
import com.ibm.wala.dataflow.IFDS.TabulationResult;
import com.ibm.wala.dataflow.IFDS.UnorderedDomain;
import com.ibm.wala.ipa.callgraph.CallGraph;
import com.ibm.wala.ipa.callgraph.propagation.InstanceKey;
import com.ibm.wala.ipa.callgraph.propagation.PointerAnalysis;
import com.ibm.wala.ipa.modref.ModRef;
import com.ibm.wala.util.CancelException;
import com.ibm.wala.util.MonitorUtil.IProgressMonitor;
import com.ibm.wala.util.collections.HashSetFactory;
import java.util.Collection;
import java.util.Collections;
/**
* A demand-driven context-sensitive slicer.
*
* <p>This computes a context-sensitive slice, building an SDG and finding realizable paths to a
* statement using tabulation.
*
* <p>This implementation uses a preliminary pointer analysis to compute data dependence between
* heap locations in the SDG.
*/
public class Slicer {
public static final boolean DEBUG = false;
public static final boolean VERBOSE = false;
/** options to control data dependence edges in the SDG */
public enum DataDependenceOptions {
FULL("full", false, false, false, false),
NO_BASE_PTRS("no_base_ptrs", true, false, false, false),
NO_BASE_NO_HEAP("no_base_no_heap", true, true, false, false),
NO_BASE_NO_EXCEPTIONS("no_base_no_exceptions", true, false, false, true),
NO_BASE_NO_HEAP_NO_EXCEPTIONS("no_base_no_heap_no_exceptions", true, true, false, true),
NO_HEAP("no_heap", false, true, false, false),
NO_HEAP_NO_EXCEPTIONS("no_heap_no_exceptions", false, true, false, true),
NO_EXCEPTIONS("no_exceptions", false, false, false, true),
/**
* Note that other code in the slicer checks for the NONE case explicitly, so its effect is not
* entirely captured by the {@code is*()} methods in {@link DataDependenceOptions}
*/
NONE("none", true, true, true, true),
REFLECTION("no_base_no_heap_no_cast", true, true, true, true);
private final String name;
/**
* Ignore data dependence edges representing base pointers? e.g for a statement y = x.f, ignore
* the data dependence edges for x
*/
private final boolean ignoreBasePtrs;
/** Ignore all data dependence edges to or from the heap? */
private final boolean ignoreHeap;
/**
* Ignore outgoing data dependence edges from a cast statements? [This is a special case option
* used for reflection processing]
*/
private final boolean terminateAtCast;
/** Ignore data dependence manifesting throw exception objects? */
private final boolean ignoreExceptions;
DataDependenceOptions(
String name,
boolean ignoreBasePtrs,
boolean ignoreHeap,
boolean terminateAtCast,
boolean ignoreExceptions) {
this.name = name;
this.ignoreBasePtrs = ignoreBasePtrs;
this.ignoreHeap = ignoreHeap;
this.terminateAtCast = terminateAtCast;
this.ignoreExceptions = ignoreExceptions;
}
public final boolean isIgnoreBasePtrs() {
return ignoreBasePtrs;
}
public final boolean isIgnoreHeap() {
return ignoreHeap;
}
public final boolean isIgnoreExceptions() {
return ignoreExceptions;
}
/**
* Should data dependence chains terminate at casts? This is used for reflection processing ...
* we only track flow into casts ... but not out.
*/
public final boolean isTerminateAtCast() {
return terminateAtCast;
}
public final String getName() {
return name;
}
}
/** options to control control dependence edges in the sdg */
public enum ControlDependenceOptions {
/** track all control dependencies */
FULL("full", false, false),
/**
* track no control dependencies. Note that other code in the slicer checks for the NONE case
* explicitly, so its effect is not entirely captured by the {@code is*()} methods in {@link
* ControlDependenceOptions}
*/
NONE("none", true, true),
/** don't track control dependence due to exceptional control flow */
NO_EXCEPTIONAL_EDGES("no_exceptional_edges", true, false),
/** don't track control dependence from caller to callee */
NO_INTERPROC_EDGES("no_interproc_edges", false, true),
/** don't track interprocedural or exceptional control dependence */
NO_INTERPROC_NO_EXCEPTION("no_interproc_no_exception", true, true);
private final String name;
/** ignore control dependence due to exceptional control flow? */
private final boolean ignoreExceptionalEdges;
/** ignore interprocedural control dependence, i.e., from caller to callee or the reverse? */
private final boolean ignoreInterprocEdges;
ControlDependenceOptions(
String name, boolean ignoreExceptionalEdges, boolean ignoreInterprocEdges) {
this.name = name;
this.ignoreExceptionalEdges = ignoreExceptionalEdges;
this.ignoreInterprocEdges = ignoreInterprocEdges;
}
public final String getName() {
return name;
}
public final boolean isIgnoreExceptions() {
return ignoreExceptionalEdges;
}
public final boolean isIgnoreInterproc() {
return ignoreInterprocEdges;
}
}
/**
* @param s a statement of interest
* @return the backward slice of s.
*/
public static <U extends InstanceKey> Collection<Statement> computeBackwardSlice(
Statement s,
CallGraph cg,
PointerAnalysis<U> pa,
DataDependenceOptions dOptions,
ControlDependenceOptions cOptions)
throws IllegalArgumentException, CancelException {
return computeSlice(
new SDG<>(cg, pa, ModRef.<U>make(), dOptions, cOptions), Collections.singleton(s), true);
}
/**
* @param s a statement of interest
* @return the forward slice of s.
*/
public static <U extends InstanceKey> Collection<Statement> computeForwardSlice(
Statement s,
CallGraph cg,
PointerAnalysis<U> pa,
DataDependenceOptions dOptions,
ControlDependenceOptions cOptions)
throws IllegalArgumentException, CancelException {
return computeSlice(
new SDG<>(cg, pa, ModRef.<U>make(), dOptions, cOptions), Collections.singleton(s), false);
}
/** Use the passed-in SDG */
public static Collection<Statement> computeBackwardSlice(SDG<?> sdg, Statement s)
throws IllegalArgumentException, CancelException {
return computeSlice(sdg, Collections.singleton(s), true);
}
/** Use the passed-in SDG */
public static Collection<Statement> computeForwardSlice(SDG<?> sdg, Statement s)
throws IllegalArgumentException, CancelException {
return computeSlice(sdg, Collections.singleton(s), false);
}
/** Use the passed-in SDG */
public static Collection<Statement> computeBackwardSlice(SDG<?> sdg, Collection<Statement> ss)
throws IllegalArgumentException, CancelException {
return computeSlice(sdg, ss, true);
}
/** @param ss a collection of statements of interest */
protected static Collection<Statement> computeSlice(
SDG<?> sdg, Collection<Statement> ss, boolean backward) throws CancelException {
if (sdg == null) {
throw new IllegalArgumentException("sdg cannot be null");
}
return new Slicer().slice(sdg, ss, backward);
}
/**
* Main driver logic.
*
* @param sdg governing system dependence graph
* @param roots set of roots to slice from
* @param backward do a backwards slice?
* @return the {@link Statement}s found by the slicer
*/
public Collection<Statement> slice(SDG<?> sdg, Collection<Statement> roots, boolean backward)
throws CancelException {
return slice(sdg, roots, backward, null);
}
/**
* Main driver logic.
*
* @param sdg governing system dependence graph
* @param roots set of roots to slice from
* @param backward do a backwards slice?
* @param monitor to cancel analysis if needed
* @return the {@link Statement}s found by the slicer
*/
public Collection<Statement> slice(
SDG<?> sdg, Collection<Statement> roots, boolean backward, IProgressMonitor monitor)
throws CancelException {
if (sdg == null) {
throw new IllegalArgumentException("sdg cannot be null");
}
SliceProblem p = makeSliceProblem(roots, sdg, backward);
PartiallyBalancedTabulationSolver<Statement, PDG<?>, Object> solver =
PartiallyBalancedTabulationSolver.createPartiallyBalancedTabulationSolver(p, monitor);
TabulationResult<Statement, PDG<?>, Object> tr = solver.solve();
Collection<Statement> slice = tr.getSupergraphNodesReached();
if (VERBOSE) {
System.err.println("Slicer done.");
}
return slice;
}
/**
* Return an object which encapsulates the tabulation logic for the slice problem. Subclasses can
* override this method to implement special semantics.
*/
protected SliceProblem makeSliceProblem(
Collection<Statement> roots, ISDG sdgView, boolean backward) {
return new SliceProblem(roots, sdgView, backward);
}
/**
* @param s a statement of interest
* @return the backward slice of s.
*/
public static Collection<Statement> computeBackwardSlice(
Statement s, CallGraph cg, PointerAnalysis<InstanceKey> pointerAnalysis)
throws IllegalArgumentException, CancelException {
return computeBackwardSlice(
s, cg, pointerAnalysis, DataDependenceOptions.FULL, ControlDependenceOptions.FULL);
}
/** Tabulation problem representing slicing */
public static class SliceProblem
implements PartiallyBalancedTabulationProblem<Statement, PDG<?>, Object> {
private final Collection<Statement> roots;
private final ISupergraph<Statement, PDG<? extends InstanceKey>> supergraph;
private final SliceFunctions f;
private final boolean backward;
public SliceProblem(Collection<Statement> roots, ISDG sdg, boolean backward) {
this.roots = roots;
this.backward = backward;
SDGSupergraph forwards = new SDGSupergraph(sdg, backward);
this.supergraph = backward ? BackwardsSupergraph.make(forwards) : forwards;
f = new SliceFunctions();
}
/** @see com.ibm.wala.dataflow.IFDS.TabulationProblem#getDomain() */
@Override
public TabulationDomain<Object, Statement> getDomain() {
// a dummy
return new UnorderedDomain<>();
}
/** @see com.ibm.wala.dataflow.IFDS.TabulationProblem#getFunctionMap() */
@Override
public IPartiallyBalancedFlowFunctions<Statement> getFunctionMap() {
return f;
}
/** @see com.ibm.wala.dataflow.IFDS.TabulationProblem#getMergeFunction() */
@Override
public IMergeFunction getMergeFunction() {
return null;
}
/** @see com.ibm.wala.dataflow.IFDS.TabulationProblem#getSupergraph() */
@Override
public ISupergraph<Statement, PDG<?>> getSupergraph() {
return supergraph;
}
@Override
public Collection<PathEdge<Statement>> initialSeeds() {
if (backward) {
Collection<PathEdge<Statement>> result = HashSetFactory.make();
for (Statement st : roots) {
PathEdge<Statement> seed =
PathEdge.createPathEdge(new MethodExitStatement(st.getNode()), 0, st, 0);
result.add(seed);
}
return result;
} else {
Collection<PathEdge<Statement>> result = HashSetFactory.make();
for (Statement st : roots) {
PathEdge<Statement> seed =
PathEdge.createPathEdge(new MethodEntryStatement(st.getNode()), 0, st, 0);
result.add(seed);
}
return result;
}
}
@Override
public Statement getFakeEntry(Statement node) {
return backward
? new MethodExitStatement(node.getNode())
: new MethodEntryStatement(node.getNode());
}
}
}
| 12,616
| 33.378747
| 99
|
java
|
WALA
|
WALA-master/core/src/main/java/com/ibm/wala/ipa/slicer/SlicerUtil.java
|
package com.ibm.wala.ipa.slicer;
import com.ibm.wala.ipa.callgraph.AnalysisScope;
import com.ibm.wala.ipa.callgraph.CGNode;
import com.ibm.wala.ssa.IR;
import com.ibm.wala.ssa.SSAAbstractInvokeInstruction;
import com.ibm.wala.ssa.SSAAbstractThrowInstruction;
import com.ibm.wala.ssa.SSAArrayLoadInstruction;
import com.ibm.wala.ssa.SSAConditionalBranchInstruction;
import com.ibm.wala.ssa.SSAGetInstruction;
import com.ibm.wala.ssa.SSAInstruction;
import com.ibm.wala.ssa.SSANewInstruction;
import com.ibm.wala.ssa.SSAPutInstruction;
import com.ibm.wala.ssa.SSAReturnInstruction;
import com.ibm.wala.util.collections.Iterator2Iterable;
import com.ibm.wala.util.debug.Assertions;
import com.ibm.wala.util.intset.IntSet;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.PrintWriter;
import java.util.Collection;
/** utility methods for working with slices and slice {@link Statement}s */
public class SlicerUtil {
private SlicerUtil() {}
/**
* Find call to method in CGNode
*
* @param n the node
* @param methodName name of called method
* @return Statement calling the method
* @throws com.ibm.wala.util.debug.UnimplementedError if no such statement found
*/
public static Statement findCallTo(CGNode n, String methodName) {
IR ir = n.getIR();
for (SSAInstruction s : Iterator2Iterable.make(ir.iterateAllInstructions())) {
if (s instanceof SSAAbstractInvokeInstruction) {
SSAAbstractInvokeInstruction call = (SSAAbstractInvokeInstruction) s;
if (call.getCallSite().getDeclaredTarget().getName().toString().equals(methodName)) {
IntSet indices = ir.getCallInstructionIndices(call.getCallSite());
Assertions.productionAssertion(
indices.size() == 1, "expected 1 but got " + indices.size());
return new NormalStatement(n, indices.intIterator().next());
}
}
}
Assertions.UNREACHABLE("failed to find call to " + methodName + " in " + n);
return null;
}
/**
* Find the first {@link SSANewInstruction} in a node
*
* @param n the node
* @return Statement corresponding to first new instruction
* @throws com.ibm.wala.util.debug.UnimplementedError if no new instruction is found
*/
public static Statement findFirstAllocation(CGNode n) {
IR ir = n.getIR();
for (int i = 0; i < ir.getInstructions().length; i++) {
SSAInstruction s = ir.getInstructions()[i];
if (s instanceof SSANewInstruction) {
return new NormalStatement(n, i);
}
}
Assertions.UNREACHABLE("failed to find allocation in " + n);
return null;
}
public static void dumpSlice(Collection<Statement> slice) {
dumpSlice(slice, new PrintWriter(System.err));
}
public static void dumpSlice(Collection<Statement> slice, PrintWriter w) {
w.println("SLICE:\n");
int i = 1;
for (Statement s : slice) {
String line = i++ + " " + s;
w.println(line);
w.flush();
}
}
public static void dumpSliceToFile(Collection<Statement> slice, String fileName)
throws FileNotFoundException {
File f = new File(fileName);
FileOutputStream fo = new FileOutputStream(f);
try (final PrintWriter w = new PrintWriter(fo)) {
dumpSlice(slice, w);
}
}
public static int countAllocations(Collection<Statement> slice, boolean applicationOnly) {
int count = 0;
for (Statement s : slice) {
if (s.getKind().equals(Statement.Kind.NORMAL)) {
NormalStatement ns = (NormalStatement) s;
if (ns.getInstruction() instanceof SSANewInstruction) {
if (!applicationOnly || fromApplicationLoader(s)) {
count++;
}
}
}
}
return count;
}
private static boolean fromApplicationLoader(Statement s) {
return s.getNode()
.getClassHierarchy()
.getScope()
.isApplicationLoader(s.getNode().getMethod().getDeclaringClass().getClassLoader());
}
public static int countThrows(Collection<Statement> slice, boolean applicationOnly) {
int count = 0;
for (Statement s : slice) {
if (s.getKind().equals(Statement.Kind.NORMAL)) {
NormalStatement ns = (NormalStatement) s;
if (ns.getInstruction() instanceof SSAAbstractThrowInstruction) {
if (!applicationOnly || fromApplicationLoader(s)) {
count++;
}
}
}
}
return count;
}
public static int countAloads(Collection<Statement> slice) {
int count = 0;
for (Statement s : slice) {
if (s.getKind().equals(Statement.Kind.NORMAL)) {
NormalStatement ns = (NormalStatement) s;
if (ns.getInstruction() instanceof SSAArrayLoadInstruction) {
count++;
}
}
}
return count;
}
public static int countNormals(Collection<Statement> slice) {
int count = 0;
for (Statement s : slice) {
if (s.getKind().equals(Statement.Kind.NORMAL)) {
count++;
}
}
return count;
}
public static int countApplicationNormals(Collection<Statement> slice) {
int count = 0;
for (Statement s : slice) {
if (s.getKind().equals(Statement.Kind.NORMAL)) {
AnalysisScope scope = s.getNode().getClassHierarchy().getScope();
if (scope.isApplicationLoader(
s.getNode().getMethod().getDeclaringClass().getClassLoader())) {
count++;
}
}
}
return count;
}
public static int countConditionals(Collection<Statement> slice) {
int count = 0;
for (Statement s : slice) {
if (s.getKind().equals(Statement.Kind.NORMAL)) {
NormalStatement ns = (NormalStatement) s;
if (ns.getInstruction() instanceof SSAConditionalBranchInstruction) {
count++;
}
}
}
return count;
}
public static int countInvokes(Collection<Statement> slice) {
int count = 0;
for (Statement s : slice) {
if (s.getKind().equals(Statement.Kind.NORMAL)) {
NormalStatement ns = (NormalStatement) s;
if (ns.getInstruction() instanceof SSAAbstractInvokeInstruction) {
count++;
}
}
}
return count;
}
public static int countPutfields(Collection<Statement> slice) {
int count = 0;
for (Statement s : slice) {
if (s.getKind().equals(Statement.Kind.NORMAL)) {
NormalStatement ns = (NormalStatement) s;
if (ns.getInstruction() instanceof SSAPutInstruction) {
SSAPutInstruction p = (SSAPutInstruction) ns.getInstruction();
if (!p.isStatic()) {
count++;
}
}
}
}
return count;
}
public static int countReturns(Collection<Statement> slice) {
int count = 0;
for (Statement s : slice) {
if (s.getKind().equals(Statement.Kind.NORMAL)) {
NormalStatement ns = (NormalStatement) s;
if (ns.getInstruction() instanceof SSAReturnInstruction) {
count++;
}
}
}
return count;
}
public static int countGetfields(Collection<Statement> slice, boolean applicationOnly) {
int count = 0;
for (Statement s : slice) {
if (s.getKind().equals(Statement.Kind.NORMAL)) {
NormalStatement ns = (NormalStatement) s;
if (ns.getInstruction() instanceof SSAGetInstruction) {
SSAGetInstruction p = (SSAGetInstruction) ns.getInstruction();
if (!p.isStatic()) {
if (!applicationOnly || fromApplicationLoader(s)) {
count++;
}
}
}
}
}
return count;
}
public static int countPutstatics(Collection<Statement> slice) {
int count = 0;
for (Statement s : slice) {
if (s.getKind().equals(Statement.Kind.NORMAL)) {
NormalStatement ns = (NormalStatement) s;
if (ns.getInstruction() instanceof SSAPutInstruction) {
SSAPutInstruction p = (SSAPutInstruction) ns.getInstruction();
if (p.isStatic()) {
count++;
}
}
}
}
return count;
}
public static int countGetstatics(Collection<Statement> slice) {
int count = 0;
for (Statement s : slice) {
if (s.getKind().equals(Statement.Kind.NORMAL)) {
NormalStatement ns = (NormalStatement) s;
if (ns.getInstruction() instanceof SSAGetInstruction) {
SSAGetInstruction p = (SSAGetInstruction) ns.getInstruction();
if (p.isStatic()) {
count++;
}
}
}
}
return count;
}
}
| 8,546
| 30.08
| 93
|
java
|
WALA
|
WALA-master/core/src/main/java/com/ibm/wala/ipa/slicer/Statement.java
|
/*
* Copyright (c) 2006 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.ipa.slicer;
import com.ibm.wala.ipa.callgraph.CGNode;
/** Identifier of a statement in an SDG. */
public abstract class Statement {
public enum Kind {
NORMAL,
PHI,
PI,
CATCH,
PARAM_CALLER,
PARAM_CALLEE,
NORMAL_RET_CALLER,
NORMAL_RET_CALLEE,
EXC_RET_CALLER,
EXC_RET_CALLEE,
HEAP_PARAM_CALLER,
HEAP_PARAM_CALLEE,
HEAP_RET_CALLER,
HEAP_RET_CALLEE,
METHOD_ENTRY,
METHOD_EXIT
}
private final CGNode node;
public Statement(final CGNode node) {
super();
if (node == null) {
throw new IllegalArgumentException("null node");
}
this.node = node;
}
public abstract Kind getKind();
public CGNode getNode() {
return node;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
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 Statement other = (Statement) obj;
if (node == null) {
if (other.node != null) return false;
} else if (!node.equals(other.node)) return false;
return true;
}
@Override
public String toString() {
return getKind().toString() + ':' + getNode();
}
}
| 1,750
| 21.74026
| 72
|
java
|
WALA
|
WALA-master/core/src/main/java/com/ibm/wala/ipa/slicer/StatementWithInstructionIndex.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.slicer;
import com.ibm.wala.ipa.callgraph.CGNode;
import com.ibm.wala.ssa.SSAInstruction;
/**
* A {@link Statement} which carries an instruction index, representing the index of an {@link
* SSAInstruction} in the IR instruction array.
*/
public abstract class StatementWithInstructionIndex extends Statement {
private final int instructionIndex;
protected StatementWithInstructionIndex(CGNode node, int instructionIndex) {
super(node);
this.instructionIndex = instructionIndex;
}
public int getInstructionIndex() {
return instructionIndex;
}
public SSAInstruction getInstruction() {
return getNode().getIR().getInstructions()[instructionIndex];
}
@Override
public int hashCode() {
final int prime = 31;
int result = super.hashCode();
result = prime * result + instructionIndex;
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (!super.equals(obj)) return false;
if (getClass() != obj.getClass()) return false;
final StatementWithInstructionIndex other = (StatementWithInstructionIndex) obj;
if (instructionIndex != other.instructionIndex) return false;
return true;
}
@Override
public String toString() {
return super.toString() + '[' + getInstructionIndex() + ']' + getInstruction();
}
}
| 1,733
| 27.9
| 94
|
java
|
WALA
|
WALA-master/core/src/main/java/com/ibm/wala/ipa/slicer/ValueNumberCarrier.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.slicer;
public interface ValueNumberCarrier {
int getValueNumber();
}
| 466
| 28.1875
| 72
|
java
|
WALA
|
WALA-master/core/src/main/java/com/ibm/wala/ipa/slicer/thin/CISDG.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.slicer.thin;
import com.ibm.wala.ipa.callgraph.CGNode;
import com.ibm.wala.ipa.callgraph.propagation.InstanceKey;
import com.ibm.wala.ipa.callgraph.propagation.PointerKey;
import com.ibm.wala.ipa.cha.IClassHierarchy;
import com.ibm.wala.ipa.slicer.ISDG;
import com.ibm.wala.ipa.slicer.PDG;
import com.ibm.wala.ipa.slicer.SDG;
import com.ibm.wala.ipa.slicer.Slicer.ControlDependenceOptions;
import com.ibm.wala.ipa.slicer.Statement;
import com.ibm.wala.util.collections.HashSetFactory;
import com.ibm.wala.util.collections.Iterator2Collection;
import com.ibm.wala.util.collections.IteratorUtil;
import com.ibm.wala.util.collections.MapUtil;
import com.ibm.wala.util.debug.Assertions;
import com.ibm.wala.util.intset.IntSet;
import java.util.Collection;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.stream.Stream;
/**
* A context-insensitive SDG. This class assumes that it is given a normal NO_HEAP SDG. It adds
* context-insensitive heap information directly from heap stores to corresponding loads, based on
* an underlying pointer analysis.
*/
public class CISDG implements ISDG {
private static final boolean DEBUG = false;
/** the basic SDG, without interprocedural heap edges */
final SDG<InstanceKey> noHeap;
/** What pointer keys does each statement mod? */
private final Map<Statement, Set<PointerKey>> ref;
/** What pointer keys does each statement ref? */
private final Map<Statement, Set<PointerKey>> mod;
/** What statements write each pointer key? */
final Map<PointerKey, Set<Statement>> invMod;
/** What statements ref each pointer key? */
final Map<PointerKey, Set<Statement>> invRef;
protected CISDG(
SDG<InstanceKey> noHeap,
Map<Statement, Set<PointerKey>> mod,
Map<Statement, Set<PointerKey>> ref) {
this.noHeap = noHeap;
this.mod = mod;
this.ref = ref;
invMod = MapUtil.inverseMap(mod);
invRef = MapUtil.inverseMap(ref);
}
@Override
public void addEdge(Statement src, Statement dst) {
Assertions.UNREACHABLE();
noHeap.addEdge(src, dst);
}
@Override
public void addNode(Statement n) {
Assertions.UNREACHABLE();
noHeap.addNode(n);
}
@Override
public boolean containsNode(Statement N) {
return noHeap.containsNode(N);
}
@Override
public boolean equals(Object obj) {
Assertions.UNREACHABLE();
return noHeap.equals(obj);
}
@Override
public ControlDependenceOptions getCOptions() {
Assertions.UNREACHABLE();
return noHeap.getCOptions();
}
@Override
public int getMaxNumber() {
return noHeap.getMaxNumber();
}
@Override
public Statement getNode(int number) {
Assertions.UNREACHABLE();
return noHeap.getNode(number);
}
@Override
public int getNumber(Statement N) {
return noHeap.getNumber(N);
}
@Override
public int getNumberOfNodes() {
return noHeap.getNumberOfNodes();
}
@Override
public PDG<InstanceKey> getPDG(CGNode node) {
Assertions.UNREACHABLE();
return noHeap.getPDG(node);
}
@Override
public int getPredNodeCount(Statement N) {
return IteratorUtil.count(getPredNodes(N));
}
@Override
public IntSet getPredNodeNumbers(Statement node) {
Assertions.UNREACHABLE();
return noHeap.getPredNodeNumbers(node);
}
@Override
public Iterator<Statement> getPredNodes(Statement N) {
if (DEBUG) {
System.err.println("getPredNodes " + N);
}
if (ref.get(N) == null) {
return noHeap.getPredNodes(N);
} else {
Collection<Statement> pred = HashSetFactory.make();
for (PointerKey p : ref.get(N)) {
if (invMod.get(p) != null) {
pred.addAll(invMod.get(p));
}
}
pred.addAll(Iterator2Collection.toSet(noHeap.getPredNodes(N)));
return pred.iterator();
}
}
@Override
public int getSuccNodeCount(Statement N) {
return IteratorUtil.count(getSuccNodes(N));
}
@Override
public IntSet getSuccNodeNumbers(Statement node) {
Assertions.UNREACHABLE();
return noHeap.getSuccNodeNumbers(node);
}
@Override
public Iterator<Statement> getSuccNodes(Statement N) {
if (DEBUG) {
System.err.println("getSuccNodes " + N);
}
if (mod.get(N) == null) {
return noHeap.getSuccNodes(N);
} else {
Collection<Statement> succ = HashSetFactory.make();
for (PointerKey p : mod.get(N)) {
if (invRef.get(p) != null) {
succ.addAll(invRef.get(p));
}
}
succ.addAll(Iterator2Collection.toSet(noHeap.getSuccNodes(N)));
return succ.iterator();
}
}
@Override
public boolean hasEdge(Statement src, Statement dst) {
Assertions.UNREACHABLE();
return noHeap.hasEdge(src, dst);
}
@Override
public int hashCode() {
Assertions.UNREACHABLE();
return noHeap.hashCode();
}
@Override
public Iterator<? extends Statement> iterateLazyNodes() {
Assertions.UNREACHABLE();
return noHeap.iterateLazyNodes();
}
@Override
public Iterator<Statement> iterator() {
return noHeap.iterator();
}
@Override
public Stream<Statement> stream() {
return noHeap.stream();
}
@Override
public Iterator<Statement> iterateNodes(IntSet s) {
Assertions.UNREACHABLE();
return noHeap.iterateNodes(s);
}
@Override
public void removeAllIncidentEdges(Statement node) {
Assertions.UNREACHABLE();
noHeap.removeAllIncidentEdges(node);
}
@Override
public void removeEdge(Statement src, Statement dst) {
Assertions.UNREACHABLE();
noHeap.removeEdge(src, dst);
}
@Override
public void removeIncomingEdges(Statement node) {
Assertions.UNREACHABLE();
noHeap.removeIncomingEdges(node);
}
@Override
public void removeNode(Statement n) {
Assertions.UNREACHABLE();
noHeap.removeNode(n);
}
@Override
public void removeNodeAndEdges(Statement N) {
Assertions.UNREACHABLE();
noHeap.removeNodeAndEdges(N);
}
@Override
public void removeOutgoingEdges(Statement node) {
Assertions.UNREACHABLE();
noHeap.removeOutgoingEdges(node);
}
@Override
public String toString() {
Assertions.UNREACHABLE();
return noHeap.toString();
}
@Override
public IClassHierarchy getClassHierarchy() {
return noHeap.getClassHierarchy();
}
}
| 6,698
| 24.184211
| 98
|
java
|
WALA
|
WALA-master/core/src/main/java/com/ibm/wala/ipa/slicer/thin/CISlicer.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.slicer.thin;
import com.ibm.wala.ipa.callgraph.CGNode;
import com.ibm.wala.ipa.callgraph.CallGraph;
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.modref.ExtendedHeapModel;
import com.ibm.wala.ipa.modref.ModRef;
import com.ibm.wala.ipa.slicer.NormalStatement;
import com.ibm.wala.ipa.slicer.SDG;
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.ssa.IR;
import com.ibm.wala.ssa.SSAInstruction;
import com.ibm.wala.util.collections.HashMapFactory;
import com.ibm.wala.util.graph.Graph;
import com.ibm.wala.util.graph.impl.GraphInverter;
import com.ibm.wala.util.graph.traverse.DFS;
import java.util.Collection;
import java.util.Collections;
import java.util.Map;
import java.util.Set;
/**
* A cheap, context-insensitive slicer based on reachability over a custom SDG.
*
* <p>This is a prototype implementation; not tuned.
*
* <p>Currently supports backward slices only.
*
* <p>TODO: Introduce a slicer interface common between this and the CS slicer. TODO: This hasn't
* been tested much. Need regression tests.
*/
public class CISlicer {
/** the dependence graph used for context-insensitive slicing */
private final Graph<Statement> depGraph;
public CISlicer(
CallGraph cg,
PointerAnalysis<InstanceKey> pa,
DataDependenceOptions dOptions,
ControlDependenceOptions cOptions) {
this(cg, pa, ModRef.make(), dOptions, cOptions);
}
public CISlicer(
CallGraph cg,
PointerAnalysis<InstanceKey> pa,
ModRef<InstanceKey> modRef,
DataDependenceOptions dOptions,
ControlDependenceOptions cOptions)
throws IllegalArgumentException {
if (dOptions == null) {
throw new IllegalArgumentException("dOptions == null");
}
if (dOptions.equals(DataDependenceOptions.NO_BASE_PTRS)
|| dOptions.equals(DataDependenceOptions.FULL)) {
throw new IllegalArgumentException("Heap data dependences requested in CISlicer!");
}
SDG<InstanceKey> sdg = new SDG<>(cg, pa, modRef, dOptions, cOptions, null);
Map<Statement, Set<PointerKey>> mod = scanForMod(sdg, pa, modRef);
Map<Statement, Set<PointerKey>> ref = scanForRef(sdg, pa, modRef);
depGraph = GraphInverter.invert(new CISDG(sdg, mod, ref));
}
public CISlicer(
final SDG<InstanceKey> sdg,
final PointerAnalysis<InstanceKey> pa,
final ModRef<InstanceKey> modRef) {
Map<Statement, Set<PointerKey>> mod = scanForMod(sdg, pa, modRef);
Map<Statement, Set<PointerKey>> ref = scanForRef(sdg, pa, modRef);
depGraph = GraphInverter.invert(new CISDG(sdg, mod, ref));
}
public Collection<Statement> computeBackwardThinSlice(Statement seed) {
Collection<Statement> slice = DFS.getReachableNodes(depGraph, Collections.singleton(seed));
return slice;
}
public Collection<Statement> computeBackwardThinSlice(Collection<Statement> seeds) {
Collection<Statement> slice = DFS.getReachableNodes(depGraph, seeds);
return slice;
}
/** Compute the set of pointer keys each statement mods */
public static Map<Statement, Set<PointerKey>> scanForMod(
SDG<InstanceKey> sdg, PointerAnalysis<InstanceKey> pa) {
return scanForMod(sdg, pa, false, ModRef.make());
}
/** Compute the set of pointer keys each statement refs */
public static Map<Statement, Set<PointerKey>> scanForRef(
SDG<InstanceKey> sdg, PointerAnalysis<InstanceKey> pa) {
if (sdg == null) {
throw new IllegalArgumentException("null sdg");
}
return scanForRef(sdg, pa, ModRef.make());
}
/** Compute the set of pointer keys each statement mods */
public static Map<Statement, Set<PointerKey>> scanForMod(
SDG<InstanceKey> sdg, PointerAnalysis<InstanceKey> pa, ModRef<InstanceKey> modRef) {
return scanForMod(sdg, pa, false, modRef);
}
/**
* Compute the set of pointer keys each statement mods. Be careful to avoid eager PDG construction
* here! That means .. don't iterate over SDG statements!
*/
public static Map<Statement, Set<PointerKey>> scanForMod(
SDG<InstanceKey> sdg,
PointerAnalysis<InstanceKey> pa,
boolean ignoreAllocHeapDefs,
ModRef<InstanceKey> modRef) {
if (pa == null) {
throw new IllegalArgumentException("null pa");
}
ExtendedHeapModel h = modRef.makeHeapModel(pa);
Map<Statement, Set<PointerKey>> result = HashMapFactory.make();
for (CGNode n : sdg.getCallGraph()) {
IR ir = n.getIR();
if (ir != null) {
for (int i = 0; i < ir.getInstructions().length; i++) {
SSAInstruction st = ir.getInstructions()[i];
if (st != null) {
Set<PointerKey> mod = modRef.getMod(n, h, pa, st, null, ignoreAllocHeapDefs);
if (!mod.isEmpty()) {
NormalStatement normal = new NormalStatement(n, i);
result.put(normal, mod);
}
}
}
}
}
return result;
}
/**
* Compute the set of PointerKeys each statement refs.Be careful to avoid eager PDG construction
* here! That means .. don't iterate over SDG statements!
*/
public static Map<Statement, Set<PointerKey>> scanForRef(
SDG<InstanceKey> sdg, PointerAnalysis<InstanceKey> pa, ModRef<InstanceKey> modRef) {
if (pa == null) {
throw new IllegalArgumentException("null pa");
}
ExtendedHeapModel h = modRef.makeHeapModel(pa);
Map<Statement, Set<PointerKey>> result = HashMapFactory.make();
for (CGNode n : sdg.getCallGraph()) {
IR ir = n.getIR();
if (ir != null) {
for (int i = 0; i < ir.getInstructions().length; i++) {
SSAInstruction st = ir.getInstructions()[i];
if (st != null) {
Set<PointerKey> mod = modRef.getRef(n, h, pa, st, null);
if (!mod.isEmpty()) {
NormalStatement normal = new NormalStatement(n, i);
result.put(normal, mod);
}
}
}
}
}
return result;
}
}
| 6,610
| 34.929348
| 100
|
java
|
WALA
|
WALA-master/core/src/main/java/com/ibm/wala/ipa/slicer/thin/ThinSlicer.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.slicer.thin;
import com.ibm.wala.ipa.callgraph.CallGraph;
import com.ibm.wala.ipa.callgraph.propagation.InstanceKey;
import com.ibm.wala.ipa.callgraph.propagation.PointerAnalysis;
import com.ibm.wala.ipa.modref.ModRef;
import com.ibm.wala.ipa.slicer.Slicer.ControlDependenceOptions;
import com.ibm.wala.ipa.slicer.Slicer.DataDependenceOptions;
/**
* A cheap, context-insensitive thin slicer based on reachability over a custom SDG.
*
* <p>This is a prototype implementation; not tuned.
*
* <p>Currently supports backward slices only.
*
* <p>TODO: Introduce a slicer interface common between this and the CS slicer. TODO: This hasn't
* been tested much. Need regression tests.
*/
public class ThinSlicer extends CISlicer {
public ThinSlicer(CallGraph cg, PointerAnalysis<InstanceKey> pa) {
this(cg, pa, ModRef.make());
}
public ThinSlicer(CallGraph cg, PointerAnalysis<InstanceKey> pa, ModRef<InstanceKey> modRef) {
super(cg, pa, modRef, DataDependenceOptions.NO_HEAP, ControlDependenceOptions.NONE);
}
}
| 1,426
| 34.675
| 97
|
java
|
WALA
|
WALA-master/core/src/main/java/com/ibm/wala/ipa/summaries/BypassClassTargetSelector.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.summaries;
import com.ibm.wala.classLoader.IClass;
import com.ibm.wala.classLoader.IClassLoader;
import com.ibm.wala.classLoader.NewSiteReference;
import com.ibm.wala.ipa.callgraph.CGNode;
import com.ibm.wala.ipa.callgraph.ClassTargetSelector;
import com.ibm.wala.ipa.cha.IClassHierarchy;
import com.ibm.wala.types.TypeName;
import com.ibm.wala.types.TypeReference;
import java.util.Set;
/**
* A {@link ClassTargetSelector} that looks up the declared type of a {@link NewSiteReference} based
* on bypass rules.
*/
public class BypassClassTargetSelector implements ClassTargetSelector {
private static final boolean DEBUG = false;
/** Set of {@link TypeReference} that should be considered allocatable */
private final Set<TypeReference> allocatableTypes;
/** Governing class hierarchy */
private final IClassHierarchy cha;
/** Delegate */
private final ClassTargetSelector parent;
/** class loader used for synthetic classes */
private final BypassSyntheticClassLoader bypassLoader;
public BypassClassTargetSelector(
ClassTargetSelector parent,
Set<TypeReference> allocatableTypes,
IClassHierarchy cha,
IClassLoader bypassLoader)
throws IllegalArgumentException {
if (bypassLoader == null) {
throw new IllegalArgumentException("bypassLoader == null");
}
if (!(bypassLoader instanceof BypassSyntheticClassLoader)) {
assert false : "unexpected bypass loader: " + bypassLoader.getClass();
}
this.allocatableTypes = allocatableTypes;
this.bypassLoader = (BypassSyntheticClassLoader) bypassLoader;
this.parent = parent;
this.cha = cha;
}
@Override
public IClass getAllocatedTarget(CGNode caller, NewSiteReference site) {
if (site == null) {
throw new IllegalArgumentException("site is null");
}
TypeReference nominalRef = site.getDeclaredType();
if (DEBUG) {
System.err.println(("BypassClassTargetSelector getAllocatedTarget: " + nominalRef));
}
IClass realType = cha.lookupClass(nominalRef);
if (realType == null) {
if (DEBUG) {
System.err.println(("cha lookup failed. Delegating to " + parent.getClass()));
}
return parent.getAllocatedTarget(caller, site);
}
TypeReference realRef = realType.getReference();
if (allocatableTypes.contains(realRef)) {
if (DEBUG) {
System.err.println("allocatableType! ");
}
if (realType.isAbstract() || realType.isInterface()) {
TypeName syntheticName = BypassSyntheticClass.getName(realRef);
IClass result = bypassLoader.lookupClass(syntheticName);
if (result != null) {
return result;
} else {
IClass x = new BypassSyntheticClass(realType, bypassLoader, cha);
bypassLoader.registerClass(syntheticName, x);
return x;
}
} else {
return realType;
}
} else {
if (DEBUG) {
System.err.println(("not allocatable. Delegating to " + parent.getClass()));
}
return parent.getAllocatedTarget(caller, site);
}
}
}
| 3,489
| 31.924528
| 100
|
java
|
WALA
|
WALA-master/core/src/main/java/com/ibm/wala/ipa/summaries/BypassMethodTargetSelector.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.summaries;
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.SyntheticMethod;
import com.ibm.wala.core.util.strings.Atom;
import com.ibm.wala.ipa.callgraph.CGNode;
import com.ibm.wala.ipa.callgraph.MethodTargetSelector;
import com.ibm.wala.ipa.callgraph.impl.ClassHierarchyMethodTargetSelector;
import com.ibm.wala.ipa.cha.IClassHierarchy;
import com.ibm.wala.ssa.SSAInstruction;
import com.ibm.wala.ssa.SSAInstructionFactory;
import com.ibm.wala.types.MemberReference;
import com.ibm.wala.types.MethodReference;
import com.ibm.wala.types.TypeName;
import com.ibm.wala.types.TypeReference;
import com.ibm.wala.util.collections.HashMapFactory;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
/**
* "Non-standard" bypass rules to use during call graph construction.
*
* <p>Normally, the method bypass rules replace the IMethod that is resolved by other means, via the
* getBypass() method. However, the bypass rules can be invoked even before resolving the target of
* a call, by checking the intercept rules.
*
* @author sfink
*/
public class BypassMethodTargetSelector implements MethodTargetSelector {
static final boolean DEBUG = false;
/**
* Method summaries collected for methods. Mapping Object -> MethodSummary where Object is
* either a
*
* <ul>
* <li>MethodReference
* <li>TypeReference
* <li>Atom (package name)
* </ul>
*/
private final Map<MethodReference, MethodSummary> methodSummaries;
/** Set of Atoms representing package names whose methods should be treated as no-ops */
private final Set<Atom> ignoredPackages;
/** Governing class hierarchy. */
protected final IClassHierarchy cha;
/** target selector to use for non-bypassed calls */
protected final MethodTargetSelector parent;
/** for checking method target resolution via CHA */
private final ClassHierarchyMethodTargetSelector chaMethodTargetSelector;
/**
* Mapping from MethodReference -> SyntheticMethod We may call syntheticMethod.put(m,null) ..
* in which case we use containsKey() to check for having already considered m.
*/
private final HashMap<MethodReference, SummarizedMethod> syntheticMethods = HashMapFactory.make();
public BypassMethodTargetSelector(
MethodTargetSelector parent,
Map<MethodReference, MethodSummary> methodSummaries,
Set<Atom> ignoredPackages,
IClassHierarchy cha) {
this.methodSummaries = methodSummaries;
this.ignoredPackages = ignoredPackages;
this.parent = parent;
this.cha = cha;
this.chaMethodTargetSelector = new ClassHierarchyMethodTargetSelector(cha);
}
/**
* Check to see if a particular call site should be bypassed, before checking normal resolution of
* the receiver.
*
* @throws IllegalArgumentException if site is null
*/
@Override
public IMethod getCalleeTarget(CGNode caller, CallSiteReference site, IClass dispatchType) {
if (site == null) {
throw new IllegalArgumentException("site is null");
}
// first, see if we'd like to bypass the CHA-based target for the site
MethodReference ref = site.getDeclaredTarget();
IMethod chaTarget = chaMethodTargetSelector.getCalleeTarget(caller, site, dispatchType);
IMethod target =
(chaTarget == null)
? findOrCreateSyntheticMethod(ref, site.isStatic())
: findOrCreateSyntheticMethod(chaTarget, site.isStatic());
// try synthetic method that matches receiver type
if (dispatchType != null) {
ref = MethodReference.findOrCreate(dispatchType.getReference(), ref.getSelector());
chaTarget = chaMethodTargetSelector.getCalleeTarget(caller, site, dispatchType);
target =
(chaTarget == null)
? findOrCreateSyntheticMethod(ref, site.isStatic())
: findOrCreateSyntheticMethod(chaTarget, site.isStatic());
}
if (DEBUG) {
System.err.println("target is initially " + target);
}
if (target != null) {
return target;
} else {
// didn't bypass the CHA target; check if we should bypass the parent target
if (canIgnore(site.getDeclaredTarget())) {
// we want to generate a NoOpSummary for this method.
return findOrCreateSyntheticMethod(site.getDeclaredTarget(), site.isStatic());
}
// not using if (instanceof ClassHierarchyMethodTargetSelector) because
// we want to make sure that getCalleeTarget() is still called if
// parent is a subclass of ClassHierarchyMethodTargetSelector
if (parent.getClass() == ClassHierarchyMethodTargetSelector.class) {
// already checked this case and decided not to bypass
return chaTarget;
}
target = parent.getCalleeTarget(caller, site, dispatchType);
if (DEBUG) {
System.err.println("target becomes " + target);
}
if (target != null) {
IMethod bypassTarget = findOrCreateSyntheticMethod(target, site.isStatic());
if (DEBUG) System.err.println("bypassTarget is " + target);
return (bypassTarget == null) ? target : bypassTarget;
} else return target;
}
}
/**
* @param m a method reference
* @return a SyntheticMethod corresponding to m; or null if none is available.
*/
protected SyntheticMethod findOrCreateSyntheticMethod(MethodReference m, boolean isStatic) {
if (syntheticMethods.containsKey(m)) {
return syntheticMethods.get(m);
} else {
MethodSummary summ = null;
if (canIgnore(m)) {
TypeReference T = m.getDeclaringClass();
IClass C = cha.lookupClass(T);
if (C == null) {
// did not load class; don't try to create a synthetic method
syntheticMethods.put(m, null);
return null;
}
summ = generateNoOp(m, isStatic);
} else {
summ = findSummary(m);
}
if (summ != null) {
TypeReference T = m.getDeclaringClass();
IClass C = cha.lookupClass(T);
if (C == null) {
syntheticMethods.put(m, null);
return null;
}
SummarizedMethod n = new SummarizedMethodWithNames(m, summ, C);
syntheticMethods.put(m, n);
return n;
} else {
syntheticMethods.put(m, null);
return null;
}
}
}
/**
* @param m a method reference
* @return a SyntheticMethod corresponding to m; or null if none is available.
*/
protected SyntheticMethod findOrCreateSyntheticMethod(IMethod m, boolean isStatic) {
MethodReference ref = m.getReference();
if (syntheticMethods.containsKey(ref)) {
return syntheticMethods.get(ref);
} else {
MethodSummary summ = null;
if (canIgnore(ref)) {
summ = generateNoOp(ref, isStatic);
} else {
summ = findSummary(ref);
}
if (summ != null) {
SummarizedMethod n = new SummarizedMethod(ref, summ, m.getDeclaringClass());
syntheticMethods.put(ref, n);
return n;
} else {
syntheticMethods.put(ref, null);
return null;
}
}
}
/**
* Generate a {@link MethodSummary} which is the "standard" representation of a method that does
* nothing.
*/
public static MethodSummary generateStandardNoOp(
Language l, MethodReference m, boolean isStatic) {
return new NoOpSummary(l, m, isStatic);
}
/**
* Generate a {@link MethodSummary} which is the "standard" representation of a method that does
* nothing. Subclasses may override this method to implement alternative semantics concerning what
* "do nothing" means.
*/
public MethodSummary generateNoOp(MethodReference m, boolean isStatic) {
Language l = cha.resolveMethod(m).getDeclaringClass().getClassLoader().getLanguage();
return new NoOpSummary(l, m, isStatic);
}
private static class NoOpSummary extends MethodSummary {
private final Language l;
public NoOpSummary(Language l, MethodReference method, boolean isStatic) {
super(method);
setStatic(isStatic);
this.l = l;
}
@Override
public SSAInstruction[] getStatements() {
if (getReturnType().equals(TypeReference.Void)) {
return NO_STATEMENTS;
} else {
int nullValue = getNumberOfParameters() + 1;
SSAInstruction[] result = new SSAInstruction[1];
SSAInstructionFactory insts = l.instructionFactory();
result[0] = insts.ReturnInstruction(0, nullValue, getReturnType().isPrimitiveType());
return result;
}
}
}
/** @return true iff we can treat m as a no-op method */
protected boolean canIgnore(MemberReference m) {
TypeReference T = m.getDeclaringClass();
TypeName n = T.getName();
Atom p = n.getPackage();
return ignoredPackages.contains(p);
}
private MethodSummary findSummary(MemberReference m) {
return methodSummaries.get(m);
}
protected IClassHierarchy getClassHierarchy() {
return cha;
}
}
| 9,507
| 33.201439
| 100
|
java
|
WALA
|
WALA-master/core/src/main/java/com/ibm/wala/ipa/summaries/BypassSyntheticClass.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.summaries;
import com.ibm.wala.classLoader.IClass;
import com.ibm.wala.classLoader.IClassLoader;
import com.ibm.wala.classLoader.IField;
import com.ibm.wala.classLoader.IMethod;
import com.ibm.wala.classLoader.SyntheticClass;
import com.ibm.wala.core.util.strings.Atom;
import com.ibm.wala.ipa.cha.IClassHierarchy;
import com.ibm.wala.types.Selector;
import com.ibm.wala.types.TypeName;
import com.ibm.wala.types.TypeReference;
import com.ibm.wala.types.annotations.Annotation;
import com.ibm.wala.util.collections.HashSetFactory;
import com.ibm.wala.util.debug.Assertions;
import com.ibm.wala.util.debug.UnimplementedError;
import java.io.Reader;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
/** A synthetic implementation of a class */
public class BypassSyntheticClass extends SyntheticClass {
/**
* @param T a type reference
* @return a synthetic class name to represent the synthetic form of this type
* @throws IllegalArgumentException if T is null
*/
public static TypeName getName(TypeReference T) {
if (T == null) {
throw new IllegalArgumentException("T is null");
}
String s = "L$" + T.getName().toString().substring(1);
return TypeName.string2TypeName(s);
}
/** The original "real" type corresponding to this synthetic type. */
private final IClass realType;
private final IClassLoader loader;
public BypassSyntheticClass(IClass realType, IClassLoader loader, IClassHierarchy cha)
throws NullPointerException, NullPointerException {
super(TypeReference.findOrCreate(loader.getReference(), getName(realType.getReference())), cha);
this.loader = loader;
this.realType = realType;
}
/** @see com.ibm.wala.classLoader.IClass#getClassLoader() */
@Override
public IClassLoader getClassLoader() {
return loader;
}
/** @see com.ibm.wala.classLoader.IClass#getSuperclass() */
@Override
public IClass getSuperclass() {
if (realType.isInterface()) {
IClass result = loader.lookupClass(TypeReference.JavaLangObject.getName());
if (result != null) {
return result;
} else {
throw new IllegalStateException("could not find java.lang.Object");
}
} else return realType;
}
/** @see com.ibm.wala.classLoader.IClass#getAllImplementedInterfaces() */
@Override
public Collection<IClass> getAllImplementedInterfaces() {
Collection<IClass> realIfaces = realType.getAllImplementedInterfaces();
if (realType.isInterface()) {
HashSet<IClass> result = HashSetFactory.make(realIfaces);
result.add(realType);
return result;
} else {
return realIfaces;
}
}
/** @see com.ibm.wala.classLoader.IClass#getMethod(Selector) */
@Override
public IMethod getMethod(Selector selector) {
return realType.getMethod(selector);
}
/** @see com.ibm.wala.classLoader.IClass#getMethod(Selector) */
@Override
public IField getField(Atom name) {
return realType.getField(name);
}
/** @see com.ibm.wala.classLoader.IClass#getSourceFileName() */
@Override
public String getSourceFileName() {
return realType.getSourceFileName();
}
/** @see com.ibm.wala.classLoader.IClass#getClassInitializer() */
@Override
public IMethod getClassInitializer() {
return null;
}
/** @see com.ibm.wala.classLoader.IClass#getDeclaredMethods() */
@Override
public Collection<? extends IMethod> getDeclaredMethods() {
return realType.getDeclaredMethods();
}
/** @see com.ibm.wala.classLoader.IClass#getDeclaredInstanceFields() */
@Override
public Collection<IField> getDeclaredInstanceFields() {
return realType.getDeclaredInstanceFields();
}
/** @see com.ibm.wala.classLoader.IClass#getDeclaredStaticFields() */
@Override
public Collection<IField> getDeclaredStaticFields() {
return realType.getDeclaredStaticFields();
}
/** @see com.ibm.wala.classLoader.IClass#isInterface() */
public boolean isSyntheticImplentor() {
return realType.isInterface();
}
@Override
public String toString() {
return "<Synthetic "
+ (realType.isInterface() ? "Implementor" : "Subclass")
+ ' '
+ realType
+ '>';
}
public IClass getRealType() {
return realType;
}
@Override
public boolean equals(Object arg0) {
if (arg0 == null) {
return false;
}
if (arg0.getClass().equals(getClass())) {
return realType.equals(((BypassSyntheticClass) arg0).realType);
} else {
return false;
}
}
@Override
public int hashCode() {
return realType.hashCode() * 1621;
}
/** @see com.ibm.wala.classLoader.IClass#getModifiers() */
@Override
public int getModifiers() throws UnimplementedError {
Assertions.UNREACHABLE();
return 0;
}
/** @see com.ibm.wala.classLoader.IClass#isReferenceType() */
@Override
public boolean isReferenceType() {
return getReference().isReferenceType();
}
/** @see com.ibm.wala.classLoader.IClass#getDirectInterfaces() */
@Override
public Collection<IClass> getDirectInterfaces() throws UnimplementedError {
Assertions.UNREACHABLE();
return null;
}
/** @see com.ibm.wala.classLoader.IClass#getAllInstanceFields() */
@Override
public Collection<IField> getAllInstanceFields() {
return realType.getAllInstanceFields();
}
/** @see com.ibm.wala.classLoader.IClass#getAllStaticFields() */
@Override
public Collection<IField> getAllStaticFields() {
return realType.getAllStaticFields();
}
/** @see com.ibm.wala.classLoader.IClass#getAllMethods() */
@Override
public Collection<? extends IMethod> getAllMethods() {
return realType.getAllMethods();
}
/** @see com.ibm.wala.classLoader.IClass#getAllFields() */
@Override
public Collection<IField> getAllFields() {
return realType.getAllFields();
}
@Override
public boolean isPublic() {
return realType.isPublic();
}
@Override
public boolean isPrivate() {
return realType.isPrivate();
}
@Override
public Reader getSource() {
return null;
}
@Override
public Collection<Annotation> getAnnotations() {
return Collections.emptySet();
}
}
| 6,582
| 27.253219
| 100
|
java
|
WALA
|
WALA-master/core/src/main/java/com/ibm/wala/ipa/summaries/BypassSyntheticClassLoader.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.summaries;
import com.ibm.wala.classLoader.IClass;
import com.ibm.wala.classLoader.IClassLoader;
import com.ibm.wala.classLoader.IMethod;
import com.ibm.wala.classLoader.Language;
import com.ibm.wala.classLoader.Module;
import com.ibm.wala.core.util.strings.Atom;
import com.ibm.wala.ipa.cha.IClassHierarchy;
import com.ibm.wala.ssa.SSAInstructionFactory;
import com.ibm.wala.types.ClassLoaderReference;
import com.ibm.wala.types.TypeName;
import com.ibm.wala.util.collections.HashMapFactory;
import com.ibm.wala.util.config.SetOfClasses;
import java.io.IOException;
import java.io.Reader;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
/**
* This class represents class loaders that introduce classes that do not exist in the actual
* application being analyzed. They may be abstract summaries of unanalyzed library code, wrappers
* that encode J2EE specialized behavior or other invented classes.
*
* <p>The intention is that there be (at most) one such classloader in a given class hierarchy, and
* that it be referenced using the "Synthetic" classloader reference. Furthermore, it is required
* that this synthetic loader be a child loader of the Primordial, Extension and Application
* loaders.
*
* <p>This special classloader has some interactions with the hierarchy for, while the classes it
* loads are normal-seeming IClass objects, unlike the other loaders, its set of classes is not
* fixed, causing special cases in code that caches hierarchy data. Also note that this causes the
* getNumberfClasses and iterateAllClasses methods to behave differently for those of other
* classloaders.
*
* <p>Code that wants to introduce synthetic classes uses the registerClass method, giving it an
* Atom which is the class name, and an IClass which is the class to load. Since the synthetic
* loader must be a child of the others, it would be very bad to use an existing name for a new
* synthetic class.
*
* <p>Class lookup works just as for any other classloader.
*
* @author Julian Dolby (dolby@us.ibm.com)
*/
public class BypassSyntheticClassLoader implements IClassLoader {
private final ClassLoaderReference me;
private final IClassLoader parent;
private final IClassHierarchy cha;
private final HashMap<TypeName, IClass> syntheticClasses = HashMapFactory.make();
/**
* Don't change my signature! ClassLoaderFactoryImpl calls me by reflection! yuck.
*
* @param me the name of this class loader
* @param parent its parent
* @param exclusions classes to ignore
* @param cha governing class hierarchy
*/
public BypassSyntheticClassLoader(
ClassLoaderReference me, IClassLoader parent, SetOfClasses exclusions, IClassHierarchy cha) {
if (cha == null) {
throw new IllegalArgumentException("null cha");
}
this.me = me;
this.cha = cha;
this.parent = parent;
}
@Override
public String toString() {
return me.getName().toString();
}
@Override
public IClass lookupClass(TypeName className) {
IClass pc = parent.lookupClass(className);
if (pc == null) {
IClass c = syntheticClasses.get(className);
return c;
} else {
return pc;
}
}
/** Register the existence of a new synthetic class */
public void registerClass(TypeName className, IClass theClass) {
cha.addClass(theClass);
syntheticClasses.put(className, theClass);
}
/** Return the ClassLoaderReference for this class loader. */
@Override
public ClassLoaderReference getReference() {
return me;
}
/** @return an Iterator of all classes loaded by this loader */
@Override
public Iterator<IClass> iterateAllClasses() {
return syntheticClasses.values().iterator();
}
/** @return the number of classes in scope to be loaded by this loader */
@Override
public int getNumberOfClasses() {
return syntheticClasses.size();
}
/** @return the unique name that identifies this class loader. */
@Override
public Atom getName() {
return me.getName();
}
/**
* @return the unique name that identifies the programming language from which this class loader
* loads code.
*/
@Override
public Language getLanguage() {
return parent.getLanguage();
}
@Override
public int getNumberOfMethods() {
// TODO Auto-generated method stub
return 0;
}
@Override
public String getSourceFileName(IClass klass) {
return null;
}
@Override
public IClassLoader getParent() {
return parent;
}
@Override
public void init(List<Module> modules) throws IOException {}
@Override
public void removeAll(Collection<IClass> toRemove) {
if (toRemove == null) {
throw new IllegalArgumentException("toRemove is null");
}
for (IClass c : toRemove) {
syntheticClasses.remove(c.getName());
}
;
}
@Override
public Reader getSource(IClass klass) {
return null;
}
@Override
public SSAInstructionFactory getInstructionFactory() {
return getLanguage().instructionFactory();
}
@Override
public Reader getSource(IMethod method, int offset) {
return null;
}
@Override
public String getSourceFileName(IMethod method, int offset) {
return null;
}
}
| 5,660
| 28.794737
| 99
|
java
|
WALA
|
WALA-master/core/src/main/java/com/ibm/wala/ipa/summaries/LambdaMethodTargetSelector.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.summaries;
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.core.util.strings.Atom;
import com.ibm.wala.ipa.callgraph.CGNode;
import com.ibm.wala.ipa.callgraph.MethodTargetSelector;
import com.ibm.wala.ipa.cha.IClassHierarchy;
import com.ibm.wala.ipa.summaries.LambdaSummaryClass.UnresolvedLambdaBodyException;
import com.ibm.wala.shrike.shrikeCT.BootstrapMethodsReader.BootstrapMethod;
import com.ibm.wala.ssa.IR;
import com.ibm.wala.ssa.SSAAbstractInvokeInstruction;
import com.ibm.wala.ssa.SSAInstructionFactory;
import com.ibm.wala.ssa.SSAInvokeDynamicInstruction;
import com.ibm.wala.types.MethodReference;
import com.ibm.wala.types.TypeReference;
import com.ibm.wala.util.collections.HashMapFactory;
import java.util.Map;
/**
* Generates synthetic summaries to model the behavior of Java 8 lambdas. See <a
* href="https://cr.openjdk.java.net/~briangoetz/lambda/lambda-translation.html">this good
* discussion of how lambdas look in bytecode</a>.
*
* <p>We generate two types of summaries.
*
* <ol>
* <li>A summary class corresponding to an anonymous class generated for the lambda; see {@link
* LambdaSummaryClass}.
* <li>A summary method corresponding to the lambda factory generated by the bootstrap method;
* this is the method actually called by {@code invokedynamic}.
* </ol>
*/
public class LambdaMethodTargetSelector implements MethodTargetSelector {
/** cache of summary methods for lambda factories */
private final Map<BootstrapMethod, SummarizedMethod> methodSummaries = HashMapFactory.make();
/** cache of summaries for lambda anonymous classes */
private final Map<BootstrapMethod, LambdaSummaryClass> classSummaries = HashMapFactory.make();
private final MethodTargetSelector base;
public LambdaMethodTargetSelector(MethodTargetSelector base) {
this.base = base;
}
/**
* Return a synthetic method target for invokedynamic calls corresponding to Java lambdas
*
* @param caller the GCNode in the call graph containing the call
* @param site the call site reference of the call site
* @param receiver the type of the target object or null
* @return a synthetic method if the call is an invokedynamic for Java lambdas; the callee target
* from the base selector otherwise
*/
@Override
public IMethod getCalleeTarget(CGNode caller, CallSiteReference site, IClass receiver) {
IR ir = caller.getIR();
if (ir.getCallInstructionIndices(site) != null) {
SSAAbstractInvokeInstruction call = ir.getCalls(site)[0];
if (call instanceof SSAInvokeDynamicInstruction) {
SSAInvokeDynamicInstruction invoke = (SSAInvokeDynamicInstruction) call;
BootstrapMethod bootstrap = invoke.getBootstrap();
if (bootstrap.isBootstrapForJavaLambdas()) {
IClassHierarchy cha = caller.getClassHierarchy();
// our summary generation relies on being able to resolve the Lambdametafactory class
if (cha.lookupClass(TypeReference.LambdaMetaFactory) != null) {
MethodReference target = site.getDeclaredTarget();
try {
return methodSummaries.computeIfAbsent(
bootstrap,
(b) -> {
MethodSummary summary = getLambdaFactorySummary(caller, site, target, invoke);
return new SummarizedMethod(
summary.getMethod(), summary, cha.lookupClass(target.getDeclaringClass()));
});
} catch (UnresolvedLambdaBodyException e) {
// give up on modeling the lambda
return null;
}
}
}
}
}
return base.getCalleeTarget(caller, site, receiver);
}
/**
* Create a summary for a lambda factory, as it would be generated by the lambda metafactory. The
* lambda factory summary returns an instance of the summary anonymous class for the lambda (see
* {@link LambdaSummaryClass}). If the lambda captures values from the enclosing scope, the lambda
* factory summary stores these values in fields of the summary class.
*/
private MethodSummary getLambdaFactorySummary(
CGNode caller,
CallSiteReference site,
MethodReference target,
SSAInvokeDynamicInstruction invoke) {
String cls =
caller.getMethod().getDeclaringClass().getName().toString().replace("/", "$").substring(1);
int bootstrapIndex = invoke.getBootstrap().getIndexInClassFile();
MethodReference ref =
MethodReference.findOrCreate(
target.getDeclaringClass(),
Atom.findOrCreateUnicodeAtom(
target.getName().toString() + '$' + cls + '$' + bootstrapIndex),
target.getDescriptor());
MethodSummary summary = new MethodSummary(ref);
if (site.isStatic()) {
summary.setStatic(true);
}
int index = 0;
IClass lambda =
classSummaries.computeIfAbsent(
invoke.getBootstrap(), (b) -> LambdaSummaryClass.create(caller, invoke));
SSAInstructionFactory insts = Language.JAVA.instructionFactory();
// allocate an anonymous class object.
// v is a value number beyond the value numbers used for the invokedynamic arguments
int v = target.getNumberOfParameters() + 2;
summary.addStatement(
insts.NewInstruction(index, v, NewSiteReference.make(index, lambda.getReference())));
index++;
// store captured values in anonymous class fields
for (int i = 0; i < target.getNumberOfParameters(); i++) {
summary.addStatement(
insts.PutInstruction(
index++,
v,
i + 1,
lambda.getField(LambdaSummaryClass.getCaptureFieldName(i)).getReference()));
}
// return the anonymous class instance
summary.addStatement(insts.ReturnInstruction(index++, v, false));
return summary;
}
}
| 6,448
| 40.876623
| 100
|
java
|
WALA
|
WALA-master/core/src/main/java/com/ibm/wala/ipa/summaries/LambdaSummaryClass.java
|
/*
* Copyright (c) 2015 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.summaries;
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.SyntheticClass;
import com.ibm.wala.core.util.strings.Atom;
import com.ibm.wala.ipa.callgraph.CGNode;
import com.ibm.wala.ipa.cha.IClassHierarchy;
import com.ibm.wala.shrike.shrikeBT.Constants;
import com.ibm.wala.shrike.shrikeBT.IInvokeInstruction.Dispatch;
import com.ibm.wala.shrike.shrikeCT.InvalidClassFileException;
import com.ibm.wala.ssa.SSAInstructionFactory;
import com.ibm.wala.ssa.SSAInvokeDynamicInstruction;
import com.ibm.wala.types.ClassLoaderReference;
import com.ibm.wala.types.Descriptor;
import com.ibm.wala.types.FieldReference;
import com.ibm.wala.types.MethodReference;
import com.ibm.wala.types.Selector;
import com.ibm.wala.types.TypeReference;
import com.ibm.wala.types.annotations.Annotation;
import com.ibm.wala.util.collections.HashMapFactory;
import com.ibm.wala.util.collections.HashSetFactory;
import java.util.Collection;
import java.util.Collections;
import java.util.Map;
import java.util.Set;
/**
* Synthetic class modeling the anonymous class generated at runtime for a lambda expression. The
* anonymous class implements the relevant functional interface. Our synthetic classes contain
* instance fields corresponding to the values captured by the lambda. The implementation of the
* functional interface method is a "trampoline" that invokes the generated lambda body method with
* the captured values stored in the instance fields.
*
* @see LambdaMethodTargetSelector
*/
public class LambdaSummaryClass extends SyntheticClass {
// Kinds of method handles.
// see https://docs.oracle.com/javase/specs/jvms/se11/html/jvms-5.html#jvms-5.4.3.5
private static final int REF_INVOKEVIRTUAL = 5;
private static final int REF_INVOKESTATIC = 6;
private static final int REF_INVOKESPECIAL = 7;
private static final int REF_NEWINVOKESPECIAL = 8;
private static final int REF_INVOKEINTERFACE = 9;
/**
* Create a lambda summary class and add it to the class hierarchy.
*
* @param caller method containing the relevant invokedynamic instruction
* @param inst the invokedynamic instruction
* @return the summary class
*/
public static LambdaSummaryClass create(CGNode caller, SSAInvokeDynamicInstruction inst) {
String bootstrapCls =
caller.getMethod().getDeclaringClass().getName().toString().replace("/", "$").substring(1);
int bootstrapIndex = inst.getBootstrap().getIndexInClassFile();
TypeReference ref =
TypeReference.findOrCreate(
ClassLoaderReference.Primordial,
"Lwala/lambda" + '$' + bootstrapCls + '$' + bootstrapIndex);
LambdaSummaryClass cls = new LambdaSummaryClass(ref, caller.getClassHierarchy(), inst);
caller.getClassHierarchy().addClass(cls);
return cls;
}
private final SSAInvokeDynamicInstruction invoke;
private final Map<Atom, IField> fields;
private final Map<Selector, IMethod> methods;
private LambdaSummaryClass(
TypeReference T, IClassHierarchy cha, SSAInvokeDynamicInstruction invoke) {
super(T, cha);
this.invoke = invoke;
this.fields = makeFields();
this.methods = Collections.singletonMap(trampoline().getSelector(), makeTrampoline());
}
@Override
public boolean isPublic() {
return false;
}
@Override
public boolean isPrivate() {
return false;
}
@Override
public int getModifiers() throws UnsupportedOperationException {
return Constants.ACC_FINAL | Constants.ACC_SUPER;
}
@Override
public IClass getSuperclass() {
return getClassHierarchy().getRootClass();
}
/** @return singleton set containing the relevant functional interface */
@Override
public Collection<? extends IClass> getDirectInterfaces() {
return Collections.singleton(getClassHierarchy().lookupClass(invoke.getDeclaredResultType()));
}
/** @return relevant functional interface and all of its super-interfaces */
@Override
public Collection<IClass> getAllImplementedInterfaces() {
IClass iface = getClassHierarchy().lookupClass(invoke.getDeclaredResultType());
Set<IClass> result = HashSetFactory.make(iface.getAllImplementedInterfaces());
result.add(iface);
return result;
}
@Override
public IMethod getMethod(Selector selector) {
return methods.get(selector);
}
@Override
public IField getField(Atom name) {
return fields.get(name);
}
@Override
public IMethod getClassInitializer() {
return null;
}
@Override
public Collection<IMethod> getDeclaredMethods() {
return methods.values();
}
@Override
public Collection<IField> getAllInstanceFields() {
return fields.values();
}
@Override
public Collection<IField> getAllStaticFields() {
return Collections.emptySet();
}
@Override
public Collection<IField> getAllFields() {
return getAllInstanceFields();
}
@Override
public Collection<IMethod> getAllMethods() {
return methods.values();
}
@Override
public Collection<IField> getDeclaredInstanceFields() {
return fields.values();
}
private Map<Atom, IField> makeFields() {
Map<Atom, IField> result = HashMapFactory.make();
for (int i = 0; i < invoke.getNumberOfPositionalParameters(); i++) {
// needed to reference current value in anonymous class
final int index = i;
result.put(
getCaptureFieldName(index),
new IField() {
@Override
public IClass getDeclaringClass() {
return LambdaSummaryClass.this;
}
@Override
public Atom getName() {
return getCaptureFieldName(index);
}
@Override
public Collection<Annotation> getAnnotations() {
return Collections.emptySet();
}
@Override
public IClassHierarchy getClassHierarchy() {
return LambdaSummaryClass.this.getClassHierarchy();
}
@Override
public TypeReference getFieldTypeReference() {
return invoke.getDeclaredTarget().getParameterType(index);
}
@Override
public FieldReference getReference() {
return FieldReference.findOrCreate(
LambdaSummaryClass.this.getReference(), getName(), getFieldTypeReference());
}
@Override
public boolean isFinal() {
return true;
}
@Override
public boolean isPrivate() {
return true;
}
@Override
public boolean isProtected() {
return false;
}
@Override
public boolean isPublic() {
return false;
}
@Override
public boolean isStatic() {
return false;
}
@Override
public boolean isVolatile() {
return false;
}
});
}
return result;
}
private MethodReference trampoline() {
try {
return MethodReference.findOrCreate(
LambdaSummaryClass.this.getReference(),
invoke.getDeclaredTarget().getName(),
Descriptor.findOrCreateUTF8(getLambdaDeclaredSignature()));
} catch (InvalidClassFileException e) {
throw new RuntimeException(e);
}
}
private String getLambdaCalleeClass() throws InvalidClassFileException {
int cpIndex = invoke.getBootstrap().callArgumentIndex(1);
return 'L' + invoke.getBootstrap().getCP().getCPHandleClass(cpIndex);
}
private String getLambdaCalleeName() throws InvalidClassFileException {
int cpIndex = invoke.getBootstrap().callArgumentIndex(1);
return invoke.getBootstrap().getCP().getCPHandleName(cpIndex);
}
private String getLambdaCalleeSignature() throws InvalidClassFileException {
int cpIndex = invoke.getBootstrap().callArgumentIndex(1);
return invoke.getBootstrap().getCP().getCPHandleType(cpIndex);
}
private String getLambdaDeclaredSignature() throws InvalidClassFileException {
int cpIndex = invoke.getBootstrap().callArgumentIndex(0);
return invoke.getBootstrap().getCP().getCPMethodType(cpIndex);
}
private int getLambdaCalleeKind() throws InvalidClassFileException {
int cpIndex = invoke.getBootstrap().callArgumentIndex(1);
return invoke.getBootstrap().getCP().getCPHandleKind(cpIndex);
}
private IMethod makeTrampoline() {
// Assume that the functional interface (FI) method takes n arguments (besides the receiver),
// and the lambda captures k variables.
// Value numbers v_1 through v_(n+1) are the formal parameters of the trampoline method.
// v_1 is the lambda summary class instance, and v_2 - v_(n+1) are the args for the FI method.
// we assign value number v_(n+2) - v_(n+k+2) the captured values, via getfield instructions
// that read the relevant fields from v_1.
SSAInstructionFactory insts = getClassLoader().getInstructionFactory();
MethodReference ref = trampoline();
int numFIMethodArgs = ref.getNumberOfParameters();
int lastFIArgValNum = numFIMethodArgs + 1;
MethodSummary summary = new MethodSummary(ref);
int inst = 0;
int numCapturedValues = invoke.getNumberOfPositionalParameters();
int firstCapturedValNum = lastFIArgValNum + 1;
int curValNum = firstCapturedValNum;
// arguments are the captured values, which were stored in the instance fields of the summary
// class
for (int i = 0; i < numCapturedValues; i++) {
summary.addStatement(
insts.GetInstruction(
inst++, curValNum++, 1, getField(getCaptureFieldName(i)).getReference()));
}
try {
MethodReference lambdaBodyCallee =
MethodReference.findOrCreate(
ClassLoaderReference.Application,
getLambdaCalleeClass(),
getLambdaCalleeName(),
getLambdaCalleeSignature());
int kind = getLambdaCalleeKind();
boolean isNew = kind == REF_NEWINVOKESPECIAL;
Dispatch code = getDispatchForMethodHandleKind(kind);
IMethod resolved = getClassHierarchy().resolveMethod(lambdaBodyCallee);
if (resolved == null) {
throw new UnresolvedLambdaBodyException("could not resolve " + lambdaBodyCallee);
}
int numLambdaCalleeParams = resolved.getNumberOfParameters();
// new calls (i.e., <init>) take one extra argument at position 0, the newly allocated object
if (numLambdaCalleeParams != numFIMethodArgs + numCapturedValues + (isNew ? 1 : 0)) {
throw new RuntimeException(
"unexpected # of args "
+ numLambdaCalleeParams
+ " lastFIArgValNum "
+ lastFIArgValNum
+ " numCaptured "
+ numCapturedValues
+ " "
+ lambdaBodyCallee);
}
int params[] = new int[numLambdaCalleeParams];
// if it's a new invocation, holds the value number for the new object
int newValNum = -1;
int curParamInd = 0;
if (isNew) {
// first pass the newly allocated object
summary.addStatement(
insts.NewInstruction(
inst++,
newValNum = curValNum++,
NewSiteReference.make(inst, lambdaBodyCallee.getDeclaringClass())));
params[curParamInd] = newValNum;
curParamInd++;
}
// pass the captured values
for (int i = 0; i < numCapturedValues; i++, curParamInd++) {
params[curParamInd] = firstCapturedValNum + i;
}
// pass the FI method args
for (int i = 0; i < numFIMethodArgs; i++, curParamInd++) {
// args start at v_2
params[curParamInd] = 2 + i;
}
if (lambdaBodyCallee.getReturnType().equals(TypeReference.Void)) {
summary.addStatement(
insts.InvokeInstruction(
inst++,
params,
curValNum++,
CallSiteReference.make(inst, lambdaBodyCallee, code),
null));
if (isNew) {
// trampoline needs to return the new object
summary.addStatement(insts.ReturnInstruction(inst++, newValNum, false));
}
} else {
int ret = curValNum++;
summary.addStatement(
insts.InvokeInstruction(
inst++,
ret,
params,
curValNum++,
CallSiteReference.make(inst, lambdaBodyCallee, code),
null));
summary.addStatement(
insts.ReturnInstruction(
inst++, ret, lambdaBodyCallee.getReturnType().isPrimitiveType()));
}
} catch (InvalidClassFileException e) {
throw new RuntimeException(e);
}
SummarizedMethod method = new SummarizedMethod(ref, summary, LambdaSummaryClass.this);
return method;
}
private static Dispatch getDispatchForMethodHandleKind(int kind) {
Dispatch code;
switch (kind) {
case REF_INVOKEVIRTUAL:
code = Dispatch.VIRTUAL;
break;
case REF_INVOKESTATIC:
code = Dispatch.STATIC;
break;
case REF_INVOKESPECIAL:
case REF_NEWINVOKESPECIAL:
code = Dispatch.SPECIAL;
break;
case REF_INVOKEINTERFACE:
code = Dispatch.INTERFACE;
break;
default:
throw new Error("unexpected dynamic invoke type " + kind);
}
return code;
}
@Override
public Collection<IField> getDeclaredStaticFields() {
return Collections.emptySet();
}
@Override
public boolean isReferenceType() {
return true;
}
/**
* get the synthetic field name for a value captured by the lambda
*
* @param i index of the captured value
* @return the field name
*/
public static Atom getCaptureFieldName(int i) {
return Atom.findOrCreateUnicodeAtom("c" + i);
}
/**
* Exception thrown when the method containing the body of the lambda (or the target of a method
* reference) cannot be resolved.
*/
static class UnresolvedLambdaBodyException extends RuntimeException {
private static final long serialVersionUID = -6504849409929928820L;
public UnresolvedLambdaBodyException(String s) {
super(s);
}
}
}
| 14,910
| 31.699561
| 99
|
java
|
WALA
|
WALA-master/core/src/main/java/com/ibm/wala/ipa/summaries/MethodBypass.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.summaries;
import com.ibm.wala.classLoader.IClass;
import com.ibm.wala.classLoader.IMethod;
import com.ibm.wala.classLoader.SyntheticMethod;
import com.ibm.wala.core.util.strings.Atom;
import com.ibm.wala.ipa.cha.IClassHierarchy;
import com.ibm.wala.types.MemberReference;
import com.ibm.wala.types.MethodReference;
import com.ibm.wala.types.TypeReference;
import com.ibm.wala.util.collections.HashMapFactory;
import com.ibm.wala.util.collections.HashSetFactory;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
/**
* "Non-standard" bypass rules to use during call graph construction.
*
* <p>Normally, the method bypass rules replace the IMethod that is resolved by other means, via the
* getBypass() method. However, the bypass rules can be invoked even before resolving the target of
* a call, by checking the intercept rules.
*/
public class MethodBypass {
static final boolean DEBUG = false;
/**
* Method summaries collected for methods. Mapping Object -> MethodSummary where Object is
* either a
*
* <ul>
* <li>MethodReference
* <li>TypeReference
* <li>Atom (package name)
* </ul>
*/
private final Map<Object, MethodSummary> methodSummaries;
/** Set of TypeReferences which are marked "allocatable" */
private final Set<TypeReference> allocatable;
/** Governing class hierarchy. */
private final IClassHierarchy cha;
/** Mapping from MethodReference -> SyntheticMethod */
private final HashMap<MethodReference, SummarizedMethod> syntheticMethods = HashMapFactory.make();
/** Set of method references that have been considered already. */
private final HashSet<MethodReference> considered = HashSetFactory.make();
public MethodBypass(
Map<Object, MethodSummary> methodSummaries,
Set<TypeReference> allocatable,
IClassHierarchy cha) {
this.methodSummaries = methodSummaries;
this.allocatable = allocatable;
this.cha = cha;
}
/**
* Lookup bypass rules based on a method reference only.
*
* <p>Method getBypass.
*/
private SyntheticMethod getBypass(MethodReference m) {
if (DEBUG) {
System.err.println(("MethodBypass.getBypass? " + m));
}
SyntheticMethod result = findOrCreateSyntheticMethod(m);
if (result != null) {
return result;
}
// first lookup failed ... try resolving target via CHA and try again.
m = resolveTarget(m);
return findOrCreateSyntheticMethod(m);
}
/**
* @param m a method reference
* @return a SyntheticMethod corresponding to m; or null if none is available.
*/
private SyntheticMethod findOrCreateSyntheticMethod(MethodReference m) {
if (considered.contains(m)) {
return syntheticMethods.get(m);
} else {
considered.add(m);
MethodSummary summ = findSummary(m);
if (summ != null) {
TypeReference T = m.getDeclaringClass();
IClass c = cha.lookupClass(T);
assert c != null : "null class for " + T;
SummarizedMethod n = new SummarizedMethod(m, summ, c);
syntheticMethods.put(m, n);
return n;
}
return null;
}
}
private MethodSummary findSummary(MemberReference m) {
MethodSummary result = methodSummaries.get(m);
if (result != null) {
if (DEBUG) {
System.err.println(("findSummary succeeded: " + m));
}
return result;
}
// try the class instead.
TypeReference t = m.getDeclaringClass();
result = methodSummaries.get(t);
if (result != null) {
if (DEBUG) {
System.err.println(("findSummary succeeded: " + t));
}
return result;
}
if (t.isArrayType()) return null;
// finally try the package.
Atom p = extractPackage(t);
result = methodSummaries.get(p);
if (result != null) {
if (DEBUG) {
System.err.println(("findSummary succeeded: " + p));
}
} else {
if (DEBUG) {
System.err.println(("findSummary failed: " + m));
}
}
return result;
}
/**
* Method getBypass. check to see if a call to the receiver 'target' should be redirected to a
* different receiver.
*
* @throws IllegalArgumentException if target is null
*/
public SyntheticMethod getBypass(IMethod target) {
if (target == null) {
throw new IllegalArgumentException("target is null");
}
return getBypass(target.getReference());
}
/**
* Method extractPackage.
*
* @return Atom that represents the package name, or null if this is the unnamed package.
*/
private static Atom extractPackage(TypeReference type) {
String s = type.getName().toString();
int index = s.lastIndexOf('/');
if (index == -1) {
return null;
} else {
s = s.substring(0, index);
return Atom.findOrCreateAsciiAtom(s);
}
}
protected IClassHierarchy getClassHierarchy() {
return cha;
}
protected MethodReference resolveTarget(MethodReference target) {
IMethod m = getClassHierarchy().resolveMethod(target);
if (m != null) {
if (DEBUG) {
System.err.println(("resolveTarget: resolved to " + m));
}
target = m.getReference();
}
return target;
}
/**
* Are we allowed to allocate (for analysis purposes) an instance of a given type? By default, the
* answer is yes iff T is not abstract. However, subclasses and summaries can override this to
* allow "special" abstract classes to be allocatable as well.
*
* @throws IllegalArgumentException if klass is null
*/
public boolean isAllocatable(IClass klass) {
if (klass == null) {
throw new IllegalArgumentException("klass is null");
}
if (!klass.isAbstract() && !klass.isInterface()) {
return true;
} else {
return allocatable.contains(klass.getReference());
}
}
}
| 6,258
| 28.947368
| 100
|
java
|
WALA
|
WALA-master/core/src/main/java/com/ibm/wala/ipa/summaries/MethodSummary.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.summaries;
import com.ibm.wala.core.util.strings.Atom;
import com.ibm.wala.core.util.warnings.Warning;
import com.ibm.wala.ssa.ConstantValue;
import com.ibm.wala.ssa.SSAInstruction;
import com.ibm.wala.types.MethodReference;
import com.ibm.wala.types.TypeReference;
import com.ibm.wala.util.collections.HashMapFactory;
import java.util.ArrayList;
import java.util.Map;
/** Summary information for a method. */
public class MethodSummary {
protected static final SSAInstruction[] NO_STATEMENTS = new SSAInstruction[0];
/** The method summarized */
private final MethodReference method;
/** List of statements that define this method summary */
private ArrayList<SSAInstruction> statements;
/** Map: value number -> constant */
private Map<Integer, ConstantValue> constantValues;
/** Some reason this method summary indicates a problem. */
private String poison;
/** An indication of how severe the poison problem is. */
private byte poisonLevel;
/** Is this a static method? */
private boolean isStatic = false;
/** Is this a "factory" method? */
private boolean isFactory = false;
private final int numberOfParameters;
/** Known names for values */
private Map<Integer, Atom> valueNames = null;
public MethodSummary(MethodReference method) {
this(method, -1);
}
public MethodSummary(MethodReference method, int numberOfParameters) {
if (method == null) {
throw new IllegalArgumentException("null method");
}
this.numberOfParameters = numberOfParameters;
this.method = method;
}
public void setValueNames(Map<Integer, Atom> nameTable) {
this.valueNames = nameTable;
}
public Map<Integer, Atom> getValueNames() {
return valueNames;
}
public Atom getValue(Integer v) {
return valueNames != null && valueNames.containsKey(v) ? valueNames.get(v) : null;
}
public int getNumberOfStatements() {
return (statements == null ? 0 : statements.size());
}
public void addStatement(SSAInstruction statement) {
if (statements == null) {
statements = new ArrayList<>();
}
statements.add(statement);
}
public void addConstant(Integer vn, ConstantValue value) {
if (constantValues == null) constantValues = HashMapFactory.make(5);
constantValues.put(vn, value);
}
/**
* Returns the method.
*
* @return MethodReference
*/
public MethodReference getMethod() {
return method;
}
public boolean isNative() {
// TODO implement this.
return false;
}
public void addPoison(String reason) {
this.poison = reason;
}
public boolean hasPoison() {
return poison != null;
}
public String getPoison() {
return poison;
}
public void setPoisonLevel(byte b) {
poisonLevel = b;
assert b == Warning.MILD || b == Warning.MODERATE || b == Warning.SEVERE;
}
public byte getPoisonLevel() {
return poisonLevel;
}
public SSAInstruction[] getStatements() {
return statements == null ? NO_STATEMENTS : statements.toArray(new SSAInstruction[0]);
}
public Map<Integer, ConstantValue> getConstants() {
return constantValues;
}
/** @return the number of parameters, including the implicit 'this' */
public int getNumberOfParameters() {
if (numberOfParameters >= 0) {
return numberOfParameters;
} else {
return isStatic() ? method.getNumberOfParameters() : method.getNumberOfParameters() + 1;
}
}
public boolean isStatic() {
return isStatic;
}
public void setStatic(boolean b) {
isStatic = b;
}
public TypeReference getReturnType() {
return method.getReturnType();
}
@Override
public String toString() {
return "[Summary: " + method + ']';
}
/** Note that by convention, getParameterType(0) == this for non-static methods. */
public TypeReference getParameterType(int i) {
if (isStatic()) {
return method.getParameterType(i);
} else {
if (i == 0) {
return method.getDeclaringClass();
} else {
return method.getParameterType(i - 1);
}
}
}
/**
* Record if this is a "factory" method; meaning it returns some object which we know little about
* ... usually we'll resolve this based on downstream uses of the object
*/
public void setFactory(boolean b) {
this.isFactory = b;
}
public boolean isFactory() {
return isFactory;
}
}
| 4,792
| 24.494681
| 100
|
java
|
WALA
|
WALA-master/core/src/main/java/com/ibm/wala/ipa/summaries/SummarizedMethod.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.summaries;
import com.ibm.wala.classLoader.IClass;
import com.ibm.wala.classLoader.SyntheticMethod;
import com.ibm.wala.ipa.callgraph.Context;
import com.ibm.wala.ipa.callgraph.impl.Everywhere;
import com.ibm.wala.ssa.IR;
import com.ibm.wala.ssa.SSAInstruction;
import com.ibm.wala.ssa.SSAOptions;
import com.ibm.wala.types.MethodReference;
import com.ibm.wala.types.TypeReference;
/** A {@link SyntheticMethod} representing the semantics encoded in a {@link MethodSummary} */
public class SummarizedMethod extends SyntheticMethod {
static final boolean DEBUG = false;
private final MethodSummary summary;
public SummarizedMethod(MethodReference ref, MethodSummary summary, IClass declaringClass)
throws NullPointerException {
super(ref, declaringClass, summary.isStatic(), summary.isFactory());
this.summary = summary;
assert declaringClass != null;
if (DEBUG) {
System.err.println(("SummarizedMethod ctor: " + ref + ' ' + summary));
}
}
/** @see com.ibm.wala.classLoader.IMethod#isNative() */
@Override
public boolean isNative() {
return summary.isNative();
}
/** @see com.ibm.wala.classLoader.IMethod#isAbstract() */
@Override
public boolean isAbstract() {
return false;
}
@Override
public String getPoison() {
return summary.getPoison();
}
@Override
public byte getPoisonLevel() {
return summary.getPoisonLevel();
}
@Override
public boolean hasPoison() {
return summary.hasPoison();
}
@SuppressWarnings("deprecation")
@Override
public SSAInstruction[] getStatements(SSAOptions options) {
if (DEBUG) {
System.err.println(("getStatements: " + this));
}
return summary.getStatements();
}
@Override
public IR makeIR(Context context, SSAOptions options) {
SSAInstruction instrs[] = getStatements(options);
return new SyntheticIR(
this,
Everywhere.EVERYWHERE,
makeControlFlowGraph(instrs),
instrs,
options,
summary.getConstants());
}
/** @see com.ibm.wala.classLoader.IMethod#getNumberOfParameters() */
@Override
public int getNumberOfParameters() {
return summary.getNumberOfParameters();
}
/** @see com.ibm.wala.classLoader.IMethod#isStatic() */
@Override
public boolean isStatic() {
return summary.isStatic();
}
/** @see com.ibm.wala.classLoader.IMethod#getParameterType(int) */
@Override
public TypeReference getParameterType(int i) {
return summary.getParameterType(i);
}
@Override
public String getLocalVariableName(int bcIndex, int localNumber) {
return summary.getValue(localNumber).toString();
}
}
| 3,048
| 26.718182
| 94
|
java
|
WALA
|
WALA-master/core/src/main/java/com/ibm/wala/ipa/summaries/SummarizedMethodWithNames.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
*/
/*
* Copyright (c) 2013,
* Tobias Blaschke <code@tobiasblaschke.de>
* All rights reserved.
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 3. The names of the contributors may not be used to endorse or promote
* products derived from this software without specific prior written
* permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
package com.ibm.wala.ipa.summaries;
import com.ibm.wala.cfg.AbstractCFG;
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.Context;
import com.ibm.wala.ipa.callgraph.impl.Everywhere;
import com.ibm.wala.ssa.ConstantValue;
import com.ibm.wala.ssa.IR;
import com.ibm.wala.ssa.SSAInstruction;
import com.ibm.wala.ssa.SSAOptions;
import com.ibm.wala.types.MethodReference;
import java.util.Map;
/**
* A SummarizedMethod (for synthetic functions) with variable names.
*
* <p>Using this class instead of a normal SummarizedMethod enables the use of human-readable
* variable names in synthetic methods. This should not change th analysis-result but may come in
* handy when debugging.
*
* @author Tobias Blaschke <code@tobiasblaschke.de>
* @since 2013-11-25
*/
public class SummarizedMethodWithNames extends SummarizedMethod {
private static final boolean DEBUG = false;
private final MethodSummary summary;
private final Map<Integer, Atom> localNames;
public SummarizedMethodWithNames(
MethodReference ref, MethodSummary summary, IClass declaringClass) {
this(ref, summary, declaringClass, summary.getValueNames());
}
public SummarizedMethodWithNames(
MethodReference ref,
MethodSummary summary,
IClass declaringClass,
Map<Integer, Atom> localNames)
throws NullPointerException {
super(ref, summary, declaringClass);
this.summary = summary;
this.localNames = localNames;
if (DEBUG) {
System.err.println("From old MSUM");
}
}
@SuppressWarnings("unused")
public SummarizedMethodWithNames(
MethodReference ref, VolatileMethodSummary summary, IClass declaringClass)
throws NullPointerException {
super(ref, summary.getMethodSummary(), declaringClass);
this.summary = summary.getMethodSummary();
this.localNames = summary.getLocalNames();
if (DEBUG && this.localNames.isEmpty()) {
System.err.println("Local names are empty for " + ref);
}
}
public static class SyntheticIRWithNames extends SyntheticIR {
private final SSA2LocalMap localMap;
public static class SyntheticSSA2LocalMap implements SSA2LocalMap {
private final Map<Integer, Atom> localNames;
public SyntheticSSA2LocalMap(Map<Integer, Atom> localNames) {
this.localNames = localNames;
}
/** Does not respect index. */
@Override
public String[] getLocalNames(int index, int vn) {
if (DEBUG) {
System.err.printf("IR.getLocalNames(%d, %d)\n", index, vn);
}
if (localNames != null && localNames.containsKey(vn)) {
return new String[] {this.localNames.get(vn).toString()};
} else {
return null;
}
}
}
public SyntheticIRWithNames(
IMethod method,
Context context,
AbstractCFG<?, ?> cfg,
SSAInstruction[] instructions,
SSAOptions options,
Map<Integer, ConstantValue> constants,
Map<Integer, Atom> localNames)
throws AssertionError {
super(method, context, cfg, instructions, options, constants);
this.localMap = new SyntheticSSA2LocalMap(localNames);
}
@Override
public SSA2LocalMap getLocalMap() {
return this.localMap;
}
}
/**
* Returns the variable name to a ssa-number.
*
* <p>Does not respect the value of bcIndex.
*/
@Override
public String getLocalVariableName(int bcIndex, int localNumber) {
if (this.localNames.containsKey(localNumber)) {
String name = this.localNames.get(localNumber).toString();
if (DEBUG) {
System.err.printf("getLocalVariableName(bc=%d, no=%d) = %s\n", bcIndex, localNumber, name);
}
return name;
} else {
if (DEBUG) {
System.err.printf("No name for %d\n", localNumber);
}
return super.getLocalVariableName(bcIndex, localNumber);
}
}
@Override
public boolean hasLocalVariableTable() {
return true;
}
@Override
public IR makeIR(Context context, SSAOptions options) {
final SSAInstruction instrs[] = getStatements(options);
final IR ir =
new SyntheticIRWithNames(
this,
Everywhere.EVERYWHERE,
makeControlFlowGraph(instrs),
instrs,
options,
summary.getConstants(),
localNames);
return ir;
}
}
| 6,425
| 32.295337
| 99
|
java
|
WALA
|
WALA-master/core/src/main/java/com/ibm/wala/ipa/summaries/SyntheticIR.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.summaries;
import com.ibm.wala.cfg.AbstractCFG;
import com.ibm.wala.cfg.InducedCFG;
import com.ibm.wala.classLoader.IMethod;
import com.ibm.wala.ipa.callgraph.Context;
import com.ibm.wala.ssa.ConstantValue;
import com.ibm.wala.ssa.IR;
import com.ibm.wala.ssa.SSACFG;
import com.ibm.wala.ssa.SSAIndirectionData;
import com.ibm.wala.ssa.SSAIndirectionData.Name;
import com.ibm.wala.ssa.SSAInstruction;
import com.ibm.wala.ssa.SSAOptions;
import com.ibm.wala.ssa.SSAPhiInstruction;
import com.ibm.wala.ssa.SSAPiInstruction;
import com.ibm.wala.ssa.SymbolTable;
import com.ibm.wala.util.debug.Assertions;
import java.util.Map;
public class SyntheticIR extends IR {
private static final boolean PARANOID = true;
/**
* Create an SSA form, induced over a list of instructions provided externally. This entrypoint is
* often used for, e.g., native method models
*
* @param method the method to construct SSA form for
* @param context the governing context
* @param instructions the SSA instructions which define the body of the method
* @param constants a Map giving information on constant values for the symbol table
* @throws AssertionError if method is null
*/
public SyntheticIR(
IMethod method,
Context context,
AbstractCFG<?, ?> cfg,
SSAInstruction[] instructions,
SSAOptions options,
Map<Integer, ConstantValue> constants)
throws AssertionError {
super(
method,
instructions,
makeSymbolTable(method, instructions, constants, cfg),
new SSACFG(method, cfg, instructions),
options);
if (PARANOID) {
repOK(instructions);
}
setupLocationMap();
}
/** throw an assertion if the instruction array contains a phi instruction */
private static void repOK(SSAInstruction[] instructions) {
for (SSAInstruction s : instructions) {
if (s instanceof SSAPhiInstruction) {
Assertions.UNREACHABLE();
}
if (s instanceof SSAPiInstruction) {
Assertions.UNREACHABLE();
}
}
}
/**
* Set up the symbol table according to statements in the IR
*
* @param constants Map: value number (Integer) -> ConstantValue
*/
private static SymbolTable makeSymbolTable(
IMethod method,
SSAInstruction[] instructions,
Map<Integer, ConstantValue> constants,
AbstractCFG<?, ?> cfg) {
if (method == null) {
throw new IllegalArgumentException("null method");
}
SymbolTable symbolTable = new SymbolTable(method.getNumberOfParameters());
// simulate allocation of value numbers
for (SSAInstruction s : instructions) {
if (s != null) {
updateForInstruction(constants, symbolTable, s);
}
}
/*
* In InducedCFGs, we have nulled out phi instructions from the instruction array ... so go back
* and retrieve them now.
*/
if (cfg instanceof InducedCFG) {
InducedCFG icfg = (InducedCFG) cfg;
for (SSAPhiInstruction phi : icfg.getAllPhiInstructions()) {
updateForInstruction(constants, symbolTable, phi);
}
}
return symbolTable;
}
private static void updateForInstruction(
Map<Integer, ConstantValue> constants, SymbolTable symbolTable, SSAInstruction s) {
for (int j = 0; j < s.getNumberOfDefs(); j++) {
symbolTable.ensureSymbol(s.getDef(j));
}
for (int j = 0; j < s.getNumberOfUses(); j++) {
int vn = s.getUse(j);
symbolTable.ensureSymbol(vn);
if (constants != null && constants.containsKey(vn))
symbolTable.setConstantValue(vn, constants.get(vn));
}
}
/** This returns "", as synthetic IRs have no line numbers right now. */
@Override
protected String instructionPosition(int instructionIndex) {
return "";
}
/** This returns null, as synthetic IRs have no local names right now. */
@Override
public SSA2LocalMap getLocalMap() {
return null;
}
@Override
protected SSAIndirectionData<Name> getIndirectionData() {
return null;
}
}
| 4,427
| 29.965035
| 100
|
java
|
WALA
|
WALA-master/core/src/main/java/com/ibm/wala/ipa/summaries/SyntheticIRFactory.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.summaries;
import com.ibm.wala.cfg.InducedCFG;
import com.ibm.wala.classLoader.SyntheticMethod;
import com.ibm.wala.ipa.callgraph.Context;
import com.ibm.wala.ssa.IR;
import com.ibm.wala.ssa.IRFactory;
import com.ibm.wala.ssa.SSAOptions;
public class SyntheticIRFactory implements IRFactory<SyntheticMethod> {
public InducedCFG makeCFG(SyntheticMethod method) {
if (method == null) {
throw new IllegalArgumentException("method is null");
}
return method.makeControlFlowGraph(method.getStatements());
}
@Override
public IR makeIR(SyntheticMethod method, Context C, SSAOptions options) {
if (method == null) {
throw new IllegalArgumentException("method is null");
}
return method.makeIR(C, options);
}
@Override
public boolean contextIsIrrelevant(SyntheticMethod method) {
// conservatively return false .. the context might matter.
return false;
}
}
| 1,314
| 29.581395
| 75
|
java
|
WALA
|
WALA-master/core/src/main/java/com/ibm/wala/ipa/summaries/VolatileMethodSummary.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
*/
/*
* Copyright (c) 2013,
* Tobias Blaschke <code@tobiasblaschke.de>
* All rights reserved.
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 3. The names of the contributors may not be used to endorse or promote
* products derived from this software without specific prior written
* permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
package com.ibm.wala.ipa.summaries;
import com.ibm.wala.core.util.strings.Atom;
import com.ibm.wala.ssa.ConstantValue;
import com.ibm.wala.ssa.SSAGotoInstruction;
import com.ibm.wala.ssa.SSAInstruction;
import com.ibm.wala.ssa.SSAInstructionFactory;
import com.ibm.wala.ssa.SymbolTable;
import com.ibm.wala.types.MemberReference;
import com.ibm.wala.types.TypeReference;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Instructions can be added in a non-ascending manner.
*
* <p>The later position of the instruction is determined by it's iindex. Additionally this Summary
* may be instructed to prune unnecessary instructions.
*
* <p>However don't go berserk with the iindex as this will consume loads of memory.
*
* <p>You can get an ordinary MethodSummary using the {@link #getMethodSummary()}-Method.
*
* <p>It extends the MethodSummarys capabilities by the functions: * {@link #getStatementAt(int)} *
* {@link #reserveProgramCounters(int)} * {@link #allowReserved(boolean)}
*
* @see com.ibm.wala.ssa.SSAInstructionFactory
* @see com.ibm.wala.ipa.callgraph.impl.FakeRootMethod
* @see com.ibm.wala.ipa.summaries.MethodSummary
* @author Tobias Blaschke <code@tobiasblaschke.de>
* @since 2013-09-08
*/
public class VolatileMethodSummary {
private static final boolean DEBUG = false;
private boolean allowReservedPC = false;
private final MethodSummary summary;
private List<SSAInstruction> instructions = new ArrayList<>();
private final Map<Integer, Atom> localNames = new HashMap<>();
private int currentProgramCounter = 0;
private boolean locked = false;
/** Placeholder for Reserved slots. */
private static final class Reserved extends SSAInstruction {
public Reserved() {
super(SSAInstruction.NO_INDEX);
}
@Override
public SSAInstruction copyForSSA(SSAInstructionFactory insts, int[] defs, int[] uses) {
throw new IllegalStateException();
}
@Override
public int hashCode() {
return 12384;
}
@Override
public boolean isFallThrough() {
return true;
}
@Override
public String toString(SymbolTable symbolTable) {
return "Reserved Slot";
}
@Override
public void visit(IVisitor v) {
throw new IllegalStateException();
}
}
private static final Reserved RESERVED = new Reserved();
/**
* @param summary a "real" summary methods get added to.
* @throws IllegalArgumentException if this summary is null or not empty
*/
public VolatileMethodSummary(MethodSummary summary) {
if (summary == null) {
throw new IllegalArgumentException("The given summary is null");
}
if (summary.getNumberOfStatements() > 0) {
throw new IllegalArgumentException("The given summary is not empty");
}
this.summary = summary;
}
/**
* @param programCounter the ProgramCounter to retrieve the Instruction from
* @return The instruction or null if there is none
* @throws IllegalArgumentException if the ProgramCounter is negative
*/
public SSAInstruction getStatementAt(int programCounter) {
if (programCounter < 0) {
throw new IllegalArgumentException("Program-Counter may not be negative!");
}
if (this.instructions.size() <= programCounter) {
return null;
}
if (this.instructions.get(programCounter).equals(RESERVED)) {
return null;
}
return this.instructions.get(programCounter);
}
/**
* Reserves an amount of ProgramCounters for later use.
*
* <p>This method reserves a count of ProgramCounters and thus affects the value returned by
* getNextProgramCounter. It also marks these ProgramCounters as reserved so you can't use them
* unless you explicitly allow it by {@link #allowReserved(boolean)}.
*
* @param count The amount of ProgramCounters to reserve ongoing from the current ProgramCounter
* @throws IllegalArgumentException if the count is negative (a count of zero is however ok)
*/
public void reserveProgramCounters(int count) {
if (count < 0) {
throw new IllegalArgumentException(
"The count of ProgramCounters to reserve may not be negative");
}
for (int i = 0; i < count; ++i) {
instructions.add(RESERVED);
}
currentProgramCounter += count;
}
/**
* (Dis-)allows the usage of reserved ProgramCounters.
*
* <p>The setting of this function defaults to disallow upon class creation
*
* @param enable A value of true allows the usage of all reserved ProgramCounters
* @return the previous value of allowReserved
*/
public boolean allowReserved(boolean enable) {
boolean prev = this.allowReservedPC;
this.allowReservedPC = enable;
return prev;
}
/**
* Returns if the ProgramCounter is reserved.
*
* @param programCounter the ProgramCounter in question
* @return true if the position is reserved
* @throws IllegalArgumentException if the ProgramCounter is negative
*/
public boolean isReserved(int programCounter) {
if (programCounter < 0) {
throw new IllegalArgumentException("The Program-Counter may not be negative");
}
if (instructions.size() - 1 < programCounter) return false;
if (instructions.get(programCounter) == null) return false;
return instructions.get(programCounter).equals(RESERVED);
}
/**
* Returns if the ProgramCounter is writable.
*
* <p>The ProgramCounter is not writable if there is already an instruction located at that
* ProgramCounter or if the reserved ProgramCounters forbid usage. Thus the answer may depend on
* the setting of {@link #allowReserved(boolean)}.
*
* @param programCounter the ProgramCounter in question
* @return true if you may write to the location
* @throws IllegalArgumentException if the ProgramCounter is negative
*/
public boolean isFree(int programCounter) {
if (programCounter < 0) {
throw new IllegalArgumentException("The Program-Counter may not be negative");
}
if (instructions.size() - 1 < programCounter) return true;
if (instructions.get(programCounter) == null) return true;
return false;
}
/**
* Not exactly dual to {@link #isFree(int)}.
*
* <p>Returns whether an instruction is located at ProgramCounter. Thus it is a shortcut to {@link
* #getStatementAt(int)} != null.
*
* <p>It is not the exact dual to {@link #isFree(int)} as it does not consider reserved
* ProgramCounters.
*
* @param programCounter the ProgramCounter in question
* @return true if there's an instruction at that program counter
* @throws IllegalArgumentException if the ProgramCounter is negative
*/
public boolean isUsed(int programCounter) {
if (programCounter < 0) {
throw new IllegalArgumentException("The Program-Counter may not be negative");
}
if (instructions.size() - 1 < programCounter) return false;
if (instructions.get(programCounter) == null) return false;
if (instructions.get(programCounter).equals(RESERVED)) return false;
return true;
}
/**
* Like {@link #addStatement(SSAInstruction)} but may replace an existing one.
*
* @param statement The statement to add without care of overwriting
* @return true if a statement has actually been overwritten
* @throws IllegalStateException if you may not write to the ProgramCounter due to the setting of
* {@link #allowReserved(boolean)} or {@link #getMethodSummary()} has been called and thus
* this summary got locked.
* @throws NullPointerException if statement is null
* @throws IllegalArgumentException if the statement has set an invalid ProgramCounter
*/
public boolean overwriteStatement(SSAInstruction statement) {
if (this.locked) {
throw new IllegalStateException("Summary locked due to call to getMethodSummary().");
}
if (statement == null) {
throw new NullPointerException("Statement is null!");
}
if (statement.iIndex() < 0) {
throw new IllegalArgumentException("Statement has a negative iindex");
}
if (!this.allowReservedPC && isReserved(statement.iIndex())) {
throw new IllegalStateException(
"ProgramCounter " + statement.iIndex() + " is reserved! Use allowReserved(true).");
}
if (statement.iIndex() > this.currentProgramCounter) {
throw new IllegalArgumentException(
"IIndex "
+ statement.iIndex()
+ " is greater than currentProgramCounter. Use getNextProgramCounter.");
}
boolean didOverwrite = isUsed(statement.iIndex());
while (this.instructions.size() - 1 < statement.iIndex()) this.instructions.add(null);
if (DEBUG) {
System.err.printf("Setting %s to %s\n", statement.iIndex(), statement);
}
this.instructions.set(statement.iIndex(), statement);
return didOverwrite;
}
/**
* Generates the MethodSummary and locks class.
*
* @throws IllegalStateException if you altered the referenced (by constructor) summary
* @return the finished MethodSummary
*/
public MethodSummary getMethodSummary() {
if (locked) {
// Already generated
return this.summary;
}
if (summary.getNumberOfStatements() > 0) {
throw new IllegalStateException(
"Meanwhile Statements have been added to the summary given "
+ "to the constructor. This behavior is not supported!");
}
this.locked = true;
for (int i = 0; i < this.instructions.size(); ++i) {
final SSAInstruction inst = this.instructions.get(i);
if (inst == null) {
if (DEBUG) {
System.err.printf("No instruction at iindex %d\n", i);
}
this.summary.addStatement(null);
} else if (inst == RESERVED) {
// replace reserved slots by 'goto next' statements
this.summary.addStatement(new SSAGotoInstruction(i, i + 1));
} else {
if (DEBUG) {
System.err.printf("Adding @%s: ", inst);
}
this.summary.addStatement(inst);
}
}
// Let the GC free instructions..
this.instructions = null;
return this.summary;
}
// /**
// * Re-enable write access to VolatileMethodSummary (CAUTION...).
// *
// * On a call to {@link #getMethodSummary()} the AndroidModelMethodSummary gets locked
// * to prevent unintended behaviour.
// *
// * Through the call of this function you gain back write access. However you should
// * know what you are doing as the "exported" MethodSummary will not get updated. A
// * AndroidModelMethodSummary of course starts in unlocked state.
// */
// public void unlock() {
// this.locked = false;
// }
//
// Now for the stuff you should be familiar with from MethodSummary, but with a view
// more checks
//
/**
* Adds a statement to the MethodSummary.
*
* @param statement The statement to be added
* @throws IllegalStateException if you may not write to the ProgramCounter due to the setting of
* {@link #allowReserved(boolean)} or {@link #getMethodSummary()} has been called and thus
* this summary got locked.
* @throws NullPointerException if statement is null
* @throws IllegalArgumentException if the statement has set an invalid ProgramCounter or if there
* is already a statement at the statements iindex. In this case you can use {@link
* #overwriteStatement(SSAInstruction)}.
*/
public void addStatement(SSAInstruction statement) {
if (isUsed(statement.iIndex())) {
throw new IllegalArgumentException(
"ProgramCounter "
+ statement.iIndex()
+ " is in use! By "
+ getStatementAt(statement.iIndex())
+ " Use overwriteStatement().");
}
overwriteStatement(statement);
}
/** Optionally add a name for a local variable. */
public void setLocalName(final int number, final String name) {
localNames.put(number, Atom.findOrCreateAsciiAtom(name));
}
/**
* Set localNames merges with existing names.
*
* <p>If a key in merge exists the value is overwritten if not the value is kept (it's a putAll on
* the internal map).
*/
public void setLocalNames(Map<Integer, Atom> merge) {
localNames.putAll(merge);
}
/** A mapping from SSA-Values to Variable-names. */
public Map<Integer, Atom> getLocalNames() {
return localNames;
}
/**
* Assigns a new Constant to a SSA-Value.
*
* @throws IllegalStateException if you redefine a constant or use the number of an existent
* SSA-Variable
* @throws IllegalArgumentException if value is null or negative
*/
public void addConstant(java.lang.Integer vn, ConstantValue value) {
if ((summary.getConstants() != null) && summary.getConstants().containsKey(vn)) {
throw new IllegalStateException("You redefined a constant at number " + vn);
}
if (vn <= 0) {
throw new IllegalArgumentException("SSA-Value may not be zero or negative.");
}
this.summary.addConstant(vn, value);
}
/**
* Adds posion to the function.
*
* <p>This call gets passed directly to the internal MethodSummary.
*/
public void addPoison(java.lang.String reason) {
this.summary.addPoison(reason);
}
/**
* Retrieves a mapping from SSA-Number to a constant.
*
* <p>You can add Constants using the function {@link #addConstant(java.lang.Integer,
* ConstantValue)}. A call to this function gets passed directly to the internal MethodSummary.
*
* @return a mapping from SSA-Number to assigned ConstantValue
*/
public java.util.Map<java.lang.Integer, ConstantValue> getConstants() {
return this.summary.getConstants();
}
/**
* Retrieve the Method this Summary implements.
*
* <p>You'll get a MemberReference which contains the declaring class (which should be the
* FakeRootClass in most cases) and the signature of the method.
*
* <p>This call gets passed directly to the internal MethodSummary.
*
* @return the implemented method as stated above
*/
public MemberReference getMethod() {
return this.summary.getMethod();
}
/**
* Gets you a non-reserved ProgramCounter you can write to.
*
* <p>This function returns the next ProgramCounter for which not({@link #isUsed(int)}) holds.
* Thus it will _not_ give you a ProgramCounter which is reserved even if you enabled writing to
* reserved ProgramCounters using {@link #allowReserved(boolean)}! You'll have to keep track of
* them on your own.
*
* @return A non-reserved writable ProgramCounter
*/
public int getNextProgramCounter() {
while (isUsed(this.currentProgramCounter) || isReserved(this.currentProgramCounter)) {
this.currentProgramCounter++;
}
while (this.instructions.size() < this.currentProgramCounter) this.instructions.add(null);
return this.currentProgramCounter;
}
/**
* Get the count of parameters of the Method this Summary implements.
*
* <p>This call gets passed directly to the internal MethodSummary.
*
* @return Number of parameters
*/
public int getNumberOfParameters() {
return this.summary.getNumberOfParameters();
}
/**
* Gets you the TypeReference of a parameter.
*
* <p>This call gets passed directly to the internal MethodSummary after some checks.
*
* @return the TypeReference of the i-th parameter.
* @throws IllegalArgumentException if the parameter is zero or negative
* @throws ArrayIndexOutOfBoundsException if the parameter is to large
*/
public TypeReference getParameterType(int i) {
if (i <= 0) {
throw new IllegalArgumentException(
"The parater number may not be zero or negative! " + i + " given");
}
if (i >= this.summary.getNumberOfParameters()) {
throw new ArrayIndexOutOfBoundsException("No such parameter index: " + i);
}
return this.summary.getParameterType(i);
}
/**
* Retrieves the poison set using {@link #addPoison(java.lang.String)}
*
* @return The poison-String
*/
public java.lang.String getPoison() {
return this.summary.getPoison();
}
/**
* Retrieves the value of Poison-Level.
*
* <p>This call gets passed directly to the internal MethodSummary.
*
* @return the poison level
*/
public byte getPoisonLevel() {
return this.summary.getPoisonLevel();
}
/**
* Retrieves the return-type of the Function whose body this Summary implements.
*
* <p>This call gets passed directly to the internal MethodSummary.
*/
public TypeReference getReturnType() {
return this.summary.getReturnType();
}
/**
* Get all statements added to the Summary.
*
* <p>This builds a copy of the internal list and may contain 'null'-values if no instruction has
* been placed at a particular pc.
*
* @return The statements of the summary
*/
public SSAInstruction[] getStatements() {
SSAInstruction[] ret = new SSAInstruction[this.instructions.size()];
ret = this.instructions.toArray(ret);
// Remove Reserved
for (int i = 0; i < ret.length; ++i) {
if (ret[i].equals(RESERVED)) {
ret[i] = null;
}
}
return ret;
}
/**
* Returns if Poison has been added using {@link #addPoison(java.lang.String)}.
*
* <p>This call gets passed directly to the internal MethodSummary.
*
* @return true if poison has been added
*/
public boolean hasPoison() {
return this.summary.hasPoison();
}
/**
* Returns if the implemented method is a factory.
*
* <p>This call gets passed directly to the internal MethodSummary.
*
* @return true if it's a factory
*/
public boolean isFactory() {
return this.summary.isFactory();
}
/**
* Return if the implemented method is a native one (which it shouldn't be).
*
* <p>This call gets passed directly to the internal MethodSummary.
*
* @return almost always false
*/
public boolean isNative() {
return this.summary.isNative();
}
/**
* Return if the implemented method is static.
*
* <p>A static method may not access non-static (and thus instance-specific) content.
*
* @return true if the method is static.
*/
public boolean isStatic() {
return this.summary.isStatic();
}
/**
* Set the value returned by {@link #isFactory()}
*
* @throws IllegalStateException if summary was locked
*/
public void setFactory(boolean b) {
if (this.locked) {
throw new IllegalStateException("Summary is locked. Unlock using unlock()");
}
this.summary.setFactory(b);
}
/**
* Set the value returned by {@link #getPoisonLevel()}
*
* @throws IllegalStateException if summary was locked
*/
public void setPoisonLevel(byte b) {
if (this.locked) {
throw new IllegalStateException("Summary is locked. Unlock using unlock()");
}
this.summary.setPoisonLevel(b);
}
/**
* Set the value returned by {@link #isStatic()}
*
* @throws IllegalStateException if summary was locked
*/
public void setStatic(boolean b) {
if (this.locked) {
throw new IllegalStateException("Summary is locked. Unlock using unlock()");
}
this.summary.setStatic(b);
}
/** Generates a String-Representation of an instance of the class. */
@Override
public java.lang.String toString() {
return "VolatileMethodSummary of " + this.summary.toString();
}
}
| 21,443
| 32.823344
| 100
|
java
|
WALA
|
WALA-master/core/src/main/java/com/ibm/wala/ipa/summaries/XMLMethodSummaryReader.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.summaries;
import static com.ibm.wala.types.TypeName.ArrayMask;
import static com.ibm.wala.types.TypeName.ElementBits;
import static com.ibm.wala.types.TypeName.PrimitiveMask;
import com.ibm.wala.classLoader.CallSiteReference;
import com.ibm.wala.classLoader.Language;
import com.ibm.wala.classLoader.NewSiteReference;
import com.ibm.wala.core.util.strings.Atom;
import com.ibm.wala.core.util.warnings.Warning;
import com.ibm.wala.ipa.callgraph.AnalysisScope;
import com.ibm.wala.shrike.shrikeBT.BytecodeConstants;
import com.ibm.wala.shrike.shrikeBT.IInvokeInstruction;
import com.ibm.wala.ssa.ConstantValue;
import com.ibm.wala.ssa.SSAArrayLoadInstruction;
import com.ibm.wala.ssa.SSAArrayStoreInstruction;
import com.ibm.wala.ssa.SSAGetInstruction;
import com.ibm.wala.ssa.SSAInstruction;
import com.ibm.wala.ssa.SSAInstructionFactory;
import com.ibm.wala.ssa.SSANewInstruction;
import com.ibm.wala.ssa.SSAPutInstruction;
import com.ibm.wala.ssa.SSAReturnInstruction;
import com.ibm.wala.ssa.SSAThrowInstruction;
import com.ibm.wala.types.ClassLoaderReference;
import com.ibm.wala.types.Descriptor;
import com.ibm.wala.types.FieldReference;
import com.ibm.wala.types.MethodReference;
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.debug.Assertions;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.StringTokenizer;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.Attributes;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
/** This class reads method summaries from an XML Stream. */
public class XMLMethodSummaryReader implements BytecodeConstants {
static final boolean DEBUG = false;
/** Governing analysis scope */
private final AnalysisScope scope;
/** Method summaries collected for methods */
private final HashMap<MethodReference, MethodSummary> summaries = HashMapFactory.make();
/** Set of TypeReferences that are marked as "allocatable" */
private final HashSet<TypeReference> allocatable = HashSetFactory.make();
/** Set of Atoms that represent packages that can be ignored */
private final HashSet<Atom> ignoredPackages = HashSetFactory.make();
//
// Define XML element names
//
private static final int E_CLASSLOADER = 0;
private static final int E_METHOD = 1;
private static final int E_CLASS = 2;
private static final int E_PACKAGE = 3;
private static final int E_CALL = 4;
private static final int E_NEW = 5;
private static final int E_POISON = 6;
private static final int E_SUMMARY_SPEC = 7;
private static final int E_RETURN = 8;
private static final int E_PUTSTATIC = 9;
private static final int E_AASTORE = 10;
private static final int E_PUTFIELD = 11;
private static final int E_GETFIELD = 12;
private static final int E_ATHROW = 13;
private static final int E_CONSTANT = 14;
private static final int E_AALOAD = 15;
private static final Map<String, Integer> elementMap = HashMapFactory.make(14);
static {
elementMap.put("classloader", E_CLASSLOADER);
elementMap.put("method", E_METHOD);
elementMap.put("class", E_CLASS);
elementMap.put("package", E_PACKAGE);
elementMap.put("call", E_CALL);
elementMap.put("new", E_NEW);
elementMap.put("poison", E_POISON);
elementMap.put("summary-spec", E_SUMMARY_SPEC);
elementMap.put("return", E_RETURN);
elementMap.put("putstatic", E_PUTSTATIC);
elementMap.put("aastore", E_AASTORE);
elementMap.put("putfield", E_PUTFIELD);
elementMap.put("getfield", E_GETFIELD);
elementMap.put("throw", E_ATHROW);
elementMap.put("constant", E_CONSTANT);
elementMap.put("aaload", E_AALOAD);
}
//
// Define XML attribute names
//
private static final String A_NAME = "name";
private static final String A_TYPE = "type";
private static final String A_CLASS = "class";
private static final String A_SIZE = "size";
private static final String A_DESCRIPTOR = "descriptor";
private static final String A_REASON = "reason";
private static final String A_LEVEL = "level";
private static final String A_WILDCARD = "*";
private static final String A_DEF = "def";
private static final String A_STATIC = "static";
private static final String A_VALUE = "value";
private static final String A_FIELD = "field";
private static final String A_FIELD_TYPE = "fieldType";
private static final String A_ARG = "arg";
private static final String A_ALLOCATABLE = "allocatable";
private static final String A_REF = "ref";
private static final String A_INDEX = "index";
private static final String A_IGNORE = "ignore";
private static final String A_FACTORY = "factory";
private static final String A_NUM_ARGS = "numArgs";
private static final String A_PARAM_NAMES = "paramNames";
private static final String V_NULL = "null";
private static final String V_TRUE = "true";
public XMLMethodSummaryReader(InputStream xmlFile, AnalysisScope scope) {
super();
if (xmlFile == null) {
throw new IllegalArgumentException("null xmlFile");
}
if (scope == null) {
throw new IllegalArgumentException("null scope");
}
this.scope = scope;
try {
readXML(xmlFile);
} catch (Exception e) {
throw new Error("bad xml file", e);
}
}
private void readXML(InputStream xml)
throws SAXException, IOException, ParserConfigurationException {
SAXHandler handler = new SAXHandler();
assert xml != null : "Null xml stream";
SAXParserFactory factory = SAXParserFactory.newInstance();
SAXParser parser = factory.newSAXParser();
parser.parse(new InputSource(xml), handler);
}
/**
* @return Method summaries collected for methods. Mapping Object -> MethodSummary where Object
* is either a
* <ul>
* <li>MethodReference
* <li>TypeReference
* <li>Atom (package name)
* </ul>
*/
public Map<MethodReference, MethodSummary> getSummaries() {
return summaries;
}
/** @return Set of TypeReferences marked "allocatable" */
public Set<TypeReference> getAllocatableClasses() {
return allocatable;
}
/** @return Set of Atoms representing ignorable packages */
public Set<Atom> getIgnoredPackages() {
return ignoredPackages;
}
/**
* @author sfink
* <p>SAX parser logic for XML method summaries
*/
private class SAXHandler extends DefaultHandler {
/** The class loader reference for the element being processed */
private ClassLoaderReference governingLoader = null;
/** The method summary for the element being processed */
private MethodSummary governingMethod = null;
/** The declaring class for the element begin processed */
private TypeReference governingClass = null;
/** The package for the element being processed */
private Atom governingPackage = null;
/** The next available local number for the method being processed */
private int nextLocal = -1;
/** A mapping from String (variable name) -> Integer (local number) */
private Map<String, Integer> symbolTable = null;
/**
* @see org.xml.sax.ContentHandler#startElement(java.lang.String, java.lang.String,
* java.lang.String, org.xml.sax.Attributes)
*/
@Override
public void startElement(String uri, String name, String qName, Attributes atts) {
Integer element = elementMap.get(qName);
if (element == null) {
Assertions.UNREACHABLE("Invalid element: " + qName);
}
switch (element) {
case E_CLASSLOADER:
{
String clName = atts.getValue(A_NAME);
governingLoader = classLoaderName2Ref(clName);
}
break;
case E_METHOD:
String mname = atts.getValue(A_NAME);
if (mname.equals(A_WILDCARD)) {
Assertions.UNREACHABLE("Wildcards not currently implemented.");
} else {
startMethod(atts);
}
break;
case E_CLASS:
String cname = atts.getValue(A_NAME);
if (cname.equals(A_WILDCARD)) {
Assertions.UNREACHABLE("Wildcards not currently implemented");
} else {
startClass(cname, atts);
}
break;
case E_PACKAGE:
governingPackage = Atom.findOrCreateUnicodeAtom(atts.getValue(A_NAME));
String ignore = atts.getValue(A_IGNORE);
if (ignore != null && ignore.equals(V_TRUE)) {
ignoredPackages.add(governingPackage);
}
break;
case E_CALL:
processCallSite(atts);
break;
case E_NEW:
processAllocation(atts);
break;
case E_PUTSTATIC:
processPutStatic(atts);
break;
case E_PUTFIELD:
processPutField(atts);
break;
case E_GETFIELD:
processGetField(atts);
break;
case E_ATHROW:
processAthrow(atts);
break;
case E_AASTORE:
processAastore(atts);
break;
case E_AALOAD:
processAaload(atts);
break;
case E_RETURN:
processReturn(atts);
break;
case E_POISON:
processPoison(atts);
break;
case E_CONSTANT:
processConstant(atts);
break;
case E_SUMMARY_SPEC:
break;
default:
Assertions.UNREACHABLE("Unexpected element: " + name);
break;
}
}
private void startClass(String cname, Attributes atts) {
String clName = governingPackage == null ? 'L' + cname : "L" + governingPackage + '/' + cname;
governingClass = className2Ref(clName);
String allocString = atts.getValue(A_ALLOCATABLE);
if (allocString != null) {
Assertions.productionAssertion(allocString.equals("true"));
allocatable.add(governingClass);
}
}
/**
* @see org.xml.sax.ContentHandler#endElement(java.lang.String, java.lang.String,
* java.lang.String)
*/
@Override
public void endElement(String uri, String name, String qName) {
Integer element = elementMap.get(qName);
if (element == null) {
Assertions.UNREACHABLE("Invalid element: " + name);
}
switch (element) {
case E_CLASSLOADER:
governingLoader = null;
break;
case E_METHOD:
if (governingMethod != null) {
checkReturnValue(governingMethod);
}
governingMethod = null;
symbolTable = null;
break;
case E_CLASS:
governingClass = null;
break;
case E_PACKAGE:
governingPackage = null;
break;
case E_CALL:
case E_GETFIELD:
case E_NEW:
case E_POISON:
case E_PUTSTATIC:
case E_PUTFIELD:
case E_AALOAD:
case E_AASTORE:
case E_ATHROW:
case E_SUMMARY_SPEC:
case E_RETURN:
case E_CONSTANT:
break;
default:
Assertions.UNREACHABLE("Unexpected element: " + name);
break;
}
}
/**
* If a method is declared to return a value, be sure the method summary includes a return
* statement. Throw an assertion if not.
*/
private void checkReturnValue(MethodSummary governingMethod) {
Assertions.productionAssertion(governingMethod != null);
Assertions.productionAssertion(governingMethod.getReturnType() != null);
if (governingMethod.getReturnType().isReferenceType()) {
SSAInstruction[] statements = governingMethod.getStatements();
for (SSAInstruction statement : statements) {
if (statement instanceof SSAReturnInstruction) {
return;
}
}
Assertions.UNREACHABLE(
"Method summary " + governingMethod + " must have a return statement.");
}
}
/** Process an element indicating a call instruction */
private void processCallSite(Attributes atts) {
String typeString = atts.getValue(A_TYPE);
String nameString = atts.getValue(A_NAME);
String classString = atts.getValue(A_CLASS);
String descString = atts.getValue(A_DESCRIPTOR);
TypeReference type =
TypeReference.findOrCreate(governingLoader, TypeName.string2TypeName(classString));
Atom nm = Atom.findOrCreateAsciiAtom(nameString);
Language lang = scope.getLanguage(governingLoader.getLanguage());
SSAInstructionFactory insts = lang.instructionFactory();
Descriptor D = Descriptor.findOrCreateUTF8(lang, descString);
MethodReference ref = MethodReference.findOrCreate(type, nm, D);
CallSiteReference site = null;
int nParams = ref.getNumberOfParameters();
switch (typeString) {
case "virtual":
site =
CallSiteReference.make(
governingMethod.getNumberOfStatements(),
ref,
IInvokeInstruction.Dispatch.VIRTUAL);
nParams++;
break;
case "special":
site =
CallSiteReference.make(
governingMethod.getNumberOfStatements(),
ref,
IInvokeInstruction.Dispatch.SPECIAL);
nParams++;
break;
case "interface":
site =
CallSiteReference.make(
governingMethod.getNumberOfStatements(),
ref,
IInvokeInstruction.Dispatch.INTERFACE);
nParams++;
break;
case "static":
site =
CallSiteReference.make(
governingMethod.getNumberOfStatements(), ref, IInvokeInstruction.Dispatch.STATIC);
break;
default:
Assertions.UNREACHABLE("Invalid call type " + typeString);
break;
}
String paramCount = atts.getValue(A_NUM_ARGS);
if (paramCount != null) {
nParams = Integer.parseInt(paramCount);
}
int[] params = new int[nParams];
for (int i = 0; i < params.length; i++) {
String argString = atts.getValue(A_ARG + i);
Assertions.productionAssertion(
argString != null, "unspecified arg in method " + governingMethod + ' ' + site);
Integer valueNumber = symbolTable.get(argString);
if (valueNumber == null) {
if (argString.equals(V_NULL)) {
valueNumber = getValueNumberForNull();
} else {
valueNumber = Integer.parseInt(argString);
}
}
params[i] = valueNumber;
}
// allocate local for exceptions
int exceptionValue = nextLocal++;
// register the local variable defined by this call, if appropriate
String defVar = atts.getValue(A_DEF);
if (defVar != null) {
if (symbolTable.containsKey(defVar)) {
Assertions.UNREACHABLE("Cannot def variable twice: " + defVar + " in " + governingMethod);
}
int defNum = nextLocal;
symbolTable.put(defVar, nextLocal++);
governingMethod.addStatement(
insts.InvokeInstruction(
governingMethod.getNumberOfStatements(),
defNum,
params,
exceptionValue,
site,
null));
} else {
// ignore return value, if any
governingMethod.addStatement(
insts.InvokeInstruction(
governingMethod.getNumberOfStatements(), params, exceptionValue, site, null));
}
}
/** Process an element indicating a new allocation site. */
private void processAllocation(Attributes atts) {
Language lang = scope.getLanguage(governingLoader.getLanguage());
SSAInstructionFactory insts = lang.instructionFactory();
// deduce the concrete type allocated
String classString = atts.getValue(A_CLASS);
final TypeReference type =
TypeReference.findOrCreate(governingLoader, TypeName.string2TypeName(classString));
// register the local variable defined by this allocation
String defVar = atts.getValue(A_DEF);
if (symbolTable.containsKey(defVar)) {
Assertions.UNREACHABLE("Cannot def variable twice: " + defVar + " in " + governingMethod);
}
if (defVar == null) {
// the method summary ignores the def'ed variable.
// just allocate a temporary
defVar = "L" + nextLocal;
}
int defNum = nextLocal;
symbolTable.put(defVar, nextLocal++);
// create the allocation statement and add it to the method summary
NewSiteReference ref = NewSiteReference.make(governingMethod.getNumberOfStatements(), type);
SSANewInstruction a = null;
if (type.isArrayType()) {
String size = atts.getValue(A_SIZE);
Assertions.productionAssertion(size != null);
Integer sNumber = symbolTable.get(size);
Assertions.productionAssertion(sNumber != null);
Assertions.productionAssertion(
// array of objects
type.getDerivedMask() == ArrayMask
||
// array of primitives
type.getDerivedMask() == ((ArrayMask << ElementBits) | PrimitiveMask));
a =
insts.NewInstruction(
governingMethod.getNumberOfStatements(), defNum, ref, new int[] {sNumber});
} else {
a = insts.NewInstruction(governingMethod.getNumberOfStatements(), defNum, ref);
}
governingMethod.addStatement(a);
}
/** Process an element indicating an Athrow */
private void processAthrow(Attributes atts) {
Language lang = scope.getLanguage(governingLoader.getLanguage());
SSAInstructionFactory insts = lang.instructionFactory();
// get the value thrown
String V = atts.getValue(A_VALUE);
if (V == null) {
Assertions.UNREACHABLE("Must specify value for putfield " + governingMethod);
}
Integer valueNumber = symbolTable.get(V);
if (valueNumber == null) {
Assertions.UNREACHABLE("Cannot lookup value: " + V);
}
SSAThrowInstruction T =
insts.ThrowInstruction(governingMethod.getNumberOfStatements(), valueNumber);
governingMethod.addStatement(T);
}
/** Process an element indicating a putfield. */
private void processGetField(Attributes atts) {
Language lang = scope.getLanguage(governingLoader.getLanguage());
SSAInstructionFactory insts = lang.instructionFactory();
// deduce the field written
String classString = atts.getValue(A_CLASS);
TypeReference type =
TypeReference.findOrCreate(governingLoader, TypeName.string2TypeName(classString));
String fieldString = atts.getValue(A_FIELD);
Atom fieldName = Atom.findOrCreateAsciiAtom(fieldString);
String ftString = atts.getValue(A_FIELD_TYPE);
TypeReference fieldType =
TypeReference.findOrCreate(governingLoader, TypeName.string2TypeName(ftString));
FieldReference field = FieldReference.findOrCreate(type, fieldName, fieldType);
// get the value def'fed
String defVar = atts.getValue(A_DEF);
if (symbolTable.containsKey(defVar)) {
Assertions.UNREACHABLE("Cannot def variable twice: " + defVar + " in " + governingMethod);
}
if (defVar == null) {
Assertions.UNREACHABLE("Must specify def for getfield " + governingMethod);
}
int defNum = nextLocal;
symbolTable.put(defVar, nextLocal++);
// get the ref read from
String R = atts.getValue(A_REF);
if (R == null) {
Assertions.UNREACHABLE("Must specify ref for getfield " + governingMethod);
}
Integer refNumber = symbolTable.get(R);
if (refNumber == null) {
Assertions.UNREACHABLE("Cannot lookup ref: " + R);
}
SSAGetInstruction G =
insts.GetInstruction(governingMethod.getNumberOfStatements(), defNum, refNumber, field);
governingMethod.addStatement(G);
}
/** Process an element indicating a putfield. */
private void processPutField(Attributes atts) {
Language lang = scope.getLanguage(governingLoader.getLanguage());
SSAInstructionFactory insts = lang.instructionFactory();
// deduce the field written
String classString = atts.getValue(A_CLASS);
TypeReference type =
TypeReference.findOrCreate(governingLoader, TypeName.string2TypeName(classString));
String fieldString = atts.getValue(A_FIELD);
Atom fieldName = Atom.findOrCreateAsciiAtom(fieldString);
String ftString = atts.getValue(A_FIELD_TYPE);
TypeReference fieldType =
TypeReference.findOrCreate(governingLoader, TypeName.string2TypeName(ftString));
FieldReference field = FieldReference.findOrCreate(type, fieldName, fieldType);
// get the value stored
String V = atts.getValue(A_VALUE);
if (V == null) {
Assertions.UNREACHABLE("Must specify value for putfield " + governingMethod);
}
Integer valueNumber = symbolTable.containsKey(V) ? symbolTable.get(V) : Integer.parseInt(V);
// get the ref stored to
String R = atts.getValue(A_REF);
if (R == null) {
Assertions.UNREACHABLE("Must specify ref for putfield " + governingMethod);
}
Integer refNumber = symbolTable.get(R);
if (refNumber == null) {
Assertions.UNREACHABLE("Cannot lookup ref: " + R);
}
SSAPutInstruction P =
insts.PutInstruction(
governingMethod.getNumberOfStatements(), refNumber, valueNumber, field);
governingMethod.addStatement(P);
}
/** Process an element indicating a putstatic. */
private void processPutStatic(Attributes atts) {
Language lang = scope.getLanguage(governingLoader.getLanguage());
SSAInstructionFactory insts = lang.instructionFactory();
// deduce the field written
String classString = atts.getValue(A_CLASS);
TypeReference type =
TypeReference.findOrCreate(governingLoader, TypeName.string2TypeName(classString));
String fieldString = atts.getValue(A_FIELD);
Atom fieldName = Atom.findOrCreateAsciiAtom(fieldString);
String ftString = atts.getValue(A_FIELD_TYPE);
TypeReference fieldType =
TypeReference.findOrCreate(governingLoader, TypeName.string2TypeName(ftString));
FieldReference field = FieldReference.findOrCreate(type, fieldName, fieldType);
// get the value stored
String V = atts.getValue(A_VALUE);
if (V == null) {
Assertions.UNREACHABLE("Must specify value for putstatic " + governingMethod);
}
Integer valueNumber = symbolTable.get(V);
if (valueNumber == null) {
Assertions.UNREACHABLE("Cannot lookup value: " + V);
}
SSAPutInstruction P =
insts.PutInstruction(governingMethod.getNumberOfStatements(), valueNumber, field);
governingMethod.addStatement(P);
}
/** Process an element indicating an Aastore */
private void processAastore(Attributes atts) {
Language lang = scope.getLanguage(governingLoader.getLanguage());
SSAInstructionFactory insts = lang.instructionFactory();
String R = atts.getValue(A_REF);
if (R == null) {
Assertions.UNREACHABLE("Must specify ref for aastore " + governingMethod);
}
Integer refNumber = symbolTable.get(R);
if (refNumber == null) {
Assertions.UNREACHABLE("Cannot lookup value: " + R);
}
// N.B: we currently ignore the index
String I = atts.getValue(A_INDEX);
if (I == null) {
Assertions.UNREACHABLE("Must specify index for aastore " + governingMethod);
}
String V = atts.getValue(A_VALUE);
if (V == null) {
Assertions.UNREACHABLE("Must specify value for aastore " + governingMethod);
}
/* BEGIN Custom change: expect type information in array-store instructions */
String strType = atts.getValue(A_TYPE);
TypeReference type;
if (strType == null) {
type = TypeReference.JavaLangObject;
} else {
type = TypeReference.findOrCreate(governingLoader, strType);
}
/* END Custom change: get type information in array-store instructions */
Integer valueNumber = symbolTable.get(V);
if (valueNumber == null) {
Assertions.UNREACHABLE("Cannot lookup value: " + V);
}
/* BEGIN Custom change: expect type information in array-store instructions */
SSAArrayStoreInstruction S =
insts.ArrayStoreInstruction(
governingMethod.getNumberOfStatements(), refNumber, 0, valueNumber, type);
/* END Custom change: get type information in array-store instructions */
governingMethod.addStatement(S);
}
/** Process an element indicating an Aaload */
private void processAaload(Attributes atts) {
// <aaload def="foo" ref="arg1" index="the-answer" />
Language lang = scope.getLanguage(governingLoader.getLanguage());
SSAInstructionFactory insts = lang.instructionFactory();
String R = atts.getValue(A_REF);
if (R == null) {
Assertions.UNREACHABLE("Must specify ref for aaload " + governingMethod);
}
Integer refNumber = symbolTable.get(R);
if (refNumber == null) {
Assertions.UNREACHABLE("Cannot lookup value: " + R);
}
String I = atts.getValue(A_INDEX);
if (I == null) {
Assertions.UNREACHABLE("Must specify index for aaload " + governingMethod);
}
Integer idxNumber = symbolTable.get(I);
if (idxNumber == null) {
Assertions.UNREACHABLE("Cannot lookup value: " + I);
}
String strType = atts.getValue(A_TYPE);
TypeReference type;
if (strType == null) {
type = TypeReference.JavaLangObject;
} else {
type = TypeReference.findOrCreate(governingLoader, strType);
}
// get the value def'fed
String defVar = atts.getValue(A_DEF);
if (symbolTable.containsKey(defVar)) {
Assertions.UNREACHABLE("Cannot def variable twice: " + defVar + " in " + governingMethod);
}
if (defVar == null) {
Assertions.UNREACHABLE("Must specify def for getfield " + governingMethod);
}
int defNum = nextLocal;
symbolTable.put(defVar, nextLocal++);
SSAArrayLoadInstruction S =
insts.ArrayLoadInstruction(
governingMethod.getNumberOfStatements(), defNum, refNumber, idxNumber, type);
governingMethod.addStatement(S);
}
/** Process an element indicating a return statement. */
private void processReturn(Attributes atts) {
Language lang = scope.getLanguage(governingLoader.getLanguage());
SSAInstructionFactory insts = lang.instructionFactory();
if (governingMethod.getReturnType() != null) {
String retV = atts.getValue(A_VALUE);
if (retV == null) {
SSAReturnInstruction R = insts.ReturnInstruction(governingMethod.getNumberOfStatements());
governingMethod.addStatement(R);
} else {
Integer valueNumber = symbolTable.get(retV);
if (valueNumber == null) {
if (!retV.equals(V_NULL)) {
Assertions.UNREACHABLE("Cannot return value with no def: " + retV);
} else {
valueNumber = getValueNumberForNull();
}
}
boolean isPrimitive = governingMethod.getReturnType().isPrimitiveType();
SSAReturnInstruction R =
insts.ReturnInstruction(
governingMethod.getNumberOfStatements(), valueNumber, isPrimitive);
governingMethod.addStatement(R);
}
}
}
private Integer getValueNumberForNull() {
Integer valueNumber;
valueNumber = symbolTable.get(V_NULL);
if (valueNumber == null) {
valueNumber = nextLocal++;
symbolTable.put(V_NULL, valueNumber);
}
return valueNumber;
}
private void processConstant(Attributes atts) {
String var = atts.getValue(A_NAME);
if (var == null) Assertions.UNREACHABLE("Must give name for constant");
Integer valueNumber = nextLocal++;
symbolTable.put(var, valueNumber);
String typeString = atts.getValue(A_TYPE);
String valueString = atts.getValue(A_VALUE);
governingMethod.addConstant(
valueNumber,
typeString.equals("int")
? new ConstantValue(Integer.valueOf(valueString))
: typeString.equals("long")
? new ConstantValue(Long.valueOf(valueString))
: typeString.equals("short")
? new ConstantValue(Short.valueOf(valueString))
: typeString.equals("float")
? new ConstantValue(Float.valueOf(valueString))
: typeString.equals("double")
? new ConstantValue(Double.valueOf(valueString))
: null);
}
/** Process an element which indicates this method is "poison" */
private void processPoison(Attributes atts) {
String reason = atts.getValue(A_REASON);
governingMethod.addPoison(reason);
String level = atts.getValue(A_LEVEL);
switch (level) {
case "severe":
governingMethod.setPoisonLevel(Warning.SEVERE);
break;
case "moderate":
governingMethod.setPoisonLevel(Warning.MODERATE);
break;
case "mild":
governingMethod.setPoisonLevel(Warning.MILD);
break;
default:
Assertions.UNREACHABLE("Unexpected level: " + level);
break;
}
}
/**
* Begin processing of a method. 1. Set the governing method. 2. Initialize the nextLocal
* variable
*/
private void startMethod(Attributes atts) {
String methodName = atts.getValue(A_NAME);
Atom mName = Atom.findOrCreateUnicodeAtom(methodName);
String descString = atts.getValue(A_DESCRIPTOR);
Language lang = scope.getLanguage(governingLoader.getLanguage());
Descriptor D = Descriptor.findOrCreateUTF8(lang, descString);
MethodReference ref = MethodReference.findOrCreate(governingClass, mName, D);
boolean isStatic = false;
String staticString = atts.getValue(A_STATIC);
if (staticString != null) {
switch (staticString) {
case "true":
isStatic = true;
break;
case "false":
isStatic = false;
break;
default:
Assertions.UNREACHABLE("Invalid attribute value " + A_STATIC + ": " + staticString);
break;
}
}
// This is somewhat gross, but it is to deal with the fact that
// some non-Java languages have notions of arguments that do not
// map nicely to descriptors.
int nParams;
String specifiedArgs = atts.getValue(A_NUM_ARGS);
if (specifiedArgs == null) {
nParams = ref.getNumberOfParameters();
if (!isStatic) {
nParams += 1;
}
} else {
nParams = Integer.parseInt(specifiedArgs);
}
governingMethod = new MethodSummary(ref, nParams);
governingMethod.setStatic(isStatic);
if (DEBUG) {
System.err.println(("Register method summary: " + ref));
}
summaries.put(ref, governingMethod);
String factoryString = atts.getValue(A_FACTORY);
if (factoryString != null) {
switch (factoryString) {
case "true":
governingMethod.setFactory(true);
break;
case "false":
governingMethod.setFactory(false);
break;
default:
Assertions.UNREACHABLE("Invalid attribute value " + A_FACTORY + ": " + factoryString);
break;
}
}
// note that symbol tables reserve v0 for "unknown", so v1 gets assigned
// to the first parameter "arg0", and so forth.
nextLocal = nParams + 1;
symbolTable = HashMapFactory.make(5);
// create symbols for the parameters
for (int i = 0; i < nParams; i++) {
symbolTable.put("arg" + i, i + 1);
}
int pn = 1;
String paramDescString = atts.getValue(A_PARAM_NAMES);
if (paramDescString != null) {
StringTokenizer paramNames = new StringTokenizer(paramDescString);
while (paramNames.hasMoreTokens()) {
symbolTable.put(paramNames.nextToken(), pn++);
}
}
Map<Integer, Atom> nameTable = HashMapFactory.make();
for (Map.Entry<String, Integer> x : symbolTable.entrySet()) {
if (!x.getKey().startsWith("arg")) {
nameTable.put(x.getValue(), Atom.findOrCreateUnicodeAtom(x.getKey()));
}
}
governingMethod.setValueNames(nameTable);
}
/**
* Method classLoaderName2Ref.
*
* @return ClassLoaderReference
*/
private ClassLoaderReference classLoaderName2Ref(String clName) {
return scope.getLoader(Atom.findOrCreateUnicodeAtom(clName));
}
/**
* Method classLoaderName2Ref.
*
* @return ClassLoaderReference
*/
private TypeReference className2Ref(String clName) {
return TypeReference.findOrCreate(governingLoader, TypeName.string2TypeName(clName));
}
}
}
| 34,246
| 33.803862
| 100
|
java
|
WALA
|
WALA-master/core/src/main/java/com/ibm/wala/model/SyntheticFactory.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.model;
/** A bogus class to support returning "unknown" objects */
public class SyntheticFactory {
/**
* This method should be hijacked.
*
* @return some object by reflection
*/
public static native Object getObject();
}
| 635
| 26.652174
| 72
|
java
|
WALA
|
WALA-master/core/src/main/java/com/ibm/wala/model/java/lang/System.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.model.java.lang;
/** A synthetic model of java.lang.System native methods. */
public class System {
/** A simple model of object-array copy. This is not completely correct. TODO: fix it. */
@SuppressWarnings("ManualArrayCopy")
static void arraycopy(Object src, Object dest) {
if (src instanceof Object[]) {
Object[] A = (Object[]) src;
Object[] B = (Object[]) dest;
for (int i = 0; i < A.length; i++) B[i] = A[i];
} else if (src instanceof int[]) {
int[] A = (int[]) src;
int[] B = (int[]) dest;
for (int i = 0; i < A.length; i++) B[i] = A[i];
} else if (src instanceof char[]) {
char[] A = (char[]) src;
char[] B = (char[]) dest;
for (int i = 0; i < A.length; i++) B[i] = A[i];
} else if (src instanceof short[]) {
short[] A = (short[]) src;
short[] B = (short[]) dest;
for (int i = 0; i < A.length; i++) B[i] = A[i];
} else if (src instanceof long[]) {
long[] A = (long[]) src;
long[] B = (long[]) dest;
for (int i = 0; i < A.length; i++) B[i] = A[i];
} else if (src instanceof byte[]) {
byte[] A = (byte[]) src;
byte[] B = (byte[]) dest;
for (int i = 0; i < A.length; i++) B[i] = A[i];
} else if (src instanceof double[]) {
double[] A = (double[]) src;
double[] B = (double[]) dest;
for (int i = 0; i < A.length; i++) B[i] = A[i];
} else if (src instanceof boolean[]) {
boolean[] A = (boolean[]) src;
boolean[] B = (boolean[]) dest;
for (int i = 0; i < A.length; i++) B[i] = A[i];
} else if (src instanceof float[]) {
float[] A = (float[]) src;
float[] B = (float[]) dest;
for (int i = 0; i < A.length; i++) B[i] = A[i];
} else {
throw new ArrayStoreException();
}
}
}
| 2,190
| 35.516667
| 91
|
java
|
WALA
|
WALA-master/core/src/main/java/com/ibm/wala/model/java/lang/Thread.java
|
/*
* Copyright (c) 2008 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.model.java.lang;
/** A synthetic model of single-threaded behavior */
public class Thread {
@SuppressWarnings("InstantiatingAThreadWithDefaultRunMethod")
static final java.lang.Thread singleThread = new java.lang.Thread();
public static java.lang.Thread currentThread() {
return singleThread;
}
}
| 701
| 29.521739
| 72
|
java
|
WALA
|
WALA-master/core/src/main/java/com/ibm/wala/model/java/lang/reflect/Array.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.model.java.lang.reflect;
/** A synthetic model of java.lang.reflect.Array native methods */
public class Array {
/** A simple model of object-array copy */
public static Object get(Object array, int index)
throws IllegalArgumentException, ArrayIndexOutOfBoundsException {
if (!array.getClass().isArray()) {
throw new IllegalArgumentException();
}
if (array instanceof Object[]) {
Object[] A = (Object[]) array;
return A[index];
} else if (array instanceof int[]) {
int[] A = (int[]) array;
return A[index];
} else if (array instanceof char[]) {
char[] A = (char[]) array;
return A[index];
} else if (array instanceof short[]) {
short[] A = (short[]) array;
return A[index];
} else if (array instanceof long[]) {
long[] A = (long[]) array;
return A[index];
} else if (array instanceof byte[]) {
byte[] A = (byte[]) array;
return A[index];
} else if (array instanceof double[]) {
double[] A = (double[]) array;
return A[index];
} else if (array instanceof boolean[]) {
boolean[] A = (boolean[]) array;
return A[index];
} else if (array instanceof float[]) {
float[] A = (float[]) array;
return A[index];
} else {
return null;
}
}
}
| 1,714
| 29.625
| 72
|
java
|
WALA
|
WALA-master/core/src/main/java/com/ibm/wala/properties/DefaultPropertiesValues.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.properties;
public final class DefaultPropertiesValues {
// --- Common options
public static final String DEFAULT_WALA_REPORT_FILENAME = "wala_report.txt"; // $NON-NLS-1$
public static final String DEFAULT_OUTPUT_DIR = "results"; // $NON-NLS-1$
}
| 652
| 31.65
| 93
|
java
|
WALA
|
WALA-master/core/src/main/java/com/ibm/wala/properties/WalaProperties.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.properties;
import com.ibm.wala.core.util.io.FileProvider;
import com.ibm.wala.util.PlatformUtil;
import com.ibm.wala.util.WalaException;
import com.ibm.wala.util.debug.Assertions;
import com.ibm.wala.util.io.FileUtil;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.Collection;
import java.util.Properties;
public final class WalaProperties {
public static final String WALA_REPORT = "WALA_report"; // $NON-NLS-1$
public static final String INPUT_DIR = "input_dir"; // $NON-NLS-1$
public static final String OUTPUT_DIR = "output_dir"; // $NON-NLS-1$
public static final String J2SE_DIR = "java_runtime_dir"; // $NON-NLS-1$
public static final String J2EE_DIR = "j2ee_runtime_dir"; // $NON-NLS-1$
public static final String ECLIPSE_PLUGINS_DIR = "eclipse_plugins_dir"; // $NON-NLS-1$
public static final String ANDROID_RT_DEX_DIR = "android_rt_dir";
public static final String ANDROID_RT_JAVA_JAR = "android_rt_jar";
public static final String ANDROID_DEX_TOOL = "android_dx_tool";
public static final String ANDROID_APK_TOOL = "android_apk_tool";
public static final String DROIDEL_TOOL = "droidel_tool";
public static final String DROIDEL_ANDROID_JAR = "droidel_android_jar";
/**
* Determine the classpath noted in wala.properties for J2SE standard libraries
*
* <p>If wala.properties cannot be loaded, returns library files in boot classpath.
*
* @throws IllegalStateException if library files cannot be discovered
* @see PlatformUtil#getJDKModules(boolean)
*/
public static String[] getJ2SEJarFiles() {
return getJDKLibraryFiles(false);
}
/**
* Determine the classpath noted in wala.properties for J2SE standard libraries
*
* <p>If wala.properties cannot be loaded, returns library files in boot classpath.
*
* @param justBase Only relevant if wala.properties cannot be loaded. If {@code true}, only
* returns the {@code java.base} library from boot classpath. Otherwise, returns all library
* modules from boot classpath.
* @see PlatformUtil#getJDKModules(boolean)
*/
public static String[] getJDKLibraryFiles(boolean justBase) {
Properties p = null;
try {
p = WalaProperties.loadProperties();
} catch (WalaException e) {
return PlatformUtil.getJDKModules(justBase);
}
String dir = p.getProperty(WalaProperties.J2SE_DIR);
if (dir == null) {
return PlatformUtil.getJDKModules(justBase);
}
if (!new File(dir).isDirectory()) {
System.err.println(
"WARNING: java_runtime_dir "
+ dir
+ " in wala.properties is invalid. Using boot class path instead.");
return PlatformUtil.getJDKModules(justBase);
}
return getJarsInDirectory(dir);
}
/**
* @return names of the Jar files holding J2EE libraries
* @throws IllegalStateException if the J2EE_DIR property is not set
*/
public static String[] getJ2EEJarFiles() {
Properties p = null;
try {
p = WalaProperties.loadProperties();
} catch (WalaException e) {
e.printStackTrace();
throw new IllegalStateException("problem loading wala.properties");
}
String dir = p.getProperty(WalaProperties.J2EE_DIR);
if (dir == null) {
throw new IllegalStateException("No J2EE directory specified");
}
return getJarsInDirectory(dir);
}
public static String[] getJarsInDirectory(String dir) {
File f = new File(dir);
Assertions.productionAssertion(f.isDirectory(), "not a directory: " + dir);
Collection<File> col = FileUtil.listFiles(dir, ".*\\.jar$", true);
String[] result = new String[col.size()];
int i = 0;
for (File jarFile : col) {
result[i++] = jarFile.getAbsolutePath();
}
return result;
}
static final String PROPERTY_FILENAME = "wala.properties"; // $NON-NLS-1$
public static Properties loadProperties() throws WalaException {
try {
Properties result =
loadPropertiesFromFile(WalaProperties.class.getClassLoader(), PROPERTY_FILENAME);
String outputDir = result.getProperty(OUTPUT_DIR, DefaultPropertiesValues.DEFAULT_OUTPUT_DIR);
result.setProperty(OUTPUT_DIR, convertToAbsolute(outputDir));
String walaReport =
result.getProperty(WALA_REPORT, DefaultPropertiesValues.DEFAULT_WALA_REPORT_FILENAME);
result.setProperty(WALA_REPORT, convertToAbsolute(walaReport));
return result;
} catch (Exception e) {
// e.printStackTrace();
throw new WalaException("Unable to set up wala properties ", e);
}
}
static String convertToAbsolute(String path) {
final File file = new File(path);
return file.isAbsolute()
? file.getAbsolutePath()
: WalaProperties.getWalaHomeDir().concat(File.separator).concat(path);
}
public static Properties loadPropertiesFromFile(ClassLoader loader, String fileName)
throws IOException {
if (loader == null) {
throw new IllegalArgumentException("loader is null");
}
if (fileName == null) {
throw new IllegalArgumentException("null fileName");
}
try (final InputStream propertyStream = loader.getResourceAsStream(fileName)) {
if (propertyStream == null) {
// create default properties
Properties defprop = new Properties();
defprop.setProperty(OUTPUT_DIR, "./out");
defprop.setProperty(INPUT_DIR, "./in");
defprop.setProperty(ECLIPSE_PLUGINS_DIR, "./plugins");
defprop.setProperty(WALA_REPORT, "./wala_report.txt");
defprop.setProperty(J2EE_DIR, "./j2ee");
return defprop;
}
Properties result = new Properties();
result.load(propertyStream);
return result;
}
}
/**
* @deprecated because when running under eclipse, there may be no such directory. Need to handle
* that case.
*/
@Deprecated
public static String getWalaHomeDir() {
final String envProperty = System.getProperty("WALA_HOME"); // $NON-NLS-1$
if (envProperty != null) return envProperty;
final URL url =
WalaProperties.class.getClassLoader().getResource("wala.properties"); // $NON-NLS-1$
if (url == null) {
return System.getProperty("user.dir"); // $NON-NLS-1$
} else {
return new File(new FileProvider().filePathFromURL(url))
.getParentFile()
.getParentFile()
.getPath();
}
}
}
| 6,860
| 33.134328
| 100
|
java
|
WALA
|
WALA-master/core/src/main/java/com/ibm/wala/ssa/AllIntegerDueToBranchePiPolicy.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.ssa;
import com.ibm.wala.util.collections.Pair;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
/**
* A policy, that adds pi nodes for all variables, that are used in a branch instruction.
*
* @author Stephan Gocht {@code <stephan@gobro.de>}
*/
public class AllIntegerDueToBranchePiPolicy implements SSAPiNodePolicy {
@Override
public Pair<Integer, SSAInstruction> getPi(
SSAAbstractInvokeInstruction call, SymbolTable symbolTable) {
return null;
}
@Override
public Pair<Integer, SSAInstruction> getPi(
SSAConditionalBranchInstruction cond,
SSAInstruction def1,
SSAInstruction def2,
SymbolTable symbolTable) {
final List<Pair<Integer, SSAInstruction>> pis = this.getPis(cond, def1, def2, symbolTable);
if (pis.size() == 0) {
return null;
} else if (pis.size() == 1) {
return pis.get(0);
} else {
throw new IllegalArgumentException(
"getPi was called but pi nodes should be inserted for more than one variable. Use getPis instead.");
}
}
@Override
public List<Pair<Integer, SSAInstruction>> getPis(
SSAConditionalBranchInstruction cond,
SSAInstruction def1,
SSAInstruction def2,
SymbolTable symbolTable) {
if (cond.isIntegerComparison()) {
final List<Pair<Integer, SSAInstruction>> result = new ArrayList<>();
for (int i = 0; i < cond.getNumberOfUses(); i++) {
result.add(Pair.make(cond.getUse(i), (SSAInstruction) cond));
}
return result;
} else {
return Collections.emptyList();
}
}
}
| 1,991
| 29.646154
| 110
|
java
|
WALA
|
WALA-master/core/src/main/java/com/ibm/wala/ssa/AuxiliaryCache.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.ssa;
import com.ibm.wala.classLoader.IMethod;
import com.ibm.wala.core.util.ref.CacheReference;
import com.ibm.wala.ipa.callgraph.Context;
import com.ibm.wala.util.collections.HashMapFactory;
import com.ibm.wala.util.collections.HashSetFactory;
import com.ibm.wala.util.collections.MapUtil;
import com.ibm.wala.util.collections.Pair;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Map.Entry;
/**
* A cache for auxiliary information based on an SSA representation
*
* <p>A mapping from (IMethod,Context) -> SSAOptions -> SoftReference -> something
*
* <p>This doesn't work very well ... GCs don't do such a great job with SoftReferences ... revamp
* it.
*/
public class AuxiliaryCache implements IAuxiliaryCache {
/** A mapping from IMethod -> SSAOptions -> SoftReference -> IR */
private HashMap<Pair<IMethod, Context>, Map<SSAOptions, Object>> dictionary =
HashMapFactory.make();
/**
* Help out the garbage collector: clear this cache when the number of items is >
* RESET_THRESHOLD
*/
private static final int RESET_THRESHOLD = 2000;
/** number of items cached here. */
private int nItems = 0;
@Override
public synchronized void wipe() {
dictionary = HashMapFactory.make();
nItems = 0;
}
/** clear out things from which no IR is reachable */
private void reset() {
Map<Pair<IMethod, Context>, Map<SSAOptions, Object>> oldDictionary = dictionary;
dictionary = HashMapFactory.make();
nItems = 0;
for (Entry<Pair<IMethod, Context>, Map<SSAOptions, Object>> e : oldDictionary.entrySet()) {
Map<SSAOptions, Object> m = e.getValue();
HashSet<Object> toRemove = HashSetFactory.make();
for (Entry<SSAOptions, Object> e2 : m.entrySet()) {
Object key = e2.getKey();
Object val = e2.getValue();
if (CacheReference.get(val) == null) {
toRemove.add(key);
}
}
for (Object object : toRemove) {
m.remove(object);
}
if (m.size() > 0) {
dictionary.put(e.getKey(), m);
}
}
}
@Override
public synchronized Object find(IMethod m, Context c, SSAOptions options) {
// methodMap: SSAOptions -> SoftReference
Pair<IMethod, Context> p = Pair.make(m, c);
Map<SSAOptions, Object> methodMap = MapUtil.findOrCreateMap(dictionary, p);
Object ref = methodMap.get(options);
if (ref == null || CacheReference.get(ref) == null) {
return null;
} else {
return CacheReference.get(ref);
}
}
@Override
public synchronized void cache(IMethod m, Context c, SSAOptions options, Object aux) {
nItems++;
if (nItems > RESET_THRESHOLD) {
reset();
}
Pair<IMethod, Context> p = Pair.make(m, c);
// methodMap: SSAOptions -> SoftReference
Map<SSAOptions, Object> methodMap = MapUtil.findOrCreateMap(dictionary, p);
Object ref = CacheReference.make(aux);
methodMap.put(options, ref);
}
@Override
public void invalidate(IMethod method, Context c) {
dictionary.remove(Pair.make(method, c));
}
}
| 3,497
| 30.513514
| 98
|
java
|
WALA
|
WALA-master/core/src/main/java/com/ibm/wala/ssa/CompoundPiPolicy.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.ssa;
import com.ibm.wala.util.collections.Pair;
import java.util.ArrayList;
import java.util.List;
/**
* A Combination of 2 {@link SSAPiNodePolicy}s. This policy will insert Pi nodes if either of two
* delegate policies says to.
*/
public class CompoundPiPolicy implements SSAPiNodePolicy {
/**
* @param p1 first {@link SSAPiNodePolicy} to delegate to
* @param p2 second {@link SSAPiNodePolicy} to delegate to
*/
public static CompoundPiPolicy createCompoundPiPolicy(SSAPiNodePolicy p1, SSAPiNodePolicy p2) {
return new CompoundPiPolicy(p1, p2);
}
private final SSAPiNodePolicy p1;
private final SSAPiNodePolicy p2;
/**
* @param p1 first {@link SSAPiNodePolicy} to delegate to
* @param p2 second {@link SSAPiNodePolicy} to delegate to
*/
private CompoundPiPolicy(SSAPiNodePolicy p1, SSAPiNodePolicy p2) {
this.p1 = p1;
this.p2 = p2;
if (p1 == null) {
throw new IllegalArgumentException("p1 is null");
}
if (p2 == null) {
throw new IllegalArgumentException("p2 is null");
}
}
@Override
public Pair<Integer, SSAInstruction> getPi(
SSAConditionalBranchInstruction cond,
SSAInstruction def1,
SSAInstruction def2,
SymbolTable symbolTable) {
Pair<Integer, SSAInstruction> result = p1.getPi(cond, def1, def2, symbolTable);
if (result != null) {
return result;
}
return p2.getPi(cond, def1, def2, symbolTable);
}
@Override
public Pair<Integer, SSAInstruction> getPi(
SSAAbstractInvokeInstruction call, SymbolTable symbolTable) {
Pair<Integer, SSAInstruction> result = p1.getPi(call, symbolTable);
if (result != null) {
return result;
}
return p2.getPi(call, symbolTable);
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((p1 == null) ? 0 : p1.hashCode());
result = prime * result + ((p2 == null) ? 0 : p2.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 CompoundPiPolicy other = (CompoundPiPolicy) obj;
if (p1 == null) {
if (other.p1 != null) return false;
} else if (!p1.equals(other.p1)) return false;
if (p2 == null) {
if (other.p2 != null) return false;
} else if (!p2.equals(other.p2)) return false;
return true;
}
@Override
public List<Pair<Integer, SSAInstruction>> getPis(
SSAConditionalBranchInstruction cond,
SSAInstruction def1,
SSAInstruction def2,
SymbolTable symbolTable) {
List<Pair<Integer, SSAInstruction>> result = new ArrayList<>();
result.addAll(p1.getPis(cond, def1, def2, symbolTable));
result.addAll(p2.getPis(cond, def1, def2, symbolTable));
return result;
}
}
| 3,259
| 29.185185
| 97
|
java
|
WALA
|
WALA-master/core/src/main/java/com/ibm/wala/ssa/ConstantValue.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.ssa;
/** The value of a constant which appears in an SSA IR. */
public class ConstantValue implements Value {
private final Object constant;
public ConstantValue(Object constant) {
this.constant = constant;
}
public ConstantValue(int constant) {
this(Integer.valueOf(constant));
}
public ConstantValue(double constant) {
this(Double.valueOf(constant));
}
/** @return an object which represents the constant value */
public Object getValue() {
return constant;
}
@Override
public String toString() {
return "#" + constant;
}
@Override
public boolean isStringConstant() {
return constant instanceof String;
}
/** @return true iff this constant is "false" */
public boolean isFalseConstant() {
return (constant instanceof Boolean) && constant.equals(Boolean.FALSE);
}
/** @return true iff this constant is "true" */
public boolean isTrueConstant() {
return (constant instanceof Boolean) && constant.equals(Boolean.TRUE);
}
/** @return true iff this constant is "zero" */
public boolean isZeroConstant() {
return ((constant instanceof Number) && (((Number) constant).intValue() == 0));
}
/** @return true iff this constant is "null" */
@Override
public boolean isNullConstant() {
return (constant == null);
}
/** @return true iff this constant is "one" */
public boolean isOneConstant() {
return ((constant instanceof Number) && (((Number) constant).intValue() == 1));
}
@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (obj.getClass().equals(getClass())) {
ConstantValue other = (ConstantValue) obj;
if (constant == null) {
return other.constant == null;
}
return constant.equals(other.constant);
} else {
return false;
}
}
@Override
public int hashCode() {
return constant == null ? 74 : 91 * constant.hashCode();
}
}
| 2,349
| 24.824176
| 83
|
java
|
WALA
|
WALA-master/core/src/main/java/com/ibm/wala/ssa/DefUse.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.ssa;
import com.ibm.wala.util.collections.EmptyIterator;
import com.ibm.wala.util.collections.Iterator2Iterable;
import com.ibm.wala.util.debug.Assertions;
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 java.util.ArrayList;
import java.util.Iterator;
/** An object which represent Def-Use information for an SSA {@link IR} */
public class DefUse {
static final boolean DEBUG = false;
/** A mapping from integer (value number) -> {@link SSAInstruction} that defines the value */
private final SSAInstruction[] defs;
/**
* A mapping from integer (value number) -> bit vector holding integers representing
* instructions that use the value number
*/
private final MutableIntSet[] uses;
/** A Mapping from integer -> Instruction */
protected final ArrayList<SSAInstruction> allInstructions = new ArrayList<>();
/** prevent the IR from being collected while this is live. */
private final IR ir;
/**
* @param ir an IR in SSA form.
* @throws IllegalArgumentException if ir is null
*/
public DefUse(final IR ir) {
if (ir == null) {
throw new IllegalArgumentException("ir is null");
}
this.ir = ir;
// set up mapping from integer -> instruction
initAllInstructions();
defs = new SSAInstruction[getMaxValueNumber() + 1];
uses = new MutableIntSet[getMaxValueNumber() + 1];
if (DEBUG) {
System.err.println(("DefUse: defs.length " + defs.length));
}
Iterator<SSAInstruction> it = allInstructions.iterator();
for (int i = 0; i < allInstructions.size(); i++) {
SSAInstruction s = it.next();
if (s == null) {
continue;
}
for (int j = 0; j < getNumberOfDefs(s); j++) {
defs[getDef(s, j)] = s;
}
for (int j = 0; j < getNumberOfUses(s); j++) {
int use = getUse(s, j);
try {
if (use != -1) {
if (uses[use] == null) {
uses[use] = IntSetUtil.make();
}
uses[use].add(i);
}
} catch (ArrayIndexOutOfBoundsException e) {
assert false : "unexpected value number " + use;
}
}
}
}
/** @return the maximum value number in a particular IR */
protected int getMaxValueNumber() {
return ir.getSymbolTable().getMaxValueNumber();
}
/** Initialize the allInstructions field with every {@link SSAInstruction} in the ir. */
protected void initAllInstructions() {
for (SSAInstruction inst : Iterator2Iterable.make(ir.iterateAllInstructions())) {
allInstructions.add(inst);
}
}
/** What is the ith value number defined by instruction s? */
protected int getDef(SSAInstruction s, int i) {
return s.getDef(i);
}
/** What is the ith value number used by instruction s? */
protected int getUse(SSAInstruction s, int i) {
return s.getUse(i);
}
/** How many value numbers does instruction s def? */
protected int getNumberOfDefs(SSAInstruction s) {
return s.getNumberOfDefs();
}
/** How many value numbers does instruction s use? */
protected int getNumberOfUses(SSAInstruction s) {
return s.getNumberOfUses();
}
/** @return the {@link SSAInstruction} that defines the variable with value number v. */
public SSAInstruction getDef(int v) {
return (v < defs.length) ? defs[v] : null;
}
/** Return all uses of the variable with the given value number */
public Iterator<SSAInstruction> getUses(int v) {
if (uses[v] == null) {
return EmptyIterator.instance();
} else {
return new UseIterator(uses[v]);
}
}
/** return an {@link Iterator} of all instructions that use any of a set of variables */
private class UseIterator implements Iterator<SSAInstruction> {
final IntIterator it;
/** @param uses the set of value numbers whose uses this object iterates over */
UseIterator(IntSet uses) {
it = uses.intIterator();
}
@Override
public boolean hasNext() {
return it.hasNext();
}
@Override
public SSAInstruction next() {
return allInstructions.get(it.next());
}
@Override
public void remove() {
Assertions.UNREACHABLE();
}
}
/**
* @param v a value number
* @return the number of uses of the variable with the given value number
*/
public int getNumberOfUses(int v) {
return uses[v] == null ? 0 : uses[v].size();
}
/**
* @param v a value number
* @return true if the variable with the given value number has no uses
*/
public boolean isUnused(int v) {
final MutableIntSet usesSet = uses[v];
assert usesSet == null || !usesSet.isEmpty();
return usesSet == null;
}
}
| 5,186
| 28.982659
| 98
|
java
|
WALA
|
WALA-master/core/src/main/java/com/ibm/wala/ssa/DefaultIRFactory.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.ssa;
import com.ibm.wala.cfg.ControlFlowGraph;
import com.ibm.wala.classLoader.IBytecodeMethod;
import com.ibm.wala.classLoader.IMethod;
import com.ibm.wala.classLoader.ShrikeCTMethod;
import com.ibm.wala.classLoader.ShrikeIRFactory;
import com.ibm.wala.classLoader.SyntheticMethod;
import com.ibm.wala.ipa.callgraph.Context;
import com.ibm.wala.ipa.summaries.SyntheticIRFactory;
import com.ibm.wala.shrike.shrikeBT.IInstruction;
import com.ibm.wala.util.debug.Assertions;
/**
* Default implementation of {@link IRFactory}.
*
* <p>This creates {@link IR} objects from Shrike methods, and directly from synthetic methods.
*/
public class DefaultIRFactory implements IRFactory<IMethod> {
private final ShrikeIRFactory shrikeFactory = new ShrikeIRFactory();
private final SyntheticIRFactory syntheticFactory = new SyntheticIRFactory();
public ControlFlowGraph<?, ?> makeCFG(IMethod method, @SuppressWarnings("unused") Context c)
throws IllegalArgumentException {
if (method == null) {
throw new IllegalArgumentException("method cannot be null");
}
if (method.isWalaSynthetic()) {
return syntheticFactory.makeCFG((SyntheticMethod) method);
} else if (method instanceof IBytecodeMethod) {
@SuppressWarnings("unchecked")
final IBytecodeMethod<IInstruction> castMethod = (IBytecodeMethod<IInstruction>) method;
return shrikeFactory.makeCFG(castMethod);
} else {
Assertions.UNREACHABLE();
return null;
}
}
@Override
public IR makeIR(IMethod method, Context c, SSAOptions options) throws IllegalArgumentException {
if (method == null) {
throw new IllegalArgumentException("method cannot be null");
}
if (method.isWalaSynthetic()) {
return syntheticFactory.makeIR((SyntheticMethod) method, c, options);
} else if (method instanceof IBytecodeMethod) {
@SuppressWarnings("unchecked")
final IBytecodeMethod<IInstruction> castMethod = (IBytecodeMethod<IInstruction>) method;
return shrikeFactory.makeIR(castMethod, c, options);
} else {
Assertions.UNREACHABLE();
return null;
}
}
/**
* Is the {@link Context} irrelevant as to structure of the {@link IR} for a particular {@link
* IMethod}?
*/
@Override
public boolean contextIsIrrelevant(IMethod method) {
if (method == null) {
throw new IllegalArgumentException("null method");
}
if (method.isWalaSynthetic()) {
return syntheticFactory.contextIsIrrelevant((SyntheticMethod) method);
} else if (method instanceof ShrikeCTMethod) {
// we know ShrikeFactory contextIsIrrelevant
return true;
} else {
// be conservative .. don't know what's going on.
return false;
}
}
}
| 3,140
| 34.292135
| 99
|
java
|
WALA
|
WALA-master/core/src/main/java/com/ibm/wala/ssa/IAuxiliaryCache.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.ssa;
import com.ibm.wala.classLoader.IMethod;
import com.ibm.wala.ipa.callgraph.Context;
interface IAuxiliaryCache {
/** The existence of this is unfortunate. */
void wipe();
/**
* @param m a method
* @param options options governing ssa construction
* @return the object cached for m, or null if none found
*/
Object find(IMethod m, Context c, SSAOptions options);
/**
* cache new auxiliary information for an <m,options> pair
*
* @param m a method
* @param options options governing ssa construction
*/
void cache(IMethod m, Context c, SSAOptions options, Object aux);
/** invalidate all cached information about a method */
void invalidate(IMethod method, Context c);
}
| 1,117
| 27.666667
| 72
|
java
|
WALA
|
WALA-master/core/src/main/java/com/ibm/wala/ssa/IR.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.ssa;
import com.ibm.wala.cfg.ControlFlowGraph;
import com.ibm.wala.classLoader.CallSiteReference;
import com.ibm.wala.classLoader.IMethod;
import com.ibm.wala.classLoader.NewSiteReference;
import com.ibm.wala.classLoader.ProgramCounter;
import com.ibm.wala.core.util.strings.StringStuff;
import com.ibm.wala.ssa.SSACFG.BasicBlock;
import com.ibm.wala.ssa.SSACFG.ExceptionHandlerBasicBlock;
import com.ibm.wala.types.TypeReference;
import com.ibm.wala.util.collections.CompoundIterator;
import com.ibm.wala.util.collections.HashMapFactory;
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.BasicNaturalRelation;
import com.ibm.wala.util.intset.IntIterator;
import com.ibm.wala.util.intset.IntSet;
import java.util.Collection;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
/**
* An SSA IR.
*
* <p>The IR (Intermediate Representation) is the central data structure that represents the
* instructions of a particular method. The IR represents a method's instructions in a language
* close to JVM bytecode, but in an SSA-based register transfer language which eliminates the stack
* abstraction, relying instead on a set of symbolic registers. The IR organizes instructions in a
* control-flow graph of basic blocks, as typical in compiler textbooks.
*
* <p>See <a href="http://wala.sourceforge.net/wiki/index.php/UserGuide:IR">more details on the IR
* API</a>.
*/
public abstract class IR implements IRView {
/** The method that defined this IR's bytecodes */
private final IMethod method;
/** Governing SSA construction options */
private final SSAOptions options;
/** Control-flow graph */
private final SSACFG cfg;
/** SSA instructions */
private final SSAInstruction[] instructions;
/** Symbol table */
private final SymbolTable symbolTable;
/** Mapping from CallSiteReference program counters to instruction[] indices */
private final BasicNaturalRelation callSiteMapping = new BasicNaturalRelation();
/** Mapping from NewSiteReference program counters to instruction[] indices */
private final Map<NewSiteReference, Integer> newSiteMapping = HashMapFactory.make();
/** Mapping from PEI program counters to instruction[] indices */
private final Map<ProgramCounter, Integer> peiMapping = HashMapFactory.make();
/** Mapping from SSAInstruction to Basic Block, computed lazily */
private Map<SSAInstruction, ISSABasicBlock> instruction2Block;
/** subclasses must provide a source name mapping, if they want one (or null otherwise) */
protected abstract SSA2LocalMap getLocalMap();
/**
* subclasses must provide information about indirect use of values, if appropriate, and otherwise
* null
*/
protected abstract <T extends SSAIndirectionData.Name> SSAIndirectionData<T> getIndirectionData();
/** Simple constructor when someone else has already computed the symbol table and cfg. */
protected IR(
IMethod method,
SSAInstruction[] instructions,
SymbolTable symbolTable,
SSACFG cfg,
SSAOptions options) {
if (method == null) {
throw new IllegalArgumentException("method is null");
}
this.method = method;
this.instructions = instructions;
this.symbolTable = symbolTable;
this.cfg = cfg;
this.options = options;
}
/** create mappings from call sites, new sites, and PEIs to instruction index */
protected void setupLocationMap() {
for (int i = 0; i < instructions.length; i++) {
SSAInstruction x = instructions[i];
if (x != null) {
if (x instanceof SSAAbstractInvokeInstruction) {
callSiteMapping.add(
((SSAAbstractInvokeInstruction) x).getCallSite().getProgramCounter(), i);
}
if (x instanceof SSANewInstruction) {
newSiteMapping.put(((SSANewInstruction) x).getNewSite(), i);
}
if (x.isPEI()) {
peiMapping.put(new ProgramCounter(cfg.getProgramCounter(i)), i);
}
}
}
}
/**
* @return a String which is a readable representation of the instruction position corresponding
* to an instruction index
*/
protected abstract String instructionPosition(int instructionIndex);
@Override
public String toString() {
Collection<? extends SSAIndirectionData.Name> names = null;
if (getIndirectionData() != null) {
names = getIndirectionData().getNames();
}
StringBuilder result = new StringBuilder(method.toString());
result.append("\nCFG:\n");
result.append(cfg.toString());
result.append("Instructions:\n");
for (int i = 0; i <= cfg.getMaxNumber(); i++) {
BasicBlock bb = cfg.getNode(i);
int start = bb.getFirstInstructionIndex();
int end = bb.getLastInstructionIndex();
result.append("BB").append(bb.getNumber());
if (bb instanceof ExceptionHandlerBasicBlock) {
result.append("<Handler> (");
Iterator<TypeReference> catchIter =
((ExceptionHandlerBasicBlock) bb).getCaughtExceptionTypes();
while (catchIter.hasNext()) {
TypeReference next = catchIter.next();
result.append(next);
if (catchIter.hasNext()) {
result.append(',');
}
}
result.append(')');
}
result.append('\n');
for (SSAPhiInstruction phi : Iterator2Iterable.make(bb.iteratePhis())) {
if (phi != null) {
result.append(" ").append(phi.toString(symbolTable)).append('\n');
}
}
if (bb instanceof ExceptionHandlerBasicBlock) {
ExceptionHandlerBasicBlock ebb = (ExceptionHandlerBasicBlock) bb;
SSAGetCaughtExceptionInstruction s = ebb.getCatchInstruction();
if (s != null) {
result.append(" ").append(s.toString(symbolTable)).append('\n');
} else {
result.append(" " + " No catch instruction. Unreachable?\n");
}
}
for (int j = start; j <= end; j++) {
if (instructions[j] != null) {
if (names != null) {
boolean any = false;
for (SSAIndirectionData.Name n : names) {
if (getIndirectionData().getUse(j, n) != -1) {
result
.append(' ')
.append(n)
.append(" -> ")
.append(getIndirectionData().getUse(j, n));
any = true;
}
}
if (any) {
result.append('\n');
}
}
StringBuilder x = new StringBuilder(j + " " + instructions[j].toString(symbolTable));
StringStuff.padWithSpaces(x, 45);
result.append(x);
result.append(instructionPosition(j));
Map<Integer, Set<String>> valNames = HashMapFactory.make();
for (int v = 0; v < instructions[j].getNumberOfDefs(); v++) {
int valNum = instructions[j].getDef(v);
addNames(j, valNames, valNum);
}
for (int v = 0; v < instructions[j].getNumberOfUses(); v++) {
int valNum = instructions[j].getUse(v);
addNames(j, valNames, valNum);
}
if (!valNames.isEmpty()) {
result.append(" [");
for (Map.Entry<Integer, Set<String>> e : valNames.entrySet()) {
result.append(e.getKey()).append('=').append(e.getValue());
}
result.append(']');
}
result.append('\n');
if (names != null) {
boolean any = false;
for (SSAIndirectionData.Name n : names) {
if (getIndirectionData().getDef(j, n) != -1) {
result
.append(' ')
.append(n)
.append(" <- ")
.append(getIndirectionData().getDef(j, n));
any = true;
}
}
if (any) {
result.append('\n');
}
}
}
}
for (SSAPiInstruction pi : Iterator2Iterable.make(bb.iteratePis())) {
if (pi != null) {
result.append(" ").append(pi.toString(symbolTable)).append('\n');
}
}
}
return result.toString();
}
private void addNames(int j, Map<Integer, Set<String>> valNames, int valNum) {
if (getLocalNames(j, valNum) != null && getLocalNames(j, valNum).length > 0) {
if (!valNames.containsKey(valNum)) {
valNames.put(valNum, HashSetFactory.<String>make());
}
for (String s : getLocalNames(j, valNum)) {
valNames.get(valNum).add(s);
}
}
}
/**
* Returns the normal instructions. Does not include {@link SSAPhiInstruction}, {@link
* SSAPiInstruction}, or {@link SSAGetCaughtExceptionInstruction}s, which are currently managed by
* {@link BasicBlock}. Entries in the returned array might be null.
*
* <p>This may go away someday.
*/
@Override
public SSAInstruction[] getInstructions() {
return instructions;
}
/** @return the {@link SymbolTable} managing attributes for values in this method */
@Override
public SymbolTable getSymbolTable() {
return symbolTable;
}
/** @return the underlying {@link ControlFlowGraph} which defines this IR. */
@Override
public SSACFG getControlFlowGraph() {
return cfg;
}
@Override
public Iterator<ISSABasicBlock> getBlocks() {
return getControlFlowGraph().iterator();
}
/** Return an {@link Iterator} of all {@link SSAPhiInstruction}s for this IR. */
public Iterator<? extends SSAInstruction> iteratePhis() {
return new TwoLevelIterator() {
@Override
Iterator<? extends SSAInstruction> getBlockIterator(BasicBlock b) {
return b.iteratePhis();
}
};
}
/** Return an {@link Iterator} of all {@link SSAPiInstruction}s for this IR. */
public Iterator<? extends SSAInstruction> iteratePis() {
return new TwoLevelIterator() {
@Override
Iterator<? extends SSAInstruction> getBlockIterator(BasicBlock b) {
return b.iteratePis();
}
};
}
/**
* An {@link Iterator} over all {@link SSAInstruction}s of a certain type, retrieved by iterating
* over the {@link BasicBlock}s, one at a time.
*
* <p>TODO: this looks buggy to me .. looks like it's hardcoded for Phis. Does it work for Pis?
*/
private abstract class TwoLevelIterator implements Iterator<SSAInstruction> {
// invariant: if currentBlockIndex != -1, then
// currentBlockIterator.hasNext()
private Iterator<? extends SSAInstruction> currentBlockIterator;
private int currentBlockIndex;
abstract Iterator<? extends SSAInstruction> getBlockIterator(BasicBlock b);
TwoLevelIterator() {
currentBlockIndex = 0;
currentBlockIterator = cfg.getNode(0).iteratePhis();
if (!currentBlockIterator.hasNext()) {
advanceBlock();
}
}
@Override
public boolean hasNext() {
return currentBlockIndex != -1;
}
@Override
public SSAInstruction next() {
SSAInstruction result = currentBlockIterator.next();
if (!currentBlockIterator.hasNext()) {
advanceBlock();
}
return result;
}
@Override
public void remove() {
Assertions.UNREACHABLE();
}
private void advanceBlock() {
for (int i = currentBlockIndex + 1; i <= cfg.getMaxNumber(); i++) {
Iterator<? extends SSAInstruction> it = getBlockIterator(cfg.getNode(i));
if (it.hasNext()) {
currentBlockIndex = i;
currentBlockIterator = it;
return;
}
}
currentBlockIterator = null;
currentBlockIndex = -1;
}
}
/** @return array of value numbers representing parameters to this method */
public int[] getParameterValueNumbers() {
return symbolTable.getParameterValueNumbers();
}
/** @return the value number of the ith parameter */
public int getParameter(int i) {
return symbolTable.getParameter(i);
}
/**
* Get the {@link TypeReference} that describes the ith parameter to this method. By convention,
* for a non-static method, the 0th parameter is "this".
*/
public TypeReference getParameterType(int i) {
return method.getParameterType(i);
}
/** @return number of parameters to this method, including "this" */
public int getNumberOfParameters() {
return method.getNumberOfParameters();
}
/** @return the method this IR represents */
@Override
public IMethod getMethod() {
return method;
}
/** @return iterator of the catch instructions in this IR */
public Iterator<SSAInstruction> iterateCatchInstructions() {
return new CatchIterator();
}
/** TODO: looks like this should be merged into {@link TwoLevelIterator}, above? */
private class CatchIterator implements Iterator<SSAInstruction> {
// invariant: if currentBlockIndex != -1, then
// then block[currentBlockIndex] is a handler block
private int currentBlockIndex;
private boolean hasCatch(Object x) {
return (x instanceof ExceptionHandlerBasicBlock)
&& (((ExceptionHandlerBasicBlock) x).getCatchInstruction() != null);
}
CatchIterator() {
currentBlockIndex = 0;
if (!hasCatch(cfg.getNode(0))) {
advanceBlock();
}
}
@Override
public boolean hasNext() {
return currentBlockIndex != -1;
}
@Override
public SSAInstruction next() {
ExceptionHandlerBasicBlock bb = (ExceptionHandlerBasicBlock) cfg.getNode(currentBlockIndex);
SSAInstruction result = bb.getCatchInstruction();
advanceBlock();
return result;
}
@Override
public void remove() {
Assertions.UNREACHABLE();
}
private void advanceBlock() {
for (int i = currentBlockIndex + 1; i < cfg.getMaxNumber(); i++) {
if (hasCatch(cfg.getNode(i))) {
currentBlockIndex = i;
return;
}
}
currentBlockIndex = -1;
}
}
/** visit each normal (non-phi, non-pi, non-catch) instruction in this IR */
public void visitNormalInstructions(SSAInstruction.IVisitor v) {
for (SSAInstruction inst : Iterator2Iterable.make(iterateNormalInstructions())) {
inst.visit(v);
}
}
/** visit each instruction in this IR */
public void visitAllInstructions(SSAInstruction.IVisitor v) {
for (SSAInstruction inst : Iterator2Iterable.make(iterateAllInstructions())) {
inst.visit(v);
}
}
/** @return an {@link Iterator} of all "normal" instructions on this IR */
public Iterator<SSAInstruction> iterateNormalInstructions() {
return new NormalIterator();
}
private class NormalIterator implements Iterator<SSAInstruction> {
int nextIndex = -1;
final SSAInstruction[] instructions = getInstructions();
NormalIterator() {
advanceIndex(0);
}
private void advanceIndex(int start) {
for (int i = start; i < instructions.length; i++) {
if (instructions[i] != null) {
nextIndex = i;
return;
}
}
nextIndex = -1;
}
@Override
public boolean hasNext() {
return nextIndex != -1;
}
@Override
public void remove() {
Assertions.UNREACHABLE();
}
@Override
public SSAInstruction next() {
SSAInstruction result = instructions[nextIndex];
advanceIndex(nextIndex + 1);
return result;
}
}
/** @return an {@link Iterator} of all instructions (Normal, Phi, and Catch) */
public Iterator<SSAInstruction> iterateAllInstructions() {
return new CompoundIterator<>(
iterateNormalInstructions(),
new CompoundIterator<>(
iterateCatchInstructions(), new CompoundIterator<>(iteratePhis(), iteratePis())));
}
/** @return the exit basic block */
@Override
public BasicBlock getExitBlock() {
return cfg.exit();
}
/**
* Return the invoke instructions corresponding to a call site
*
* <p>Note that Shrike may inline JSRS. This can lead to multiple copies of a single bytecode
* instruction in a particular IR. So we may have more than one instruction index for a particular
* call site from bytecode.
*/
public SSAAbstractInvokeInstruction[] getCalls(CallSiteReference site) {
if (site == null) {
throw new IllegalArgumentException("site is null");
}
IntSet s = callSiteMapping.getRelated(site.getProgramCounter());
if (s == null) {
throw new IllegalArgumentException("no calls at site's pc");
}
SSAAbstractInvokeInstruction[] result = new SSAAbstractInvokeInstruction[s.size()];
int index = 0;
for (IntIterator it = s.intIterator(); it.hasNext(); ) {
int i = it.next();
result[index++] = (SSAAbstractInvokeInstruction) instructions[i];
}
return result;
}
/**
* Return the instruction indices corresponding to a call site.
*
* <p>Note that Shrike may inline JSRS. This can lead to multiple copies of a single bytecode
* instruction in a particular IR. So we may have more than one instruction index for a particular
* call site from bytecode.
*/
public IntSet getCallInstructionIndices(CallSiteReference site) {
if (site == null) {
throw new IllegalArgumentException("site is null");
}
return callSiteMapping.getRelated(site.getProgramCounter());
}
/** Return the new instruction corresponding to an allocation site */
public SSANewInstruction getNew(NewSiteReference site) {
Integer i = newSiteMapping.get(site);
return (SSANewInstruction) instructions[i];
}
/** Return the instruction index corresponding to an allocation site */
public int getNewInstructionIndex(NewSiteReference site) {
Integer i = newSiteMapping.get(site);
return i;
}
/**
* @param pc a program counter
* @return the instruction (a PEI) at this program counter
*/
@Override
public SSAInstruction getPEI(ProgramCounter pc) {
Integer i = peiMapping.get(pc);
return instructions[i];
}
/**
* @return an {@link Iterator} of all the allocation sites ( {@link NewSiteReference}s ) in this
* IR
*/
@Override
public Iterator<NewSiteReference> iterateNewSites() {
return newSiteMapping.keySet().iterator();
}
/** @return an {@link Iterator} of all the call sites ( {@link CallSiteReference}s ) in this IR */
@Override
public Iterator<CallSiteReference> iterateCallSites() {
return new Iterator<>() {
private final int limit = callSiteMapping.maxKeyValue();
private int i = -1;
{
advance();
}
private void advance() {
while (callSiteMapping.getRelatedCount(++i) == 0 && i <= limit) ;
}
@Override
public boolean hasNext() {
return i <= limit;
}
@Override
public CallSiteReference next() {
int index = callSiteMapping.getRelated(i).max();
advance();
return ((SSAAbstractInvokeInstruction) instructions[index]).getCallSite();
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
};
}
/**
* @param site a call site in this method
* @return the basic block corresponding to this instruction
* @throws IllegalArgumentException if site is null
*/
@Override
public ISSABasicBlock[] getBasicBlocksForCall(final CallSiteReference site) {
if (site == null) {
throw new IllegalArgumentException("site is null");
}
final IntSet s = callSiteMapping.getRelated(site.getProgramCounter());
if (s == null) {
throw new IllegalArgumentException("invalid site: " + site);
}
final ISSABasicBlock[] result = new ISSABasicBlock[s.size()];
int index = 0;
for (final IntIterator it = s.intIterator(); it.hasNext(); ) {
final int i = it.next();
result[index++] = getControlFlowGraph().getBlockForInstruction(i);
}
return result;
}
/**
* This is space-inefficient. Use with care.
*
* <p>Be very careful; note the strange identity semantics of SSAInstruction, using ==. You can't
* mix SSAInstructions and IRs freely.
*/
public ISSABasicBlock getBasicBlockForInstruction(SSAInstruction s) {
if (instruction2Block == null) {
mapInstructions2Blocks();
}
return instruction2Block.get(s);
}
private void mapInstructions2Blocks() {
instruction2Block = HashMapFactory.make();
for (ISSABasicBlock b : cfg) {
for (SSAInstruction s : b) {
instruction2Block.put(s, b);
}
}
}
/**
* TODO: why do we need this? We should enforce instructions == null if necessary, I think.
*
* @return true iff every instruction is null
*/
public boolean isEmptyIR() {
if (instructions == null) return true;
for (SSAInstruction instruction : instructions) if (instruction != null) return false;
return true;
}
/**
* @param index an index into the IR instruction array
* @param vn a value number
* @return if we know that immediately after the given program counter, v_vn corresponds to one or
* more locals and local variable names are available, the name of the locals which v_vn
* represents. Otherwise, null.
*/
@Override
public String[] getLocalNames(int index, int vn) {
if (getLocalMap() == null) {
return new String[0];
} else {
return getLocalMap().getLocalNames(index, vn);
}
}
/**
* A Map that gives the names of the local variables corresponding to SSA value numbers at
* particular IR instruction indices, if such information is available from source code mapping.
*/
public interface SSA2LocalMap {
/**
* @param index an index into the IR instruction array
* @param vn a value number
* @return if we know that immediately after the given program counter, v_vn corresponds to one
* or more locals and local variable names are available, the name of the locals which v_vn
* represents. Otherwise, null.
*/
String[] getLocalNames(int index, int vn);
}
/** Return the {@link ISSABasicBlock} corresponding to a particular catch instruction */
public ISSABasicBlock getBasicBlockForCatch(SSAGetCaughtExceptionInstruction instruction) {
if (instruction == null) {
throw new IllegalArgumentException("instruction is null");
}
int bb = instruction.getBasicBlockNumber();
return cfg.getBasicBlock(bb);
}
/** @return the {@link SSAOptions} which controlled how this {@code IR} was built */
public SSAOptions getOptions() {
return options;
}
}
| 23,103
| 31.358543
| 100
|
java
|
WALA
|
WALA-master/core/src/main/java/com/ibm/wala/ssa/IRFactory.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.ssa;
import com.ibm.wala.classLoader.IMethod;
import com.ibm.wala.ipa.callgraph.CGNode;
import com.ibm.wala.ipa.callgraph.Context;
/**
* This is intended as an internal interface; clients probably shouldn't be using this directly.
*
* <p>If you have a call graph in hand, to get the {@link IR} for a {@link CGNode}, use
* node.getIR();
*
* <p>Otherwise, look at {@link SSACache}.
*/
public interface IRFactory<T extends IMethod> {
/** Build an SSA {@link IR} for a method in a particular context */
IR makeIR(T method, Context c, SSAOptions options);
/** Does this factory always return the same IR for a method, regardless of context? */
boolean contextIsIrrelevant(T method);
}
| 1,095
| 32.212121
| 96
|
java
|
WALA
|
WALA-master/core/src/main/java/com/ibm/wala/ssa/IRView.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.ssa;
import com.ibm.wala.cfg.ControlFlowGraph;
import com.ibm.wala.classLoader.CallSiteReference;
import com.ibm.wala.classLoader.IMethod;
import com.ibm.wala.classLoader.NewSiteReference;
import com.ibm.wala.classLoader.ProgramCounter;
import java.util.Iterator;
public interface IRView {
SymbolTable getSymbolTable();
ControlFlowGraph<SSAInstruction, ISSABasicBlock> getControlFlowGraph();
ISSABasicBlock[] getBasicBlocksForCall(CallSiteReference callSite);
SSAInstruction[] getInstructions();
SSAInstruction getPEI(ProgramCounter peiLoc);
IMethod getMethod();
ISSABasicBlock getExitBlock();
Iterator<NewSiteReference> iterateNewSites();
Iterator<CallSiteReference> iterateCallSites();
Iterator<ISSABasicBlock> getBlocks();
String[] getLocalNames(int i, int v);
}
| 1,190
| 26.068182
| 73
|
java
|
WALA
|
WALA-master/core/src/main/java/com/ibm/wala/ssa/ISSABasicBlock.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.ssa;
import com.ibm.wala.cfg.ControlFlowGraph;
import com.ibm.wala.cfg.IBasicBlock;
import com.ibm.wala.types.TypeReference;
import java.util.Iterator;
/** Common interface to all SSA BasicBlocks */
public interface ISSABasicBlock extends IBasicBlock<SSAInstruction> {
/** Is this block a catch block */
@Override
boolean isCatchBlock();
/** Does this block represent the unique exit from a {@link ControlFlowGraph}? */
@Override
boolean isExitBlock();
/** Does this block represent the unique entry to a {@link ControlFlowGraph} */
@Override
boolean isEntryBlock();
/** @return the phi instructions incoming to this block */
Iterator<SSAPhiInstruction> iteratePhis();
/** @return the pi instructions incoming to this block */
Iterator<SSAPiInstruction> iteratePis();
/** @return the last instruction in this block. */
SSAInstruction getLastInstruction();
/** @return the set of exception types this block may catch. */
Iterator<TypeReference> getCaughtExceptionTypes();
}
| 1,412
| 30.4
| 83
|
java
|
WALA
|
WALA-master/core/src/main/java/com/ibm/wala/ssa/IVisitorWithAddresses.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.ssa;
import com.ibm.wala.ssa.SSAInstruction.IVisitor;
/**
* @author omert
* <p>Temporary interface to accomodate the newly added {@link SSAAddressOfInstruction}
* instruction. Ultimately, this interface should be merged into {@link IVisitor}.
* <p>TODO: Add 'visitAddressOf' to {@link IVisitor}.
*/
public interface IVisitorWithAddresses extends IVisitor {
void visitAddressOf(SSAAddressOfInstruction instruction);
void visitLoadIndirect(SSALoadIndirectInstruction instruction);
void visitStoreIndirect(SSAStoreIndirectInstruction instruction);
}
| 964
| 32.275862
| 91
|
java
|
WALA
|
WALA-master/core/src/main/java/com/ibm/wala/ssa/InstanceOfPiPolicy.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.ssa;
import com.ibm.wala.util.collections.Pair;
import java.util.Collections;
import java.util.List;
/**
* A pi node policy with the following rule:
*
* <p>If we have the following code:
*
* <pre> S1: c = v1 instanceof T S2: if (c == 0) { ... } </pre>
*
* replace it with:
*
* <pre> S1: c = v1 instanceof T S2: if (c == 0) { v2 = PI(v1, S1) .... } </pre>
*
* The same pattern holds if the test is c == 1. This renaming allows SSA-based analysis to reason
* about the type of v2 depending on the outcome of the branch.
*/
public class InstanceOfPiPolicy implements SSAPiNodePolicy {
private static final InstanceOfPiPolicy singleton = new InstanceOfPiPolicy();
public static InstanceOfPiPolicy createInstanceOfPiPolicy() {
return singleton;
}
private InstanceOfPiPolicy() {}
@Override
public Pair<Integer, SSAInstruction> getPi(
SSAConditionalBranchInstruction cond,
SSAInstruction def1,
SSAInstruction def2,
SymbolTable symbolTable) {
if (def1 instanceof SSAInstanceofInstruction) {
if (symbolTable.isBooleanOrZeroOneConstant(cond.getUse(1))) {
return Pair.make(def1.getUse(0), def1);
}
}
if (def2 instanceof SSAInstanceofInstruction) {
if (symbolTable.isBooleanOrZeroOneConstant(cond.getUse(0))) {
return Pair.make(def2.getUse(0), def2);
}
}
return null;
}
@Override
public boolean equals(Object obj) {
return this == obj;
}
@Override
public int hashCode() {
return 12;
}
@Override
public Pair<Integer, SSAInstruction> getPi(
SSAAbstractInvokeInstruction call, SymbolTable symbolTable) {
return null;
}
@Override
public List<Pair<Integer, SSAInstruction>> getPis(
SSAConditionalBranchInstruction cond,
SSAInstruction def1,
SSAInstruction def2,
SymbolTable symbolTable) {
return Collections.singletonList(getPi(cond, def1, def2, symbolTable));
}
}
| 2,332
| 26.447059
| 98
|
java
|
WALA
|
WALA-master/core/src/main/java/com/ibm/wala/ssa/NullTestPiPolicy.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.ssa;
import com.ibm.wala.util.collections.Pair;
import java.util.Collections;
import java.util.List;
/**
* A pi node policy with the following rule:
*
* <p>If we have the following code:
*
* <pre> S1: if (c op null) { ... } </pre>
*
* replace it with:
*
* <pre> S1: if (c op null) { v2 = PI(c, S1) .... } </pre>
*
* This renaming allows SSA-based analysis to reason about the nullness of v2 depending on the
* outcome of the branch.
*/
public class NullTestPiPolicy implements SSAPiNodePolicy {
private static final NullTestPiPolicy singleton = new NullTestPiPolicy();
public static NullTestPiPolicy createNullTestPiPolicy() {
return singleton;
}
private NullTestPiPolicy() {}
@Override
public Pair<Integer, SSAInstruction> getPi(
SSAConditionalBranchInstruction cond,
SSAInstruction def1,
SSAInstruction def2,
SymbolTable symbolTable) {
if (symbolTable == null) {
throw new IllegalArgumentException("null symbolTable");
}
if (cond == null) {
throw new IllegalArgumentException("null cond");
}
if (symbolTable.isNullConstant(cond.getUse(1))) {
return Pair.<Integer, SSAInstruction>make(cond.getUse(0), cond);
}
if (symbolTable.isNullConstant(cond.getUse(0))) {
return Pair.<Integer, SSAInstruction>make(cond.getUse(1), cond);
}
return null;
}
@Override
public Pair<Integer, SSAInstruction> getPi(
SSAAbstractInvokeInstruction call, SymbolTable symbolTable) {
return null;
}
@Override
public List<Pair<Integer, SSAInstruction>> getPis(
SSAConditionalBranchInstruction cond,
SSAInstruction def1,
SSAInstruction def2,
SymbolTable symbolTable) {
return Collections.singletonList(getPi(cond, def1, def2, symbolTable));
}
}
| 2,180
| 27.324675
| 94
|
java
|
WALA
|
WALA-master/core/src/main/java/com/ibm/wala/ssa/PhiValue.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.ssa;
/**
* A value generated by a phi instruction.
*
* <p>Clients shouldn't use this ... it's only used internally during SSA construction.
*/
public class PhiValue implements Value {
/** The phi instruction that defines this value */
private final SSAPhiInstruction phi;
/** @param phi The phi instruction that defines this value */
PhiValue(SSAPhiInstruction phi) {
this.phi = phi;
}
@Override
public String toString() {
return "v" + phi.getDef();
}
/** @return The phi instruction that defines this value */
public SSAPhiInstruction getPhiInstruction() {
return phi;
}
@Override
public boolean isStringConstant() {
return false;
}
@Override
public boolean isNullConstant() {
return false;
}
}
| 1,156
| 23.617021
| 87
|
java
|
WALA
|
WALA-master/core/src/main/java/com/ibm/wala/ssa/ReflectiveMemberAccess.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.ssa;
/** TODO: document me. */
public abstract class ReflectiveMemberAccess extends SSAInstruction {
protected final int objectRef;
protected final int memberRef;
protected ReflectiveMemberAccess(int iindex, int objectRef, int memberRef) {
super(iindex);
this.objectRef = objectRef;
this.memberRef = memberRef;
}
@Override
public String toString(SymbolTable symbolTable) {
return "fieldref "
+ getValueString(symbolTable, objectRef)
+ '.'
+ getValueString(symbolTable, memberRef);
}
@Override
public int getUse(int j) {
assert j <= 1;
return (j == 0) ? objectRef : memberRef;
}
public int getObjectRef() {
return objectRef;
}
public int getMemberRef() {
return memberRef;
}
@Override
public int hashCode() {
return 6311 * memberRef ^ 2371 * objectRef;
}
@Override
public boolean isFallThrough() {
return true;
}
}
| 1,323
| 22.22807
| 78
|
java
|
WALA
|
WALA-master/core/src/main/java/com/ibm/wala/ssa/SSAAbstractBinaryInstruction.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.ssa;
public abstract class SSAAbstractBinaryInstruction extends SSAInstruction {
protected final int result;
protected final int val1;
protected final int val2;
public SSAAbstractBinaryInstruction(int iindex, int result, int val1, int val2) {
super(iindex);
this.result = result;
assert val1 != -1;
this.val1 = val1;
assert val2 != -1;
this.val2 = val2;
}
@Override
public boolean hasDef() {
return true;
}
@Override
public int getDef() {
return result;
}
@Override
public int getDef(int i) {
assert i == 0;
return result;
}
/** @see com.ibm.wala.ssa.SSAInstruction#getNumberOfUses() */
@Override
public int getNumberOfDefs() {
return 1;
}
@Override
public int getNumberOfUses() {
return 2;
}
@Override
public int getUse(int j) {
assert j <= 1;
return (j == 0) ? val1 : val2;
}
@Override
public int hashCode() {
return 6311 * result ^ 2371 * val1 + val2;
}
}
| 1,372
| 19.80303
| 83
|
java
|
WALA
|
WALA-master/core/src/main/java/com/ibm/wala/ssa/SSAAbstractInvokeInstruction.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.ssa;
import com.ibm.wala.classLoader.CallSiteReference;
import com.ibm.wala.shrike.shrikeBT.IInvokeInstruction;
import com.ibm.wala.types.MethodReference;
import com.ibm.wala.types.TypeReference;
/**
* A Call instruction.
*
* <p>Note that different languages have different notions of what a call is. This is an abstract
* superclass which encapsulates the common functionality that all languages share, so far.
*/
public abstract class SSAAbstractInvokeInstruction extends SSAInstruction {
/** The value number which represents the exception object which the call may throw. */
protected final int exception;
/** The call site, containing the program counter location and the method being called. */
protected final CallSiteReference site;
/**
* @param exception The value number which represents the exception object which the call may
* throw.
* @param site The call site, containing the program counter location and the method being called.
*/
protected SSAAbstractInvokeInstruction(int iindex, int exception, CallSiteReference site) {
super(iindex);
this.exception = exception;
this.site = site;
}
/** @return The call site, containing the program counter location and the method being called. */
public CallSiteReference getCallSite() {
return site;
}
/** Is this a 'static' call? (invokestatic in Java) */
public boolean isStatic() {
return getCallSite().isStatic();
}
/**
* Might this call dispatch to one of several possible methods? i.e., in Java, is it an
* invokeinterface or invokevirtual
*/
public boolean isDispatch() {
return getCallSite().isDispatch();
}
/** Is this a 'special' call? (invokespecial in Java) */
public boolean isSpecial() {
return getCallSite().isSpecial();
}
/** @return the value number of the receiver of a virtual call */
public int getReceiver() {
assert site.getInvocationCode() != IInvokeInstruction.Dispatch.STATIC : toString();
return getUse(0);
}
/** @return the program counter (index into the method's bytecode) for this call site. */
public int getProgramCounter() {
return site.getProgramCounter();
}
@Override
public int getNumberOfDefs() {
return getNumberOfReturnValues() + 1;
}
@Override
public int getDef(int i) {
if (getNumberOfReturnValues() == 0) {
assert i == 0;
return exception;
} else {
switch (i) {
case 0:
return getReturnValue(0);
case 1:
return exception;
default:
return getReturnValue(i - 1);
}
}
}
/**
* Return the value number which is def'fed by this call instruction if the call returns
* exceptionally.
*/
public int getException() {
return exception;
}
@Override
public boolean hasDef() {
return getNumberOfReturnValues() > 0;
}
@Override
public int getDef() {
return getReturnValue(0);
}
/** How many parameters does this call specify? */
public abstract int getNumberOfPositionalParameters();
/** How many distinct values does this call return? */
public abstract int getNumberOfReturnValues();
/** What is the the value number of the ith value returned by this call */
public abstract int getReturnValue(int i);
/** What is the declared return type of the called method */
public TypeReference getDeclaredResultType() {
return site.getDeclaredTarget().getReturnType();
}
/** What method is the declared callee? */
public MethodReference getDeclaredTarget() {
return site.getDeclaredTarget();
}
/** @see com.ibm.wala.classLoader.CallSiteReference#getInvocationCode() */
public IInvokeInstruction.IDispatch getInvocationCode() {
return site.getInvocationCode();
}
@Override
public boolean isPEI() {
return true;
}
@Override
public boolean isFallThrough() {
return true;
}
@Override
public String toString(SymbolTable symbolTable) {
String code = site.getInvocationString();
StringBuilder s = new StringBuilder();
if (hasDef()) {
s.append(getValueString(symbolTable, getDef())).append(" = ");
}
s.append("invoke").append(code);
s.append(' ');
s.append(site.getDeclaredTarget().toString());
if (getNumberOfPositionalParameters() > 0) {
s.append(' ').append(getValueString(symbolTable, getUse(0)));
for (int i = 1; i < getNumberOfPositionalParameters(); i++) {
s.append(',').append(getValueString(symbolTable, getUse(i)));
}
}
s.append(" @");
s.append(site.getProgramCounter());
if (exception == -1) {
s.append(" exception: NOT MODELED");
} else {
s.append(" exception:").append(getValueString(symbolTable, exception));
}
return s.toString();
}
}
| 5,179
| 27.618785
| 100
|
java
|
WALA
|
WALA-master/core/src/main/java/com/ibm/wala/ssa/SSAAbstractThrowInstruction.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.ssa;
/** An instruction which unconditionally throws an exception */
public abstract class SSAAbstractThrowInstruction extends SSAInstruction {
private final int exception;
public SSAAbstractThrowInstruction(int iindex, int exception) {
super(iindex);
assert exception > 0;
this.exception = exception;
}
@Override
public String toString(SymbolTable symbolTable) {
return "throw " + getValueString(symbolTable, exception);
}
@Override
public int getNumberOfUses() {
return 1;
}
@Override
public int getUse(int j) {
if (j != 0) {
throw new IllegalArgumentException("j must be 0");
}
return exception;
}
@Override
public int hashCode() {
return 7529 + exception * 823;
}
@Override
public boolean isPEI() {
return true;
}
@Override
public boolean isFallThrough() {
return false;
}
/** @return value number of the thrown exception object. */
public int getException() {
return exception;
}
}
| 1,395
| 21.516129
| 74
|
java
|
WALA
|
WALA-master/core/src/main/java/com/ibm/wala/ssa/SSAAbstractUnaryInstruction.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.ssa;
/** */
public abstract class SSAAbstractUnaryInstruction extends SSAInstruction {
protected final int result;
protected final int val;
protected SSAAbstractUnaryInstruction(int iindex, int result, int val) {
super(iindex);
this.result = result;
this.val = val;
}
/** @see com.ibm.wala.ssa.SSAInstruction#getDef() */
@Override
public boolean hasDef() {
return true;
}
@Override
public int getDef() {
return result;
}
@Override
public int getDef(int i) {
assert i == 0;
return result;
}
/** @see com.ibm.wala.ssa.SSAInstruction#getNumberOfUses() */
@Override
public int getNumberOfDefs() {
return 1;
}
@Override
public int getNumberOfUses() {
return 1;
}
@Override
public int getUse(int j) {
assert j == 0;
return val;
}
@Override
public int hashCode() {
return val * 1663 ^ result * 4027;
}
@Override
public boolean isFallThrough() {
return true;
}
}
| 1,376
| 18.394366
| 74
|
java
|
WALA
|
WALA-master/core/src/main/java/com/ibm/wala/ssa/SSAAddressOfInstruction.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.ssa;
import com.ibm.wala.ssa.SSAIndirectionData.Name;
import com.ibm.wala.types.FieldReference;
import com.ibm.wala.types.TypeReference;
import com.ibm.wala.util.debug.Assertions;
/**
* An {@link SSAAddressOfInstruction} represents storing the address of some "source" level entity
* (@see {@link Name}) into an SSA value number.
*/
public class SSAAddressOfInstruction extends SSAInstruction {
/**
* The value number which is def'ed ... this instruction assigns this value to hold an address.
*/
private final int lval;
/**
* The SSA value number that represents the entity whose address is being taken.
*
* <p>If we're taking the address of a local variable, this is the value number representing that
* local variable immediately before this instruction.
*
* <p>If we're taking the address of an array element or a field of an object, then this is the
* base pointer.
*/
private final int addressVal;
/**
* If we're taking the address of an array element, this is the array index. Otherwise, this is
* -1.
*/
private final int indexVal;
/**
* If we're taking the address of a field, this is the field reference. Otherwise, this is null.
*/
private final FieldReference field;
private final TypeReference pointeeType;
/** Use this constructor when taking the address of a local variable. */
public SSAAddressOfInstruction(int iindex, int lval, int local, TypeReference pointeeType) {
super(iindex);
if (local <= 0) {
throw new IllegalArgumentException("Invalid local address load of " + local);
}
this.lval = lval;
this.addressVal = local;
this.indexVal = -1;
this.field = null;
this.pointeeType = pointeeType;
}
/** Use this constructor when taking the address of an array element. */
public SSAAddressOfInstruction(
int iindex, int lval, int basePointer, int indexVal, TypeReference pointeeType) {
super(iindex);
this.lval = lval;
this.addressVal = basePointer;
this.indexVal = indexVal;
this.field = null;
this.pointeeType = pointeeType;
}
/** Use this constructor when taking the address of a field in an object. */
public SSAAddressOfInstruction(
int iindex, int lval, int basePointer, FieldReference field, TypeReference pointeeType) {
super(iindex);
this.lval = lval;
this.addressVal = basePointer;
this.indexVal = -1;
this.field = field;
this.pointeeType = pointeeType;
}
public TypeReference getType() {
return pointeeType;
}
@Override
public SSAInstruction copyForSSA(SSAInstructionFactory insts, int[] defs, int[] uses) {
Assertions.UNREACHABLE("not yet implemented. to be nuked");
return null;
}
@Override
public int hashCode() {
return lval * 99701 + addressVal;
}
@Override
public boolean isFallThrough() {
return true;
}
@Override
public String toString(SymbolTable symbolTable) {
return getValueString(symbolTable, lval)
+ " ("
+ pointeeType.getName()
+ ") "
+ " = &"
+ getValueString(symbolTable, addressVal)
+ ((indexVal != -1)
? '[' + getValueString(symbolTable, indexVal) + ']'
: (field != null) ? '.' + field.getName().toString() : "");
}
@Override
public void visit(IVisitor v) {
assert (v instanceof IVisitorWithAddresses) : "expected an instance of IVisitorWithAddresses";
((IVisitorWithAddresses) v).visitAddressOf(this);
}
@Override
public int getNumberOfDefs() {
return 1;
}
@Override
public int getDef(int i) {
assert i == 0;
return lval;
}
@Override
public int getDef() {
return lval;
}
@Override
public int getNumberOfUses() {
return (indexVal == -1) ? 1 : 2;
}
@Override
public int getUse(int i) {
assert i == 0 || (i == 1 && indexVal != -1);
if (i == 0) {
return addressVal;
} else {
return indexVal;
}
}
}
| 4,350
| 26.537975
| 99
|
java
|
WALA
|
WALA-master/core/src/main/java/com/ibm/wala/ssa/SSAArrayLengthInstruction.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.ssa;
/** SSA instruction representing v_x := arraylength v_y */
public abstract class SSAArrayLengthInstruction extends SSAInstruction {
private final int result;
private final int arrayref;
protected SSAArrayLengthInstruction(int iindex, int result, int arrayref) {
super(iindex);
this.result = result;
this.arrayref = arrayref;
}
@Override
public SSAInstruction copyForSSA(SSAInstructionFactory insts, int[] defs, int[] uses)
throws IllegalArgumentException {
if (defs != null && defs.length != 1) {
throw new IllegalArgumentException();
}
if (uses != null && uses.length != 1) {
throw new IllegalArgumentException();
}
return insts.ArrayLengthInstruction(
iIndex(), defs == null ? result : defs[0], uses == null ? arrayref : uses[0]);
}
@Override
public String toString(SymbolTable symbolTable) {
return getValueString(symbolTable, result)
+ " = arraylength "
+ getValueString(symbolTable, arrayref);
}
@Override
public void visit(IVisitor v) throws NullPointerException {
v.visitArrayLength(this);
}
@Override
public int getDef() {
return result;
}
@Override
public boolean hasDef() {
return true;
}
@Override
public int getDef(int i) {
if (i != 0) {
throw new IllegalArgumentException("invalid i " + i);
}
return result;
}
@Override
public int getNumberOfDefs() {
return 1;
}
public int getArrayRef() {
return arrayref;
}
@Override
public int getNumberOfUses() {
return 1;
}
@Override
public int getUse(int j) {
if (j != 0) {
throw new IllegalArgumentException("invalid j: " + j);
}
return arrayref;
}
@Override
public int hashCode() {
return arrayref * 7573 + result * 563;
}
@Override
public boolean isPEI() {
return true;
}
@Override
public boolean isFallThrough() {
return true;
}
}
| 2,338
| 21.27619
| 87
|
java
|
WALA
|
WALA-master/core/src/main/java/com/ibm/wala/ssa/SSAArrayLoadInstruction.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.ssa;
import com.ibm.wala.types.TypeReference;
/** SSA instruction representing an array load. */
public abstract class SSAArrayLoadInstruction extends SSAArrayReferenceInstruction {
private final int result;
protected SSAArrayLoadInstruction(
int iindex, int result, int arrayref, int index, TypeReference elementType) {
super(iindex, arrayref, index, elementType);
this.result = result;
}
@Override
public SSAInstruction copyForSSA(SSAInstructionFactory insts, int[] defs, int[] uses)
throws IllegalArgumentException {
if (defs != null && defs.length == 0) {
throw new IllegalArgumentException("defs.length == 0");
}
if (uses != null && uses.length < 2) {
throw new IllegalArgumentException("uses.length < 2");
}
return insts.ArrayLoadInstruction(
iIndex(),
defs == null ? result : defs[0],
uses == null ? getArrayRef() : uses[0],
uses == null ? getIndex() : uses[1],
getElementType());
}
@Override
public String toString(SymbolTable symbolTable) {
return getValueString(symbolTable, result)
+ " = arrayload "
+ getValueString(symbolTable, getArrayRef())
+ '['
+ getValueString(symbolTable, getIndex())
+ ']';
}
/**
* @see com.ibm.wala.ssa.SSAInstruction#visit(IVisitor)
* @throws IllegalArgumentException if v is null
*/
@Override
public void visit(IVisitor v) {
if (v == null) {
throw new IllegalArgumentException("v is null");
}
v.visitArrayLoad(this);
}
/** @see com.ibm.wala.ssa.SSAInstruction#getDef() */
@Override
public boolean hasDef() {
return true;
}
@Override
public int getDef() {
return result;
}
@Override
public int getDef(int i) {
if (i != 0) {
throw new IllegalArgumentException("illegal i: " + i);
}
return result;
}
@Override
public int getNumberOfDefs() {
return 1;
}
@Override
public int hashCode() {
return 6311 * result ^ 2371 * getArrayRef() + getIndex();
}
}
| 2,448
| 25.333333
| 87
|
java
|
WALA
|
WALA-master/core/src/main/java/com/ibm/wala/ssa/SSAArrayReferenceInstruction.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.ssa;
import com.ibm.wala.types.TypeReference;
/** Abstract base class for instructions that load or store from array contents. */
public abstract class SSAArrayReferenceInstruction extends SSAInstruction {
private final int arrayref;
private final int index;
private final TypeReference elementType;
SSAArrayReferenceInstruction(int iindex, int arrayref, int index, TypeReference elementType) {
super(iindex);
this.arrayref = arrayref;
this.index = index;
this.elementType = elementType;
if (elementType == null) {
throw new IllegalArgumentException("null elementType");
}
}
@Override
public int getNumberOfUses() {
return 2;
}
@Override
public int getUse(int j) {
assert j <= 1;
return (j == 0) ? arrayref : index;
}
/** Return the value number of the array reference. */
public int getArrayRef() {
return arrayref;
}
/** Return the value number of the index of the array reference. */
public int getIndex() {
return index;
}
public TypeReference getElementType() {
return elementType;
}
/** @return true iff this represents an array access of a primitive type element */
public boolean typeIsPrimitive() {
return elementType.isPrimitiveType();
}
@Override
public boolean isPEI() {
return true;
}
@Override
public boolean isFallThrough() {
return true;
}
}
| 1,790
| 23.202703
| 96
|
java
|
WALA
|
WALA-master/core/src/main/java/com/ibm/wala/ssa/SSAArrayStoreInstruction.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.ssa;
import com.ibm.wala.types.TypeReference;
/** SSA instruction representing an array store. */
public abstract class SSAArrayStoreInstruction extends SSAArrayReferenceInstruction {
private final int value;
protected SSAArrayStoreInstruction(
int iindex, int arrayref, int index, int value, TypeReference elementType) {
super(iindex, arrayref, index, elementType);
this.value = value;
}
@Override
public SSAInstruction copyForSSA(SSAInstructionFactory insts, int[] defs, int[] uses) {
if (uses != null && uses.length < 3) {
throw new IllegalArgumentException("uses.length < 3");
}
return insts.ArrayStoreInstruction(
iIndex(),
uses == null ? getArrayRef() : uses[0],
uses == null ? getIndex() : uses[1],
uses == null ? value : uses[2],
getElementType());
}
@Override
public String toString(SymbolTable symbolTable) {
return "arraystore "
+ getValueString(symbolTable, getArrayRef())
+ '['
+ getValueString(symbolTable, getIndex())
+ "] = "
+ getValueString(symbolTable, value);
}
/**
* @see com.ibm.wala.ssa.SSAInstruction#visit(IVisitor)
* @throws IllegalArgumentException if v is null
*/
@Override
public void visit(IVisitor v) {
if (v == null) {
throw new IllegalArgumentException("v is null");
}
v.visitArrayStore(this);
}
/** @see com.ibm.wala.ssa.SSAInstruction#getNumberOfUses() */
@Override
public int getNumberOfUses() {
return 3;
}
@Override
public int getNumberOfDefs() {
return 0;
}
public int getValue() {
return value;
}
/** @see com.ibm.wala.ssa.SSAInstruction#getUse(int) */
@Override
public int getUse(int j) {
if (j == 2) return value;
else return super.getUse(j);
}
@Override
public int hashCode() {
return 6311 * value ^ 2371 * getArrayRef() + getIndex();
}
}
| 2,315
| 25.318182
| 89
|
java
|
WALA
|
WALA-master/core/src/main/java/com/ibm/wala/ssa/SSABinaryOpInstruction.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.ssa;
import com.ibm.wala.shrike.shrikeBT.BinaryOpInstruction;
import com.ibm.wala.shrike.shrikeBT.IBinaryOpInstruction;
public abstract class SSABinaryOpInstruction extends SSAAbstractBinaryInstruction {
private final IBinaryOpInstruction.IOperator operator;
/** Might this instruction represent integer arithmetic? */
private final boolean mayBeInteger;
protected SSABinaryOpInstruction(
int iindex,
IBinaryOpInstruction.IOperator operator,
int result,
int val1,
int val2,
boolean mayBeInteger) {
super(iindex, result, val1, val2);
this.operator = operator;
this.mayBeInteger = mayBeInteger;
if (val1 <= 0) {
throw new IllegalArgumentException("illegal val1: " + val1);
}
if (val2 <= 0) {
throw new IllegalArgumentException("illegal val2: " + val2);
}
}
@Override
public String toString(SymbolTable symbolTable) {
return getValueString(symbolTable, result)
+ " = binaryop("
+ operator
+ ") "
+ getValueString(symbolTable, val1)
+ " , "
+ getValueString(symbolTable, val2);
}
/** @see com.ibm.wala.ssa.SSAInstruction#visit(IVisitor) */
@Override
public void visit(IVisitor v) throws NullPointerException {
v.visitBinaryOp(this);
}
/** Ugh. clean up shrike operator stuff. */
public IBinaryOpInstruction.IOperator getOperator() {
return operator;
}
/** @see com.ibm.wala.ssa.SSAInstruction#isPEI() */
@Override
public boolean isPEI() {
return mayBeInteger
&& (operator == BinaryOpInstruction.Operator.DIV
|| operator == BinaryOpInstruction.Operator.REM);
}
/** @see com.ibm.wala.ssa.SSAInstruction#isFallThrough() */
@Override
public boolean isFallThrough() {
return true;
}
public boolean mayBeIntegerOp() {
return mayBeInteger;
}
}
| 2,258
| 26.888889
| 83
|
java
|
WALA
|
WALA-master/core/src/main/java/com/ibm/wala/ssa/SSABuilder.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.ssa;
import com.ibm.wala.analysis.stackMachine.AbstractIntStackMachine;
import com.ibm.wala.cfg.IBasicBlock;
import com.ibm.wala.cfg.ShrikeCFG;
import com.ibm.wala.cfg.ShrikeCFG.BasicBlock;
import com.ibm.wala.classLoader.BytecodeLanguage;
import com.ibm.wala.classLoader.CallSiteReference;
import com.ibm.wala.classLoader.IBytecodeMethod;
import com.ibm.wala.classLoader.Language;
import com.ibm.wala.classLoader.NewSiteReference;
import com.ibm.wala.core.util.shrike.ShrikeUtil;
import com.ibm.wala.shrike.shrikeBT.ArrayLengthInstruction;
import com.ibm.wala.shrike.shrikeBT.ConstantInstruction;
import com.ibm.wala.shrike.shrikeBT.GotoInstruction;
import com.ibm.wala.shrike.shrikeBT.IArrayLoadInstruction;
import com.ibm.wala.shrike.shrikeBT.IArrayStoreInstruction;
import com.ibm.wala.shrike.shrikeBT.IBinaryOpInstruction;
import com.ibm.wala.shrike.shrikeBT.IComparisonInstruction;
import com.ibm.wala.shrike.shrikeBT.IConditionalBranchInstruction;
import com.ibm.wala.shrike.shrikeBT.IConversionInstruction;
import com.ibm.wala.shrike.shrikeBT.IGetInstruction;
import com.ibm.wala.shrike.shrikeBT.IInstanceofInstruction;
import com.ibm.wala.shrike.shrikeBT.IInvokeInstruction;
import com.ibm.wala.shrike.shrikeBT.ILoadIndirectInstruction;
import com.ibm.wala.shrike.shrikeBT.ILoadInstruction;
import com.ibm.wala.shrike.shrikeBT.IPutInstruction;
import com.ibm.wala.shrike.shrikeBT.IShiftInstruction;
import com.ibm.wala.shrike.shrikeBT.IStoreIndirectInstruction;
import com.ibm.wala.shrike.shrikeBT.IStoreInstruction;
import com.ibm.wala.shrike.shrikeBT.ITypeTestInstruction;
import com.ibm.wala.shrike.shrikeBT.IUnaryOpInstruction;
import com.ibm.wala.shrike.shrikeBT.IndirectionData;
import com.ibm.wala.shrike.shrikeBT.InvokeDynamicInstruction;
import com.ibm.wala.shrike.shrikeBT.MonitorInstruction;
import com.ibm.wala.shrike.shrikeBT.NewInstruction;
import com.ibm.wala.shrike.shrikeBT.ReturnInstruction;
import com.ibm.wala.shrike.shrikeBT.SwitchInstruction;
import com.ibm.wala.shrike.shrikeBT.ThrowInstruction;
import com.ibm.wala.shrike.shrikeCT.BootstrapMethodsReader.BootstrapMethod;
import com.ibm.wala.shrike.shrikeCT.InvalidClassFileException;
import com.ibm.wala.ssa.ShrikeIndirectionData.ShrikeLocalName;
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.collections.Pair;
import com.ibm.wala.util.debug.Assertions;
import com.ibm.wala.util.graph.dominators.Dominators;
import com.ibm.wala.util.intset.IntPair;
import java.util.Arrays;
/**
* This class constructs an SSA {@link IR} from a backing ShrikeBT instruction stream.
*
* <p>The basic algorithm here is an abstract interpretation over the Java bytecode to determine
* types of stack locations and local variables. As a side effect, the flow functions of the
* abstract interpretation emit instructions, eliminating the stack abstraction and moving to a
* register-transfer language in SSA form.
*/
public class SSABuilder extends AbstractIntStackMachine {
public static SSABuilder make(
IBytecodeMethod<?> method,
SSACFG cfg,
ShrikeCFG scfg,
SSAInstruction[] instructions,
SymbolTable symbolTable,
boolean buildLocalMap,
SSAPiNodePolicy piNodePolicy)
throws IllegalArgumentException {
if (scfg == null) {
throw new IllegalArgumentException("scfg == null");
}
return new SSABuilder(
method, cfg, scfg, instructions, symbolTable, buildLocalMap, piNodePolicy);
}
/** A wrapper around the method being analyzed. */
private final IBytecodeMethod<?> method;
/** Governing symbol table */
private final SymbolTable symbolTable;
/**
* A logical mapping from <bcIndex, valueNumber> -> local number if null, don't build it.
*/
private final SSA2LocalMap localMap;
/** a factory to create concrete instructions */
private final SSAInstructionFactory insts;
/** information about indirect use of local variables in the bytecode */
private final IndirectionData bytecodeIndirections;
private final ShrikeIndirectionData ssaIndirections;
private SSABuilder(
IBytecodeMethod<?> method,
SSACFG cfg,
ShrikeCFG scfg,
SSAInstruction[] instructions,
SymbolTable symbolTable,
boolean buildLocalMap,
SSAPiNodePolicy piNodePolicy) {
super(scfg);
localMap =
buildLocalMap ? new SSA2LocalMap(scfg, instructions.length, cfg.getNumberOfNodes()) : null;
init(
new SymbolTableMeeter(symbolTable, cfg, scfg),
new SymbolicPropagator(scfg, instructions, symbolTable, localMap, cfg, piNodePolicy));
this.method = method;
this.symbolTable = symbolTable;
this.insts = method.getDeclaringClass().getClassLoader().getInstructionFactory();
this.bytecodeIndirections = method.getIndirectionData();
this.ssaIndirections = new ShrikeIndirectionData(instructions.length);
assert cfg != null : "Null CFG";
}
private class SymbolTableMeeter implements Meeter {
final SSACFG cfg;
final SymbolTable symbolTable;
final ShrikeCFG shrikeCFG;
SymbolTableMeeter(SymbolTable symbolTable, SSACFG cfg, ShrikeCFG shrikeCFG) {
this.cfg = cfg;
this.symbolTable = symbolTable;
this.shrikeCFG = shrikeCFG;
}
@Override
public int meetStack(int slot, int[] rhs, BasicBlock bb) {
assert bb != null : "null basic block";
if (bb.isExitBlock()) {
return TOP;
}
if (allTheSame(rhs)) {
for (int rh : rhs) {
if (rh != TOP) {
return rh;
}
}
// didn't find anything but TOP
return TOP;
} else {
SSACFG.BasicBlock newBB = cfg.getNode(shrikeCFG.getNumber(bb));
// if we already have a phi for this stack location
SSAPhiInstruction phi = newBB.getPhiForStackSlot(slot);
int result;
if (phi == null) {
// no phi already exists. create one.
result = symbolTable.newPhi(rhs);
PhiValue v = symbolTable.getPhiValue(result);
phi = v.getPhiInstruction();
newBB.addPhiForStackSlot(slot, phi);
} else {
// already created a phi. update it to account for the
// new merge.
result = phi.getDef();
phi.setValues(rhs.clone());
}
return result;
}
}
@Override
public int meetLocal(int n, int[] rhs, BasicBlock bb) {
if (allTheSame(rhs)) {
for (int rh : rhs) {
if (rh != TOP) {
return rh;
}
}
// didn't find anything but TOP
return TOP;
} else {
SSACFG.BasicBlock newBB = cfg.getNode(shrikeCFG.getNumber(bb));
if (bb.isExitBlock()) {
// no phis in exit block please
return TOP;
}
// if we already have a phi for this local
SSAPhiInstruction phi = newBB.getPhiForLocal(n);
int result;
if (phi == null) {
// no phi already exists. create one.
result = symbolTable.newPhi(rhs);
PhiValue v = symbolTable.getPhiValue(result);
phi = v.getPhiInstruction();
newBB.addPhiForLocal(n, phi);
} else {
// already created a phi. update it to account for the
// new merge.
result = phi.getDef();
phi.setValues(rhs.clone());
}
return result;
}
}
/**
* Are all rhs values all the same? Note, we consider TOP (-1) to be same as everything else.
*
* @return boolean
*/
private boolean allTheSame(int[] rhs) {
int x = -1;
// set x := the first non-TOP value
int i = 0;
for (i = 0; i < rhs.length; i++) {
if (rhs[i] != TOP) {
x = rhs[i];
break;
}
}
// check the remaining values
for (i++; i < rhs.length; i++) {
if (rhs[i] != x && rhs[i] != TOP) return false;
}
return true;
}
@Override
public int meetStackAtCatchBlock(BasicBlock bb) {
int bbNumber = shrikeCFG.getNumber(bb);
SSACFG.ExceptionHandlerBasicBlock newBB =
(SSACFG.ExceptionHandlerBasicBlock) cfg.getNode(bbNumber);
SSAGetCaughtExceptionInstruction s = newBB.getCatchInstruction();
int exceptionValue;
if (s == null) {
exceptionValue = symbolTable.newSymbol();
s = insts.GetCaughtExceptionInstruction(SSAInstruction.NO_INDEX, bbNumber, exceptionValue);
newBB.setCatchInstruction(s);
} else {
exceptionValue = s.getException();
}
return exceptionValue;
}
}
@Override
protected void initializeVariables() {
MachineState entryState = getEntryState();
int parameterNumber = 0;
int local = -1;
for (int i = 0; i < method.getNumberOfParameters(); i++) {
local++;
TypeReference t = method.getParameterType(i);
if (t != null) {
int symbol = symbolTable.getParameter(parameterNumber++);
entryState.setLocal(local, symbol);
if (t.equals(TypeReference.Double) || t.equals(TypeReference.Long)) {
local++;
}
}
}
// This useless value ensures that the state cannot be empty, even
// for a static method with no arguments in blocks with an empty stack
// and no locals being used. This ensures that propagation of the
// state thru the CFGSystem will always show changes the first time
// it reaches a block, and thus no piece of the CFG will be skipped.
//
// (note that this bizarre state really happened, in java_cup)
//
entryState.push(symbolTable.newSymbol());
}
/**
* This class defines the type abstractions for this analysis and the flow function for each
* instruction in the ShrikeBT IR.
*/
private class SymbolicPropagator extends BasicStackFlowProvider {
final SSAInstruction[] instructions;
final SymbolTable symbolTable;
final ShrikeCFG shrikeCFG;
final SSACFG cfg;
final ClassLoaderReference loader;
/** creators[i] holds the instruction that defs value number i */
private SSAInstruction[] creators;
final SSA2LocalMap localMap;
final SSAPiNodePolicy piNodePolicy;
public SymbolicPropagator(
ShrikeCFG shrikeCFG,
SSAInstruction[] instructions,
SymbolTable symbolTable,
SSA2LocalMap localMap,
SSACFG cfg,
SSAPiNodePolicy piNodePolicy) {
super(shrikeCFG);
this.piNodePolicy = piNodePolicy;
this.cfg = cfg;
this.creators = new SSAInstruction[0];
this.shrikeCFG = shrikeCFG;
this.instructions = instructions;
this.symbolTable = symbolTable;
this.loader = shrikeCFG.getMethod().getDeclaringClass().getClassLoader().getReference();
this.localMap = localMap;
init(this.new NodeVisitor(), this.new EdgeVisitor());
}
@Override
public boolean needsEdgeFlow() {
return piNodePolicy != null;
}
private void emitInstruction(SSAInstruction s) {
if (s != null) {
instructions[getCurrentInstructionIndex()] = s;
for (int i = 0; i < s.getNumberOfDefs(); i++) {
if (creators.length < (s.getDef(i) + 1)) {
creators = Arrays.copyOf(creators, 2 * s.getDef(i));
}
assert s.getDef(i) != -1 : "invalid def " + i + " for " + s;
creators[s.getDef(i)] = s;
}
}
}
private SSAInstruction getCurrentInstruction() {
return instructions[getCurrentInstructionIndex()];
}
/**
* If we've already created the current instruction, return the value number def'ed by the
* current instruction. Else, create a new symbol.
*/
private int reuseOrCreateDef() {
if (getCurrentInstruction() == null) {
return symbolTable.newSymbol();
} else {
return getCurrentInstruction().getDef();
}
}
/**
* If we've already created the current instruction, return the value number representing the
* exception the instruction may throw. Else, create a new symbol
*/
private int reuseOrCreateException() {
if (getCurrentInstruction() != null) {
assert getCurrentInstruction() instanceof SSAInvokeInstruction;
}
if (getCurrentInstruction() == null) {
return symbolTable.newSymbol();
} else {
SSAInvokeInstruction s = (SSAInvokeInstruction) getCurrentInstruction();
return s.getException();
}
}
/** Update the machine state to account for an instruction */
class NodeVisitor extends BasicStackMachineVisitor {
/**
* @see
* com.ibm.wala.shrike.shrikeBT.IInstruction.Visitor#visitArrayLength(ArrayLengthInstruction)
*/
@Override
public void visitArrayLength(
com.ibm.wala.shrike.shrikeBT.ArrayLengthInstruction instruction) {
int arrayRef = workingState.pop();
int length = reuseOrCreateDef();
workingState.push(length);
emitInstruction(
insts.ArrayLengthInstruction(getCurrentInstructionIndex(), length, arrayRef));
}
/**
* @see
* com.ibm.wala.shrike.shrikeBT.IInstruction.Visitor#visitArrayLoad(IArrayLoadInstruction)
*/
@Override
public void visitArrayLoad(IArrayLoadInstruction instruction) {
int index = workingState.pop();
int arrayRef = workingState.pop();
int result = reuseOrCreateDef();
workingState.push(result);
TypeReference t = ShrikeUtil.makeTypeReference(loader, instruction.getType());
if (instruction.isAddressOf()) {
emitInstruction(
insts.AddressOfInstruction(getCurrentInstructionIndex(), result, arrayRef, index, t));
} else {
emitInstruction(
insts.ArrayLoadInstruction(getCurrentInstructionIndex(), result, arrayRef, index, t));
}
}
/**
* @see
* com.ibm.wala.shrike.shrikeBT.IInstruction.Visitor#visitArrayStore(IArrayStoreInstruction)
*/
@Override
public void visitArrayStore(IArrayStoreInstruction instruction) {
int value = workingState.pop();
int index = workingState.pop();
int arrayRef = workingState.pop();
TypeReference t = ShrikeUtil.makeTypeReference(loader, instruction.getType());
emitInstruction(
insts.ArrayStoreInstruction(getCurrentInstructionIndex(), arrayRef, index, value, t));
}
/**
* @see com.ibm.wala.shrike.shrikeBT.IInstruction.Visitor#visitBinaryOp(IBinaryOpInstruction)
*/
@Override
public void visitBinaryOp(IBinaryOpInstruction instruction) {
int val2 = workingState.pop();
int val1 = workingState.pop();
int result = reuseOrCreateDef();
workingState.push(result);
boolean isFloat =
instruction.getType().equals(TYPE_double) || instruction.getType().equals(TYPE_float);
emitInstruction(
insts.BinaryOpInstruction(
getCurrentInstructionIndex(),
instruction.getOperator(),
instruction.throwsExceptionOnOverflow(),
instruction.isUnsigned(),
result,
val1,
val2,
!isFloat));
}
/**
* @see com.ibm.wala.shrike.shrikeBT.IInstruction.Visitor#visitCheckCast(ITypeTestInstruction)
*/
@Override
public void visitCheckCast(ITypeTestInstruction instruction) {
int val = workingState.pop();
int result = reuseOrCreateDef();
workingState.push(result);
if (!instruction.firstClassTypes()) {
String[] typeNames = instruction.getTypes();
TypeReference[] t = new TypeReference[typeNames.length];
for (int i = 0; i < typeNames.length; i++) {
t[i] = ShrikeUtil.makeTypeReference(loader, typeNames[i]);
}
emitInstruction(
insts.CheckCastInstruction(
getCurrentInstructionIndex(), result, val, t, instruction.isPEI()));
}
}
/**
* @see
* com.ibm.wala.shrike.shrikeBT.IInstruction.Visitor#visitComparison(IComparisonInstruction)
*/
@Override
public void visitComparison(IComparisonInstruction instruction) {
int val2 = workingState.pop();
int val1 = workingState.pop();
int result = reuseOrCreateDef();
workingState.push(result);
emitInstruction(
insts.ComparisonInstruction(
getCurrentInstructionIndex(), instruction.getOperator(), result, val1, val2));
}
@Override
public void visitConditionalBranch(IConditionalBranchInstruction instruction) {
int val2 = workingState.pop();
int val1 = workingState.pop();
TypeReference t = ShrikeUtil.makeTypeReference(loader, instruction.getType());
emitInstruction(
insts.ConditionalBranchInstruction(
getCurrentInstructionIndex(),
instruction.getOperator(),
t,
val1,
val2,
instruction.getTarget()));
}
/**
* @see com.ibm.wala.shrike.shrikeBT.IInstruction.Visitor#visitConstant(ConstantInstruction)
*/
@Override
public void visitConstant(com.ibm.wala.shrike.shrikeBT.ConstantInstruction instruction) {
Language l = cfg.getMethod().getDeclaringClass().getClassLoader().getLanguage();
TypeReference type = l.getConstantType(instruction.getValue());
int symbol = 0;
if (l.isNullType(type)) {
symbol = symbolTable.getNullConstant();
} else if (l.isIntType(type)) {
Integer value = (Integer) instruction.getValue();
symbol = symbolTable.getConstant(value);
} else if (l.isLongType(type)) {
Long value = (Long) instruction.getValue();
symbol = symbolTable.getConstant(value);
} else if (l.isFloatType(type)) {
Float value = (Float) instruction.getValue();
symbol = symbolTable.getConstant(value);
} else if (l.isDoubleType(type)) {
Double value = (Double) instruction.getValue();
symbol = symbolTable.getConstant(value);
} else if (l.isStringType(type)) {
String value = (String) instruction.getValue();
symbol = symbolTable.getConstant(value);
} else if (l.isMetadataType(type)) {
Object rval = l.getMetadataToken(instruction.getValue());
symbol = reuseOrCreateDef();
emitInstruction(
insts.LoadMetadataInstruction(getCurrentInstructionIndex(), symbol, type, rval));
} else {
Assertions.UNREACHABLE("unexpected " + type);
}
workingState.push(symbol);
}
/**
* @see
* com.ibm.wala.shrike.shrikeBT.IInstruction.Visitor#visitConversion(IConversionInstruction)
*/
@Override
public void visitConversion(IConversionInstruction instruction) {
int val = workingState.pop();
int result = reuseOrCreateDef();
workingState.push(result);
TypeReference fromType = ShrikeUtil.makeTypeReference(loader, instruction.getFromType());
TypeReference toType = ShrikeUtil.makeTypeReference(loader, instruction.getToType());
emitInstruction(
insts.ConversionInstruction(
getCurrentInstructionIndex(),
result,
val,
fromType,
toType,
instruction.throwsExceptionOnOverflow()));
}
/** @see com.ibm.wala.shrike.shrikeBT.IInstruction.Visitor#visitGet(IGetInstruction) */
@Override
public void visitGet(IGetInstruction instruction) {
int result = reuseOrCreateDef();
FieldReference f =
FieldReference.findOrCreate(
loader,
instruction.getClassType(),
instruction.getFieldName(),
instruction.getFieldType());
if (instruction.isAddressOf()) {
int ref = instruction.isStatic() ? -1 : workingState.pop();
emitInstruction(
insts.AddressOfInstruction(
getCurrentInstructionIndex(), result, ref, f, f.getFieldType()));
} else if (instruction.isStatic()) {
emitInstruction(insts.GetInstruction(getCurrentInstructionIndex(), result, f));
} else {
int ref = workingState.pop();
emitInstruction(insts.GetInstruction(getCurrentInstructionIndex(), result, ref, f));
}
assert result != -1;
workingState.push(result);
}
/** @see com.ibm.wala.shrike.shrikeBT.IInstruction.Visitor#visitGoto(GotoInstruction) */
@Override
public void visitGoto(com.ibm.wala.shrike.shrikeBT.GotoInstruction instruction) {
emitInstruction(
insts.GotoInstruction(getCurrentInstructionIndex(), instruction.getLabel()));
}
/**
* @see
* com.ibm.wala.shrike.shrikeBT.IInstruction.Visitor#visitInstanceof(IInstanceofInstruction)
*/
@Override
public void visitInstanceof(IInstanceofInstruction instruction) {
int ref = workingState.pop();
int result = reuseOrCreateDef();
workingState.push(result);
TypeReference t = ShrikeUtil.makeTypeReference(loader, instruction.getType());
emitInstruction(insts.InstanceofInstruction(getCurrentInstructionIndex(), result, ref, t));
}
/** @see com.ibm.wala.shrike.shrikeBT.IInstruction.Visitor#visitInvoke(IInvokeInstruction) */
@Override
public void visitInvoke(IInvokeInstruction instruction) {
doIndirectReads(bytecodeIndirections.indirectlyReadLocals(getCurrentInstructionIndex()));
int n = instruction.getPoppedCount();
int[] params = new int[n];
for (int i = n - 1; i >= 0; i--) {
params[i] = workingState.pop();
}
Language lang = shrikeCFG.getMethod().getDeclaringClass().getClassLoader().getLanguage();
MethodReference m = ((BytecodeLanguage) lang).getInvokeMethodReference(loader, instruction);
IInvokeInstruction.IDispatch code = instruction.getInvocationCode();
CallSiteReference site = CallSiteReference.make(getCurrentProgramCounter(), m, code);
int exc = reuseOrCreateException();
BootstrapMethod bootstrap = null;
if (instruction instanceof InvokeDynamicInstruction) {
bootstrap = ((InvokeDynamicInstruction) instruction).getBootstrap();
}
if (instruction.getPushedWordSize() > 0) {
int result = reuseOrCreateDef();
workingState.push(result);
emitInstruction(
insts.InvokeInstruction(
getCurrentInstructionIndex(), result, params, exc, site, bootstrap));
} else {
emitInstruction(
insts.InvokeInstruction(getCurrentInstructionIndex(), params, exc, site, bootstrap));
}
doIndirectWrites(
bytecodeIndirections.indirectlyWrittenLocals(getCurrentInstructionIndex()), -1);
}
@Override
public void visitLocalLoad(ILoadInstruction instruction) {
if (instruction.isAddressOf()) {
int result = reuseOrCreateDef();
int t = workingState.getLocal(instruction.getVarIndex());
if (t == -1) {
doIndirectWrites(new int[] {instruction.getVarIndex()}, -1);
t = workingState.getLocal(instruction.getVarIndex());
}
TypeReference type = ShrikeUtil.makeTypeReference(loader, instruction.getType());
emitInstruction(
insts.AddressOfInstruction(getCurrentInstructionIndex(), result, t, type));
workingState.push(result);
} else {
super.visitLocalLoad(instruction);
}
}
/**
* @see com.ibm.wala.shrike.shrikeBT.IInstruction.Visitor#visitLocalStore(IStoreInstruction)
*/
@Override
public void visitLocalStore(IStoreInstruction instruction) {
if (localMap != null) {
localMap.startRange(
getCurrentInstructionIndex(), instruction.getVarIndex(), workingState.peek());
}
super.visitLocalStore(instruction);
}
/** @see com.ibm.wala.shrike.shrikeBT.IInstruction.Visitor#visitMonitor(MonitorInstruction) */
@Override
public void visitMonitor(com.ibm.wala.shrike.shrikeBT.MonitorInstruction instruction) {
int ref = workingState.pop();
emitInstruction(
insts.MonitorInstruction(getCurrentInstructionIndex(), ref, instruction.isEnter()));
}
/** @see com.ibm.wala.shrike.shrikeBT.IInstruction.Visitor#visitNew(NewInstruction) */
@Override
public void visitNew(com.ibm.wala.shrike.shrikeBT.NewInstruction instruction) {
int result = reuseOrCreateDef();
TypeReference t = ShrikeUtil.makeTypeReference(loader, instruction.getType());
NewSiteReference ref = NewSiteReference.make(getCurrentProgramCounter(), t);
if (t.isArrayType()) {
int[] sizes = new int[instruction.getArrayBoundsCount()];
for (int i = 0; i < instruction.getArrayBoundsCount(); i++) {
sizes[instruction.getArrayBoundsCount() - 1 - i] = workingState.pop();
}
emitInstruction(insts.NewInstruction(getCurrentInstructionIndex(), result, ref, sizes));
} else {
emitInstruction(insts.NewInstruction(getCurrentInstructionIndex(), result, ref));
popN(instruction);
}
workingState.push(result);
}
/** @see com.ibm.wala.shrike.shrikeBT.IInstruction.Visitor#visitGet(IGetInstruction) */
@Override
public void visitPut(IPutInstruction instruction) {
int value = workingState.pop();
if (instruction.isStatic()) {
FieldReference f =
FieldReference.findOrCreate(
loader,
instruction.getClassType(),
instruction.getFieldName(),
instruction.getFieldType());
emitInstruction(insts.PutInstruction(getCurrentInstructionIndex(), value, f));
} else {
int ref = workingState.pop();
FieldReference f =
FieldReference.findOrCreate(
loader,
instruction.getClassType(),
instruction.getFieldName(),
instruction.getFieldType());
emitInstruction(insts.PutInstruction(getCurrentInstructionIndex(), ref, value, f));
}
}
/** @see com.ibm.wala.shrike.shrikeBT.IInstruction.Visitor#visitReturn(ReturnInstruction) */
@Override
public void visitReturn(com.ibm.wala.shrike.shrikeBT.ReturnInstruction instruction) {
if (instruction.getPoppedCount() == 1) {
int result = workingState.pop();
TypeReference t = ShrikeUtil.makeTypeReference(loader, instruction.getType());
emitInstruction(
insts.ReturnInstruction(getCurrentInstructionIndex(), result, t.isPrimitiveType()));
} else {
emitInstruction(insts.ReturnInstruction(getCurrentInstructionIndex()));
}
}
/** @see com.ibm.wala.shrike.shrikeBT.IInstruction.Visitor#visitShift(IShiftInstruction) */
@Override
public void visitShift(IShiftInstruction instruction) {
int val2 = workingState.pop();
int val1 = workingState.pop();
int result = reuseOrCreateDef();
workingState.push(result);
emitInstruction(
insts.BinaryOpInstruction(
getCurrentInstructionIndex(),
instruction.getOperator(),
false,
instruction.isUnsigned(),
result,
val1,
val2,
true));
}
/** @see com.ibm.wala.shrike.shrikeBT.IInstruction.Visitor#visitSwitch(SwitchInstruction) */
@Override
public void visitSwitch(com.ibm.wala.shrike.shrikeBT.SwitchInstruction instruction) {
int val = workingState.pop();
emitInstruction(
insts.SwitchInstruction(
getCurrentInstructionIndex(),
val,
instruction.getDefaultLabel(),
instruction.getCasesAndLabels()));
}
private Dominators<ISSABasicBlock> dom = null;
private int findRethrowException() {
int index = getCurrentInstructionIndex();
SSACFG.BasicBlock bb = cfg.getBlockForInstruction(index);
if (bb.isCatchBlock()) {
SSACFG.ExceptionHandlerBasicBlock newBB = (SSACFG.ExceptionHandlerBasicBlock) bb;
SSAGetCaughtExceptionInstruction s = newBB.getCatchInstruction();
return s.getDef();
} else {
// TODO: should we really use dominators here? maybe it would be cleaner to propagate
// the notion of 'current exception to rethrow' using the abstract interpreter.
if (dom == null) {
dom = Dominators.make(cfg, cfg.entry());
}
ISSABasicBlock x = bb;
while (x != null) {
if (x.isCatchBlock()) {
SSACFG.ExceptionHandlerBasicBlock newBB = (SSACFG.ExceptionHandlerBasicBlock) x;
SSAGetCaughtExceptionInstruction s = newBB.getCatchInstruction();
return s.getDef();
} else {
x = dom.getIdom(x);
}
}
// assert false;
return -1;
}
}
/** @see com.ibm.wala.shrike.shrikeBT.IInstruction.Visitor#visitThrow(ThrowInstruction) */
@Override
public void visitThrow(com.ibm.wala.shrike.shrikeBT.ThrowInstruction instruction) {
if (instruction.isRethrow()) {
workingState.clearStack();
emitInstruction(
insts.ThrowInstruction(getCurrentInstructionIndex(), findRethrowException()));
} else {
int exception = workingState.pop();
workingState.clearStack();
workingState.push(exception);
emitInstruction(insts.ThrowInstruction(getCurrentInstructionIndex(), exception));
}
}
/**
* @see com.ibm.wala.shrike.shrikeBT.IInstruction.Visitor#visitUnaryOp(IUnaryOpInstruction)
*/
@Override
public void visitUnaryOp(IUnaryOpInstruction instruction) {
int val = workingState.pop();
int result = reuseOrCreateDef();
workingState.push(result);
emitInstruction(
insts.UnaryOpInstruction(
getCurrentInstructionIndex(), instruction.getOperator(), result, val));
}
private void doIndirectReads(int[] locals) {
for (int local : locals) {
ssaIndirections.setUse(
getCurrentInstructionIndex(),
new ShrikeLocalName(local),
workingState.getLocal(local));
}
}
@Override
public void visitLoadIndirect(ILoadIndirectInstruction instruction) {
int addressVal = workingState.pop();
int result = reuseOrCreateDef();
doIndirectReads(bytecodeIndirections.indirectlyReadLocals(getCurrentInstructionIndex()));
TypeReference t = ShrikeUtil.makeTypeReference(loader, instruction.getPushedType(null));
emitInstruction(
insts.LoadIndirectInstruction(getCurrentInstructionIndex(), result, t, addressVal));
workingState.push(result);
}
private void doIndirectWrites(int[] locals, int rval) {
for (int local : locals) {
ShrikeLocalName name = new ShrikeLocalName(local);
int idx = getCurrentInstructionIndex();
if (ssaIndirections.getDef(idx, name) == -1) {
ssaIndirections.setDef(idx, name, rval == -1 ? symbolTable.newSymbol() : rval);
}
workingState.setLocal(local, ssaIndirections.getDef(idx, name));
}
}
@Override
public void visitStoreIndirect(IStoreIndirectInstruction instruction) {
int val = workingState.pop();
int addressVal = workingState.pop();
doIndirectWrites(
bytecodeIndirections.indirectlyWrittenLocals(getCurrentInstructionIndex()), val);
TypeReference t = ShrikeUtil.makeTypeReference(loader, instruction.getType());
emitInstruction(
insts.StoreIndirectInstruction(getCurrentInstructionIndex(), addressVal, val, t));
}
}
private void reuseOrCreatePi(SSAInstruction piCause, int ref) {
int n = getCurrentInstructionIndex();
SSACFG.BasicBlock bb = cfg.getBlockForInstruction(n);
BasicBlock path = getCurrentSuccessor();
int outNum = shrikeCFG.getNumber(path);
SSAPiInstruction pi = bb.getPiForRefAndPath(ref, path);
if (pi == null) {
pi =
insts.PiInstruction(
SSAInstruction.NO_INDEX,
symbolTable.newSymbol(),
ref,
bb.getNumber(),
outNum,
piCause);
bb.addPiForRefAndPath(ref, path, pi);
}
workingState.replaceValue(ref, pi.getDef());
}
// private void maybeInsertPi(int val) {
// if ((addPiForFieldSelect) && (creators.length > val) && (creators[val] instanceof
// SSAGetInstruction)
// && !((SSAGetInstruction) creators[val]).isStatic()) {
// reuseOrCreatePi(creators[val], val);
// } else if ((addPiForDispatchSelect)
// && (creators.length > val)
// && (creators[val] instanceof SSAInvokeInstruction)
// && (((SSAInvokeInstruction) creators[val]).getInvocationCode() ==
// IInvokeInstruction.Dispatch.VIRTUAL ||
// ((SSAInvokeInstruction) creators[val])
// .getInvocationCode() == IInvokeInstruction.Dispatch.INTERFACE)) {
// reuseOrCreatePi(creators[val], val);
// }
// }
private void maybeInsertPi(SSAAbstractInvokeInstruction call) {
if (piNodePolicy != null) {
Pair<Integer, SSAInstruction> pi = piNodePolicy.getPi(call, symbolTable);
if (pi != null) {
reuseOrCreatePi(pi.snd, pi.fst);
}
}
}
private void maybeInsertPi(SSAConditionalBranchInstruction cond) {
if (piNodePolicy != null) {
for (Pair<Integer, SSAInstruction> pi :
piNodePolicy.getPis(
cond, getDef(cond.getUse(0)), getDef(cond.getUse(1)), symbolTable)) {
if (pi != null) {
reuseOrCreatePi(pi.snd, pi.fst);
}
}
}
}
private SSAInstruction getDef(int vn) {
if (vn < creators.length) {
return creators[vn];
} else {
return null;
}
}
class EdgeVisitor extends com.ibm.wala.shrike.shrikeBT.IInstruction.Visitor {
@Override
public void visitInvoke(IInvokeInstruction instruction) {
maybeInsertPi((SSAAbstractInvokeInstruction) getCurrentInstruction());
}
@Override
public void visitConditionalBranch(IConditionalBranchInstruction instruction) {
maybeInsertPi((SSAConditionalBranchInstruction) getCurrentInstruction());
}
}
@Override
public com.ibm.wala.shrike.shrikeBT.IInstruction[] getInstructions() {
try {
return shrikeCFG.getMethod().getInstructions();
} catch (InvalidClassFileException e) {
e.printStackTrace();
Assertions.UNREACHABLE();
return null;
}
}
}
/** Build the IR */
public void build() {
solve();
if (localMap != null) {
localMap.finishLocalMap(this);
}
}
public SSA2LocalMap getLocalMap() {
return localMap;
}
public ShrikeIndirectionData getIndirectionData() {
return ssaIndirections;
}
/**
* A logical mapping from <pc, valueNumber> -> local number Note: make sure this class
* remains static: this persists as part of the IR!!
*/
private static class SSA2LocalMap implements com.ibm.wala.ssa.IR.SSA2LocalMap {
private final ShrikeCFG shrikeCFG;
/**
* Mapping Integer -> IntPair where p maps to (vn,L) iff we've started a range at pc p where
* value number vn corresponds to local L
*/
private final IntPair[] localStoreMap;
/**
* For each basic block i and local j, block2LocalState[i][j] gives the contents of local j at
* the start of block i
*/
private final int[][] block2LocalState;
/**
* @param nInstructions number of instructions in the bytecode for this method
* @param nBlocks number of basic blocks in the CFG
*/
SSA2LocalMap(ShrikeCFG shrikeCfg, int nInstructions, int nBlocks) {
shrikeCFG = shrikeCfg;
localStoreMap = new IntPair[nInstructions];
block2LocalState = new int[nBlocks][];
}
/**
* Record the beginning of a new range, starting at the given program counter, in which a
* particular value number corresponds to a particular local number
*/
void startRange(int pc, int localNumber, int valueNumber) {
localStoreMap[pc] = new IntPair(valueNumber, localNumber);
}
/** Finish populating the map of local variable information */
private void finishLocalMap(SSABuilder builder) {
for (BasicBlock bb : shrikeCFG) {
MachineState S = builder.getIn(bb);
int number = bb.getNumber();
block2LocalState[number] = S.getLocals();
}
}
/**
* @param index - index into IR instruction array
* @param vn - value number
*/
@Override
public String[] getLocalNames(int index, int vn) {
try {
if (!shrikeCFG.getMethod().hasLocalVariableTable()) {
return null;
} else {
int[] localNumbers = findLocalsForValueNumber(index, vn);
if (localNumbers == null) {
return null;
} else {
IBytecodeMethod<?> m = shrikeCFG.getMethod();
String[] result = new String[localNumbers.length];
for (int i = 0; i < localNumbers.length; i++) {
result[i] = m.getLocalVariableName(m.getBytecodeIndex(index), localNumbers[i]);
}
return result;
}
}
} catch (Exception e) {
e.printStackTrace();
Assertions.UNREACHABLE();
return null;
}
}
public int[] allocateNewLocalsArray(int maxLocals) {
int[] result = new int[maxLocals];
for (int i = 0; i < maxLocals; i++) {
result[i] = OPTIMISTIC ? TOP : BOTTOM;
}
return result;
}
private int[] setLocal(int[] locals, int localNumber, int valueNumber) {
if (locals == null) {
locals = allocateNewLocalsArray(localNumber + 1);
} else if (locals.length <= localNumber) {
int[] newLocals = allocateNewLocalsArray(2 * Math.max(locals.length, localNumber) + 1);
System.arraycopy(locals, 0, newLocals, 0, locals.length);
locals = newLocals;
}
locals[localNumber] = valueNumber;
return locals;
}
/**
* @param pc a program counter (index into ShrikeBT instruction array)
* @param vn a value number
* @return if we know that immediately after the given program counter, v_vn corresponds to some
* set of locals, then return an array of the local numbers. else return null.
*/
private int[] findLocalsForValueNumber(int pc, int vn) {
if (vn < 0) {
return null;
}
IBasicBlock<?> bb = shrikeCFG.getBlockForInstruction(pc);
int firstInstruction = bb.getFirstInstructionIndex();
// walk forward from the first instruction to reconstruct the
// state of the locals at this pc
int[] locals = block2LocalState[bb.getNumber()];
for (int i = firstInstruction; i <= pc; i++) {
if (localStoreMap[i] != null) {
IntPair p = localStoreMap[i];
locals = setLocal(locals, p.getY(), p.getX());
}
}
return locals == null ? null : extractIndices(locals, vn);
}
/** @return the indices i s.t. x[i] == y, or null if none found. */
private static int[] extractIndices(int[] x, int y) {
assert x != null;
int count = 0;
for (int element : x) {
if (element == y) {
count++;
}
}
if (count == 0) {
return null;
} else {
int[] result = new int[count];
int j = 0;
for (int i = 0; i < x.length; i++) {
if (x[i] == y) {
result[j++] = i;
}
}
return result;
}
}
}
}
| 41,181
| 35.2837
| 103
|
java
|
WALA
|
WALA-master/core/src/main/java/com/ibm/wala/ssa/SSACFG.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.ssa;
import com.ibm.wala.cfg.AbstractCFG;
import com.ibm.wala.cfg.BytecodeCFG;
import com.ibm.wala.cfg.ControlFlowGraph;
import com.ibm.wala.cfg.IBasicBlock;
import com.ibm.wala.cfg.InducedCFG;
import com.ibm.wala.cfg.MinimalCFG;
import com.ibm.wala.classLoader.IClass;
import com.ibm.wala.classLoader.IClassLoader;
import com.ibm.wala.classLoader.IMethod;
import com.ibm.wala.core.util.shrike.ShrikeUtil;
import com.ibm.wala.core.util.warnings.Warning;
import com.ibm.wala.core.util.warnings.Warnings;
import com.ibm.wala.shrike.shrikeBT.ExceptionHandler;
import com.ibm.wala.shrike.shrikeBT.IInstruction;
import com.ibm.wala.types.ClassLoaderReference;
import com.ibm.wala.types.TypeReference;
import com.ibm.wala.util.collections.EmptyIterator;
import com.ibm.wala.util.collections.HashMapFactory;
import com.ibm.wala.util.collections.Iterator2Collection;
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.impl.NumberedNodeIterator;
import com.ibm.wala.util.intset.BitVector;
import com.ibm.wala.util.intset.IntSet;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Function;
import java.util.stream.Stream;
/**
* A control-flow graph for ssa form.
*
* <p>This implementation is uglified in the name of performance. This implementation does not
* directly track the graph structure, but instead delegates to a prebuilt {@link ControlFlowGraph}
* which stores the structure. This decision from 2004 may have been premature optimization, left
* over from a world where {@link IR}s and related structures were long-lived. In today's system,
* they are cached and reconstituted by {@link SSACache}. Perhaps we should just extend {@link
* AbstractCFG} and not worry so much about space.
*
* <p>As the current implementation stands, the delegate graph stores the graph structure, and this
* class additionally stores {@link BasicBlock}s and the {@link SSAInstruction} array.
*/
public class SSACFG
implements ControlFlowGraph<SSAInstruction, ISSABasicBlock>, MinimalCFG<ISSABasicBlock> {
private static final boolean DEBUG = false;
/**
* The {@link ISSABasicBlock}s which live in this graph. These {@link BasicBlock}s must have the
* same numbers as the corresponding {@link IBasicBlock}s in the delegate {@link AbstractCFG}.
* This array is additionally co-indexed by these numbers.
*/
private BasicBlock[] basicBlocks;
/**
* The "normal" instructions which constitute the SSA form. This does not include {@link
* SSAPhiInstruction}s, which dwell in {@link BasicBlock}s instead.
*/
protected final SSAInstruction[] instructions;
/** The {@link IMethod} this {@link ControlFlowGraph} represents */
protected final IMethod method;
/** A delegate CFG, pre-built, which stores the graph structure of this CFG. */
protected final AbstractCFG<IInstruction, IBasicBlock<IInstruction>> delegate;
/** cache a ref to the exit block for efficient access */
private BasicBlock exit;
/** @throws IllegalArgumentException if method is null */
@SuppressWarnings("unchecked")
public SSACFG(IMethod method, AbstractCFG cfg, SSAInstruction[] instructions) {
if (method == null) {
throw new IllegalArgumentException("method is null");
}
this.delegate = cfg;
if (DEBUG) {
System.err.println(("Incoming CFG for " + method + ':'));
System.err.println(cfg.toString());
}
this.method = method;
assert method.getDeclaringClass() != null : "null declaring class for " + method;
createBasicBlocks(cfg);
if (cfg instanceof InducedCFG) {
addPhisFromInducedCFG((InducedCFG) cfg);
addPisFromInducedCFG((InducedCFG) cfg);
}
if (cfg instanceof BytecodeCFG) {
recordExceptionTypes(
((BytecodeCFG) cfg).getExceptionHandlers(), method.getDeclaringClass().getClassLoader());
}
this.instructions = instructions;
}
/**
* This is ugly. Clean it up someday. {@link InducedCFG}s carry around pii instructions. add these
* pii instructions to the SSABasicBlocks
*/
private void addPisFromInducedCFG(InducedCFG cfg) {
for (com.ibm.wala.cfg.InducedCFG.BasicBlock ib : cfg) {
// we rely on the invariant that basic blocks in this cfg are numbered identically as in the
// source
// InducedCFG
BasicBlock b = getBasicBlock(ib.getNumber());
for (SSAPiInstruction pi : ib.getPis()) {
BasicBlock path = getBasicBlock(pi.getSuccessor());
b.addPiForRefAndPath(pi.getVal(), path, pi);
}
}
}
/**
* This is ugly. Clean it up someday. {@link InducedCFG}s carry around phi instructions. add these
* phi instructions to the SSABasicBlocks
*/
private void addPhisFromInducedCFG(InducedCFG cfg) {
for (com.ibm.wala.cfg.InducedCFG.BasicBlock ib : cfg) {
// we rely on the invariant that basic blocks in this cfg are numbered identically as in the
// source
// InducedCFG
BasicBlock b = getBasicBlock(ib.getNumber());
// this is really ugly. we pretend that each successively phi in the basic block defs a
// particular 'local'. TODO: fix the API in some way so that this is unnecessary.
// {What does Julian do for, say, Javascript?}
int local = 0;
for (SSAPhiInstruction phi : ib.getPhis()) {
b.addPhiForLocal(local++, phi);
}
}
}
@Override
public int hashCode() {
return -3 * delegate.hashCode();
}
@Override
public boolean equals(Object o) {
return (o instanceof SSACFG) && delegate.equals(((SSACFG) o).delegate);
}
private void recordExceptionTypes(Set<ExceptionHandler> set, IClassLoader loader) {
for (ExceptionHandler handler : set) {
TypeReference t = null;
if (handler.getCatchClass() == null) {
// by convention, in ShrikeCT this means catch everything
t = TypeReference.JavaLangThrowable;
} else if (handler.getCatchClassLoader() instanceof ClassLoaderReference) {
t =
ShrikeUtil.makeTypeReference(
(ClassLoaderReference) handler.getCatchClassLoader(), handler.getCatchClass());
} else {
TypeReference exceptionType =
ShrikeUtil.makeTypeReference(loader.getReference(), handler.getCatchClass());
IClass klass = loader.lookupClass(exceptionType.getName());
if (klass == null) {
Warnings.add(ExceptionLoadFailure.create(exceptionType, method));
t = exceptionType;
} else {
t = klass.getReference();
}
}
int instructionIndex = handler.getHandler();
IBasicBlock<?> b = getBlockForInstruction(instructionIndex);
assert b instanceof ExceptionHandlerBasicBlock
: "not exception handler " + b + " index " + instructionIndex;
ExceptionHandlerBasicBlock bb =
(ExceptionHandlerBasicBlock) getBlockForInstruction(instructionIndex);
bb.addCaughtExceptionType(t);
}
}
private void createBasicBlocks(AbstractCFG<?, ?> G) {
basicBlocks = new BasicBlock[G.getNumberOfNodes()];
for (int i = 0; i <= G.getMaxNumber(); i++) {
if (G.getCatchBlocks().get(i)) {
basicBlocks[i] = new ExceptionHandlerBasicBlock(i);
} else {
basicBlocks[i] = new BasicBlock(i);
}
}
exit = basicBlocks[delegate.getNumber(delegate.exit())];
}
/**
* Get the basic block an instruction belongs to. Note: the instruction2Block array is filled in
* lazily. During initialization, the mapping is set up only for the first instruction of each
* basic block.
*/
@Override
public SSACFG.BasicBlock getBlockForInstruction(int instructionIndex) {
IBasicBlock<IInstruction> N = delegate.getBlockForInstruction(instructionIndex);
int number = delegate.getNumber(N);
return basicBlocks[number];
}
/**
* NB: Use iterators such as IR.iterateAllInstructions() instead of this method. This will
* probably be deprecated someday.
*
* <p>Return the instructions. Note that the CFG is created from the Shrike CFG prior to creating
* the SSA instructions.
*
* @return an array containing the SSA instructions.
*/
@Override
public SSAInstruction[] getInstructions() {
return instructions;
}
private final Map<RefPathKey, SSAPiInstruction> piInstructions = HashMapFactory.make(2);
private static class RefPathKey {
private final int n;
private final Object src;
private final Object path;
RefPathKey(int n, Object src, Object path) {
this.n = n;
this.src = src;
this.path = path;
}
@Override
public int hashCode() {
return n * path.hashCode();
}
@Override
public boolean equals(Object x) {
return (x instanceof RefPathKey)
&& n == ((RefPathKey) x).n
&& src == ((RefPathKey) x).src
&& path == ((RefPathKey) x).path;
}
}
/** A Basic Block in an SSA IR */
public class BasicBlock implements ISSABasicBlock {
/** state needed for the numbered graph. */
private final int number;
/** List of PhiInstructions associated with the entry of this block. */
private SSAPhiInstruction stackSlotPhis[];
private SSAPhiInstruction localPhis[];
private static final int initialCapacity = 10;
public BasicBlock(int number) {
this.number = number;
}
@Override
public int getNumber() {
return number;
}
/** Method getFirstInstructionIndex. */
@Override
public int getFirstInstructionIndex() {
IBasicBlock<?> B = delegate.getNode(number);
return B.getFirstInstructionIndex();
}
/** Is this block marked as a catch block? */
@Override
public boolean isCatchBlock() {
return delegate.getCatchBlocks().get(getNumber());
}
@Override
public int getLastInstructionIndex() {
IBasicBlock<?> B = delegate.getNode(number);
return B.getLastInstructionIndex();
}
@Override
public Iterator<SSAPhiInstruction> iteratePhis() {
compressPhis();
if (stackSlotPhis == null) {
if (localPhis == null) {
return EmptyIterator.instance();
} else {
ArrayList<SSAPhiInstruction> result = new ArrayList<>();
for (SSAPhiInstruction phi : localPhis) {
if (phi != null) {
result.add(phi);
}
}
return result.iterator();
}
} else {
// stackSlotPhis != null
ArrayList<SSAPhiInstruction> result = new ArrayList<>();
for (SSAPhiInstruction phi : stackSlotPhis) {
if (phi != null) {
result.add(phi);
}
}
if (localPhis != null) {
for (SSAPhiInstruction phi : localPhis) {
if (phi != null) {
result.add(phi);
}
}
}
return result.iterator();
}
}
/** This method is used during SSA construction. */
public SSAPhiInstruction getPhiForStackSlot(int slot) {
if (stackSlotPhis == null) {
return null;
} else {
if (slot >= stackSlotPhis.length) {
return null;
} else {
return stackSlotPhis[slot];
}
}
}
/** This method is used during SSA construction. */
public SSAPhiInstruction getPhiForLocal(int n) {
if (localPhis == null) {
return null;
} else {
if (n >= localPhis.length) {
return null;
} else {
return localPhis[n];
}
}
}
public void addPhiForStackSlot(int slot, SSAPhiInstruction phi) {
if (stackSlotPhis == null) {
stackSlotPhis = new SSAPhiInstruction[initialCapacity];
}
if (slot >= stackSlotPhis.length) {
stackSlotPhis = Arrays.copyOf(stackSlotPhis, slot * 2);
}
stackSlotPhis[slot] = phi;
}
public void addPhiForLocal(int n, SSAPhiInstruction phi) {
if (localPhis == null) {
localPhis = new SSAPhiInstruction[initialCapacity];
}
if (n >= localPhis.length) {
localPhis = Arrays.copyOf(localPhis, n * 2);
}
localPhis[n] = phi;
}
/** Remove any phis in the set. */
public void removePhis(Set<SSAPhiInstruction> toRemove) {
int nRemoved = 0;
if (stackSlotPhis != null) {
for (int i = 0; i < stackSlotPhis.length; i++) {
if (toRemove.contains(stackSlotPhis[i])) {
stackSlotPhis[i] = null;
nRemoved++;
}
}
}
if (nRemoved > 0) {
int newLength = stackSlotPhis.length - nRemoved;
if (newLength == 0) {
stackSlotPhis = null;
} else {
SSAPhiInstruction[] old = stackSlotPhis;
stackSlotPhis = new SSAPhiInstruction[newLength];
int j = 0;
for (SSAPhiInstruction element : old) {
if (element != null) {
stackSlotPhis[j++] = element;
}
}
}
}
nRemoved = 0;
if (localPhis != null) {
for (int i = 0; i < localPhis.length; i++) {
if (toRemove.contains(localPhis[i])) {
localPhis[i] = null;
nRemoved++;
}
}
}
if (nRemoved > 0) {
int newLength = localPhis.length - nRemoved;
if (newLength == 0) {
localPhis = null;
} else {
SSAPhiInstruction[] old = localPhis;
localPhis = new SSAPhiInstruction[newLength];
int j = 0;
for (SSAPhiInstruction element : old) {
if (element != null) {
localPhis[j++] = element;
}
}
}
}
}
public SSAPiInstruction getPiForRefAndPath(int n, Object path) {
return piInstructions.get(new RefPathKey(n, this, path));
}
private final ArrayList<SSAPiInstruction> blockPiInstructions = new ArrayList<>();
/**
* @param n can be the val in the pi instruction
* @param path can be the successor block in the pi instruction
*/
public void addPiForRefAndPath(int n, Object path, SSAPiInstruction pi) {
piInstructions.put(new RefPathKey(n, this, path), pi);
blockPiInstructions.add(pi);
}
@Override
public Iterator<SSAPiInstruction> iteratePis() {
return blockPiInstructions.iterator();
}
public Iterator<SSAInstruction> iterateNormalInstructions() {
int lookup = getFirstInstructionIndex();
final int end = getLastInstructionIndex();
// skip to first non-null instruction
while (lookup <= end && instructions[lookup] == null) {
lookup++;
}
final int dummy = lookup;
return new Iterator<>() {
private int start = dummy;
@Override
public boolean hasNext() {
return (start <= end);
}
@Override
public SSAInstruction next() {
SSAInstruction i = instructions[start];
start++;
while (start <= end && instructions[start] == null) {
start++;
}
return i;
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
};
}
/** TODO: make this more efficient if needed */
public List<SSAInstruction> getAllInstructions() {
compressPhis();
ArrayList<SSAInstruction> result = new ArrayList<>();
for (SSAInstruction inst : Iterator2Iterable.make(iteratePhis())) {
result.add(inst);
}
for (int i = getFirstInstructionIndex(); i <= getLastInstructionIndex(); i++) {
SSAInstruction s = instructions[i];
if (s != null) {
result.add(s);
}
}
for (SSAInstruction inst : Iterator2Iterable.make(iteratePis())) {
result.add(inst);
}
return result;
}
/** rewrite the phi arrays so they have no null entries. */
private void compressPhis() {
if (stackSlotPhis != null && stackSlotPhis[stackSlotPhis.length - 1] == null) {
int size = countNonNull(stackSlotPhis);
if (size == 0) {
stackSlotPhis = null;
} else {
SSAPhiInstruction[] old = stackSlotPhis;
stackSlotPhis = new SSAPhiInstruction[size];
int j = 0;
for (SSAPhiInstruction element : old) {
if (element != null) {
stackSlotPhis[j++] = element;
}
}
}
}
if (localPhis != null && localPhis[localPhis.length - 1] == null) {
int size = countNonNull(localPhis);
if (size == 0) {
localPhis = null;
} else {
SSAPhiInstruction[] old = localPhis;
localPhis = new SSAPhiInstruction[size];
int j = 0;
for (SSAPhiInstruction element : old) {
if (element != null) {
localPhis[j++] = element;
}
}
}
}
}
private int countNonNull(SSAPhiInstruction[] a) {
int result = 0;
for (SSAPhiInstruction element : a) {
if (element != null) {
result++;
}
}
return result;
}
@Override
public Iterator<SSAInstruction> iterator() {
return getAllInstructions().iterator();
}
/** @return true iff this basic block has at least one phi */
public boolean hasPhi() {
return stackSlotPhis != null || localPhis != null;
}
/** @see com.ibm.wala.util.graph.INodeWithNumber#getGraphNodeId() */
@Override
public int getGraphNodeId() {
return number;
}
/** @see com.ibm.wala.util.graph.INodeWithNumber#setGraphNodeId(int) */
@Override
public void setGraphNodeId(int number) {
// TODO Auto-generated method stub
}
@Override
public String toString() {
return "BB[SSA:"
+ getFirstInstructionIndex()
+ ".."
+ getLastInstructionIndex()
+ ']'
+ getNumber()
+ " - "
+ method.getSignature();
}
private SSACFG getGraph() {
return SSACFG.this;
}
@Override
public boolean equals(Object arg0) {
if (arg0 instanceof BasicBlock) {
BasicBlock b = (BasicBlock) arg0;
if (getNumber() == b.getNumber()) {
if (getMethod().equals(b.getMethod())) {
return getGraph().equals(b.getGraph());
} else {
return false;
}
} else {
return false;
}
} else {
return false;
}
}
@Override
public IMethod getMethod() {
return method;
}
@Override
public int hashCode() {
return delegate.getNode(getNumber()).hashCode() * 6271;
}
/** @see com.ibm.wala.cfg.IBasicBlock#isExitBlock() */
@Override
public boolean isExitBlock() {
return this == SSACFG.this.exit();
}
/** @see com.ibm.wala.cfg.IBasicBlock#isEntryBlock() */
@Override
public boolean isEntryBlock() {
return this == SSACFG.this.entry();
}
@Override
public SSAInstruction getLastInstruction() {
return instructions[getLastInstructionIndex()];
}
/** The {@link ExceptionHandlerBasicBlock} subclass will override this. */
@Override
public Iterator<TypeReference> getCaughtExceptionTypes() {
return EmptyIterator.instance();
}
}
public class ExceptionHandlerBasicBlock extends BasicBlock {
/** The type of the exception caught by this block. */
private TypeReference[] exceptionTypes;
private static final int initialCapacity = 3;
private int nExceptionTypes = 0;
/** Instruction that defines the exception value this block catches */
private SSAGetCaughtExceptionInstruction catchInstruction;
public ExceptionHandlerBasicBlock(int number) {
super(number);
}
public SSAGetCaughtExceptionInstruction getCatchInstruction() {
return catchInstruction;
}
public void setCatchInstruction(SSAGetCaughtExceptionInstruction catchInstruction) {
this.catchInstruction = catchInstruction;
}
@Override
public Iterator<TypeReference> getCaughtExceptionTypes() {
return new Iterator<>() {
int next = 0;
@Override
public boolean hasNext() {
return next < nExceptionTypes;
}
@Override
public TypeReference next() {
return exceptionTypes[next++];
}
@Override
public void remove() {
Assertions.UNREACHABLE();
}
};
}
@Override
public String toString() {
return "BB(Handler)[SSA]" + getNumber() + " - " + method.getSignature();
}
public void addCaughtExceptionType(TypeReference exceptionType) {
if (exceptionTypes == null) {
exceptionTypes = new TypeReference[initialCapacity];
}
nExceptionTypes++;
if (nExceptionTypes > exceptionTypes.length) {
exceptionTypes = Arrays.copyOf(exceptionTypes, nExceptionTypes * 2);
}
exceptionTypes[nExceptionTypes - 1] = exceptionType;
}
@Override
public List<SSAInstruction> getAllInstructions() {
List<SSAInstruction> result = super.getAllInstructions();
if (catchInstruction != null) {
// it's disturbing that catchInstruction can be null here. must be some
// strange corner case
// involving dead code. oh well .. keep on chugging until we have hard
// evidence that this is a bug
result.add(0, catchInstruction);
}
return result;
}
}
@Override
public String toString() {
StringBuilder s = new StringBuilder();
for (int i = 0; i <= getNumber(exit()); i++) {
BasicBlock bb = getNode(i);
s.append("BB")
.append(i)
.append('[')
.append(bb.getFirstInstructionIndex())
.append("..")
.append(bb.getLastInstructionIndex())
.append("]\n");
Iterator<ISSABasicBlock> succNodes = getSuccNodes(bb);
while (succNodes.hasNext()) {
s.append(" -> BB").append(((BasicBlock) succNodes.next()).getNumber()).append('\n');
}
}
return s.toString();
}
@Override
public BitVector getCatchBlocks() {
return delegate.getCatchBlocks();
}
/**
* is the given i a catch block?
*
* @return true if catch block, false otherwise
*/
public boolean isCatchBlock(int i) {
return delegate.isCatchBlock(i);
}
@Override
public SSACFG.BasicBlock entry() {
return basicBlocks[0];
}
@Override
public SSACFG.BasicBlock exit() {
return exit;
}
@Override
public int getNumber(ISSABasicBlock b) throws IllegalArgumentException {
if (b == null) {
throw new IllegalArgumentException("N == null");
}
return b.getNumber();
}
/** @see com.ibm.wala.util.graph.NumberedGraph#getNode(int) */
@Override
public BasicBlock getNode(int number) {
return basicBlocks[number];
}
/** @see com.ibm.wala.util.graph.NumberedGraph#getMaxNumber() */
@Override
public int getMaxNumber() {
return basicBlocks.length - 1;
}
/** @see com.ibm.wala.util.graph.Graph#iterator() */
@Override
public Iterator<ISSABasicBlock> iterator() {
return Arrays.<ISSABasicBlock>asList(basicBlocks).iterator();
}
@Override
public Stream<ISSABasicBlock> stream() {
return Arrays.stream(basicBlocks);
}
/** @see com.ibm.wala.util.graph.Graph#getNumberOfNodes() */
@Override
public int getNumberOfNodes() {
return delegate.getNumberOfNodes();
}
/** @see com.ibm.wala.util.graph.Graph#getPredNodes(Object) */
@Override
public Iterator<ISSABasicBlock> getPredNodes(ISSABasicBlock b) throws IllegalArgumentException {
if (b == null) {
throw new IllegalArgumentException("b == null");
}
IBasicBlock<IInstruction> n = delegate.getNode(b.getNumber());
final Iterator<IBasicBlock<IInstruction>> i = delegate.getPredNodes(n);
return new Iterator<>() {
@Override
public boolean hasNext() {
return i.hasNext();
}
@Override
public BasicBlock next() {
IBasicBlock<?> n = i.next();
int number = n.getNumber();
return basicBlocks[number];
}
@Override
public void remove() {
Assertions.UNREACHABLE();
}
};
}
/** @see com.ibm.wala.util.graph.Graph#getPredNodeCount(Object) */
@Override
public int getPredNodeCount(ISSABasicBlock b) throws IllegalArgumentException {
if (b == null) {
throw new IllegalArgumentException("b == null");
}
IBasicBlock<IInstruction> n = delegate.getNode(b.getNumber());
return delegate.getPredNodeCount(n);
}
/** @see com.ibm.wala.util.graph.Graph#getSuccNodes(Object) */
@Override
public Iterator<ISSABasicBlock> getSuccNodes(ISSABasicBlock b) throws IllegalArgumentException {
if (b == null) {
throw new IllegalArgumentException("b == null");
}
IBasicBlock<IInstruction> n = delegate.getNode(b.getNumber());
final Iterator<IBasicBlock<IInstruction>> i = delegate.getSuccNodes(n);
return new Iterator<>() {
@Override
public boolean hasNext() {
return i.hasNext();
}
@Override
public ISSABasicBlock next() {
IBasicBlock<?> n = i.next();
int number = n.getNumber();
return basicBlocks[number];
}
@Override
public void remove() {
Assertions.UNREACHABLE();
}
};
}
/** @see com.ibm.wala.util.graph.Graph#getSuccNodeCount(Object) */
@Override
public int getSuccNodeCount(ISSABasicBlock b) throws IllegalArgumentException {
if (b == null) {
throw new IllegalArgumentException("b == null");
}
IBasicBlock<IInstruction> n = delegate.getNode(b.getNumber());
return delegate.getSuccNodeCount(n);
}
/** @see com.ibm.wala.util.graph.NumberedGraph#addNode(Object) */
@Override
public void addNode(ISSABasicBlock n) throws UnsupportedOperationException {
throw new UnsupportedOperationException();
}
@Override
public void addEdge(ISSABasicBlock src, ISSABasicBlock dst) throws UnsupportedOperationException {
throw new UnsupportedOperationException();
}
@Override
public void removeEdge(ISSABasicBlock src, ISSABasicBlock dst)
throws UnsupportedOperationException {
throw new UnsupportedOperationException();
}
/** @see com.ibm.wala.util.graph.EdgeManager#removeAllIncidentEdges(Object) */
@Override
public void removeAllIncidentEdges(ISSABasicBlock node) throws UnsupportedOperationException {
throw new UnsupportedOperationException();
}
/** @see com.ibm.wala.util.graph.Graph#removeNode(Object) */
@Override
public void removeNodeAndEdges(ISSABasicBlock N) throws UnsupportedOperationException {
throw new UnsupportedOperationException();
}
/** @see com.ibm.wala.util.graph.NodeManager#removeNode(Object) */
@Override
public void removeNode(ISSABasicBlock n) throws UnsupportedOperationException {
throw new UnsupportedOperationException();
}
@Override
public int getProgramCounter(int index) {
// delegate to incoming cfg.
return delegate.getProgramCounter(index);
}
/** @see com.ibm.wala.util.graph.Graph#containsNode(Object) */
@Override
public boolean containsNode(ISSABasicBlock N) {
if (N instanceof BasicBlock) {
return basicBlocks[getNumber(N)] == N;
} else {
return false;
}
}
@Override
public IMethod getMethod() {
return method;
}
@Override
public List<ISSABasicBlock> getExceptionalSuccessors(final ISSABasicBlock b) {
if (b == null) {
throw new IllegalArgumentException("b is null");
}
final IBasicBlock<IInstruction> n = delegate.getNode(b.getNumber());
final Collection<IBasicBlock<IInstruction>> ss = delegate.getExceptionalSuccessors(n);
final List<ISSABasicBlock> c = new ArrayList<>(getSuccNodeCount(b));
for (final IBasicBlock<IInstruction> s : ss) {
c.add(basicBlocks[delegate.getNumber(s)]);
}
return c;
}
/** @see com.ibm.wala.cfg.ControlFlowGraph#getExceptionalSuccessors(Object) */
@Override
public Collection<ISSABasicBlock> getExceptionalPredecessors(ISSABasicBlock b) {
if (b == null) {
throw new IllegalArgumentException("b is null");
}
IBasicBlock<IInstruction> n = delegate.getNode(b.getNumber());
Function<IBasicBlock<IInstruction>, ISSABasicBlock> f =
object -> basicBlocks[delegate.getNumber(object)];
return Iterator2Collection.toSet(
new MapIterator<>(delegate.getExceptionalPredecessors(n).iterator(), f));
}
private IBasicBlock<IInstruction> getUnderlyingBlock(SSACFG.BasicBlock block) {
return delegate.getNode(getNumber(block));
}
/**
* has exceptional edge src -> dest
*
* @throws IllegalArgumentException if dest is null
*/
public boolean hasExceptionalEdge(BasicBlock src, BasicBlock dest) {
if (dest == null) {
throw new IllegalArgumentException("dest is null");
}
if (dest.isExitBlock()) {
int srcNum = getNumber(src);
return delegate.getExceptionalToExit().get(srcNum);
}
return delegate.hasExceptionalEdge(getUnderlyingBlock(src), getUnderlyingBlock(dest));
}
/**
* has normal edge src -> dest
*
* @throws IllegalArgumentException if dest is null
*/
public boolean hasNormalEdge(BasicBlock src, BasicBlock dest) {
if (dest == null) {
throw new IllegalArgumentException("dest is null");
}
if (dest.isExitBlock()) {
int srcNum = getNumber(src);
return delegate.getNormalToExit().get(srcNum);
}
return delegate.hasNormalEdge(getUnderlyingBlock(src), getUnderlyingBlock(dest));
}
@Override
public Collection<ISSABasicBlock> getNormalSuccessors(ISSABasicBlock b) {
if (b == null) {
throw new IllegalArgumentException("b is null");
}
IBasicBlock<IInstruction> n = delegate.getNode(b.getNumber());
final Collection<IBasicBlock<IInstruction>> ss = delegate.getNormalSuccessors(n);
Collection<ISSABasicBlock> c = new ArrayList<>(getSuccNodeCount(b));
for (IBasicBlock<IInstruction> s : ss) {
c.add(basicBlocks[delegate.getNumber(s)]);
}
return c;
}
/** @see com.ibm.wala.cfg.ControlFlowGraph#getNormalSuccessors(Object) */
@Override
public Collection<ISSABasicBlock> getNormalPredecessors(ISSABasicBlock b) {
if (b == null) {
throw new IllegalArgumentException("b is null");
}
IBasicBlock<IInstruction> n = delegate.getNode(b.getNumber());
final Collection<IBasicBlock<IInstruction>> ss = delegate.getNormalPredecessors(n);
Collection<ISSABasicBlock> c = new ArrayList<>(getPredNodeCount(b));
for (IBasicBlock<IInstruction> s : ss) {
c.add(basicBlocks[delegate.getNumber(s)]);
}
return c;
}
/**
* @see com.ibm.wala.util.graph.NumberedNodeManager#iterateNodes(com.ibm.wala.util.intset.IntSet)
*/
@Override
public Iterator<ISSABasicBlock> iterateNodes(IntSet s) {
return new NumberedNodeIterator<>(s, this);
}
@Override
public void removeIncomingEdges(ISSABasicBlock node) throws UnsupportedOperationException {
throw new UnsupportedOperationException();
}
@Override
public void removeOutgoingEdges(ISSABasicBlock node) throws UnsupportedOperationException {
throw new UnsupportedOperationException();
}
@Override
public boolean hasEdge(ISSABasicBlock src, ISSABasicBlock dst) throws UnimplementedError {
return getSuccNodeNumbers(src).contains(getNumber(dst));
}
@Override
public IntSet getSuccNodeNumbers(ISSABasicBlock b) throws IllegalArgumentException {
if (b == null) {
throw new IllegalArgumentException("b == null");
}
IBasicBlock<IInstruction> n = delegate.getNode(b.getNumber());
return delegate.getSuccNodeNumbers(n);
}
@Override
public IntSet getPredNodeNumbers(ISSABasicBlock node) throws UnimplementedError {
Assertions.UNREACHABLE();
return null;
}
/** A warning for when we fail to resolve the type for a checkcast */
private static class ExceptionLoadFailure extends Warning {
final TypeReference type;
final IMethod method;
ExceptionLoadFailure(TypeReference type, IMethod method) {
super(Warning.MODERATE);
this.type = type;
this.method = method;
}
@Override
public String getMsg() {
return getClass().toString() + " : " + type + ' ' + method;
}
public static ExceptionLoadFailure create(TypeReference type, IMethod method) {
return new ExceptionLoadFailure(type, method);
}
}
/** @return the basic block with a particular number */
public BasicBlock getBasicBlock(int bb) {
return basicBlocks[bb];
}
}
| 33,436
| 29.648029
| 100
|
java
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.