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/cfg/exc/ExceptionPruningAnalysis.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.cfg.exc;
import com.ibm.wala.cfg.ControlFlowGraph;
import com.ibm.wala.cfg.IBasicBlock;
import com.ibm.wala.cfg.exc.intra.NullPointerState;
import com.ibm.wala.util.CancelException;
import com.ibm.wala.util.MonitorUtil.IProgressMonitor;
import com.ibm.wala.util.graph.GraphIntegrity.UnsoundGraphException;
/**
* This abstract class is used as interface for analysis that remove impossible control flow from a
* CFG. This is done by detecting exceptions that may always (or never) appear.
*
* @author Juergen Graf <graf@kit.edu>
*/
public interface ExceptionPruningAnalysis<I, T extends IBasicBlock<I>> {
/**
* Computes impossible control flow that is due to exceptions that definitely will not appear or
* that will always be thrown. You have to run this method before using getPruned() to extract the
* result of the analysis.
*
* @param progress A progress monitor that is used to display the progress of the analysis. It can
* also be used to detect a cancel request from the user. The common behavior is to cancel the
* method if progress.isCanceled() is true by throwing a CancelException.
* @return Number of edges that have been removed from the cfg.
* @throws UnsoundGraphException Thrown if the original CFG contains inconsistencies.
* @throws CancelException Thrown if the user requested cancellation through the progress monitor.
*/
int compute(IProgressMonitor progress) throws UnsoundGraphException, CancelException;
/**
* Returns the result of the analysis: A control flow graph where impossible control flow has been
* removed. The way how and which impossible flow is detected may vary between different
* implementations of this class. Run compute(IProgressMonitor) first.
*
* @return The improved CFG without edges that were detected as impossible flow.
*/
ControlFlowGraph<I, T> getCFG();
/**
* Returns true if the corresponding method contains instructions that may throw an exception
* which is not caught in the same method. Run compute(IPrograssMonitor) first.
*
* @return true if the corresponding method contains instructions that may throw an exception
* which is not caught in the same method
*/
boolean hasExceptions();
/**
* Returns the state of a node. The node has to be part of the cfg.
*
* @param bb Node
* @return NullPointerState
*/
NullPointerState getState(T bb);
}
| 2,829
| 40.014493
| 100
|
java
|
WALA
|
WALA-master/core/src/main/java/com/ibm/wala/cfg/exc/InterprocAnalysisResult.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.cfg.exc;
import com.ibm.wala.cfg.IBasicBlock;
import com.ibm.wala.ipa.callgraph.CGNode;
/**
* Interface to retrieve the result of the interprocedural analysis.
*
* @author Juergen Graf <graf@kit.edu>
*/
public interface InterprocAnalysisResult<I, T extends IBasicBlock<I>> {
/** Returns the result of the interprocedural analysis for the given call graph node. */
ExceptionPruningAnalysis<I, T> getResult(CGNode n);
/** Returns true iff an analysis result exists for the given call graph node. */
boolean containsResult(CGNode n);
}
| 952
| 30.766667
| 90
|
java
|
WALA
|
WALA-master/core/src/main/java/com/ibm/wala/cfg/exc/NullPointerAnalysis.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.cfg.exc;
import com.ibm.wala.cfg.exc.inter.InterprocNullPointerAnalysis;
import com.ibm.wala.cfg.exc.intra.ExplodedCFGNullPointerAnalysis;
import com.ibm.wala.cfg.exc.intra.MethodState;
import com.ibm.wala.cfg.exc.intra.ParameterState;
import com.ibm.wala.cfg.exc.intra.SSACFGNullPointerAnalysis;
import com.ibm.wala.ipa.callgraph.CallGraph;
import com.ibm.wala.ssa.IR;
import com.ibm.wala.ssa.ISSABasicBlock;
import com.ibm.wala.ssa.SSAInstruction;
import com.ibm.wala.ssa.analysis.IExplodedBasicBlock;
import com.ibm.wala.types.TypeReference;
import com.ibm.wala.util.CancelException;
import com.ibm.wala.util.MonitorUtil.IProgressMonitor;
import com.ibm.wala.util.WalaException;
import com.ibm.wala.util.graph.GraphIntegrity.UnsoundGraphException;
/**
* Tries to detect impossible (or always appearing) NullPointerExceptions and removes impossible
* control flow from the CFG.
*
* @author Juergen Graf <graf@kit.edu>
*/
public final class NullPointerAnalysis {
public static final TypeReference[] DEFAULT_IGNORE_EXCEPTIONS = {
TypeReference.JavaLangOutOfMemoryError,
TypeReference.JavaLangExceptionInInitializerError,
TypeReference.JavaLangNegativeArraySizeException
};
private NullPointerAnalysis() {
throw new IllegalStateException("No instances of this class allowed.");
}
public static ExceptionPruningAnalysis<SSAInstruction, IExplodedBasicBlock>
createIntraproceduralExplodedCFGAnalysis(IR ir) {
return createIntraproceduralExplodedCFGAnalysis(DEFAULT_IGNORE_EXCEPTIONS, ir, null, null);
}
public static ExceptionPruningAnalysis<SSAInstruction, IExplodedBasicBlock>
createIntraproceduralExplodedCFGAnalysis(TypeReference[] ignoredExceptions, IR ir) {
return createIntraproceduralExplodedCFGAnalysis(ignoredExceptions, ir, null, null);
}
public static ExceptionPruningAnalysis<SSAInstruction, IExplodedBasicBlock>
createIntraproceduralExplodedCFGAnalysis(
TypeReference[] ignoredExceptions, IR ir, ParameterState paramState, MethodState mState) {
return new ExplodedCFGNullPointerAnalysis(ignoredExceptions, ir, paramState, mState, false);
}
public static ExceptionPruningAnalysis<SSAInstruction, IExplodedBasicBlock>
createIntraproceduralExplodedCFGAnalysis(
TypeReference[] ignoredExceptions,
IR ir,
ParameterState paramState,
MethodState mState,
boolean optHasException) {
return new ExplodedCFGNullPointerAnalysis(
ignoredExceptions, ir, paramState, mState, optHasException);
}
public static ExceptionPruningAnalysis<SSAInstruction, ISSABasicBlock>
createIntraproceduralSSACFGAnalyis(IR ir) {
return createIntraproceduralSSACFGAnalyis(DEFAULT_IGNORE_EXCEPTIONS, ir, null, null);
}
public static ExceptionPruningAnalysis<SSAInstruction, ISSABasicBlock>
createIntraproceduralSSACFGAnalyis(TypeReference[] ignoredExceptions, IR ir) {
return createIntraproceduralSSACFGAnalyis(ignoredExceptions, ir, null, null);
}
public static ExceptionPruningAnalysis<SSAInstruction, ISSABasicBlock>
createIntraproceduralSSACFGAnalyis(
TypeReference[] ignoredExceptions, IR ir, ParameterState paramState, MethodState mState) {
return new SSACFGNullPointerAnalysis(ignoredExceptions, ir, paramState, mState);
}
public static InterprocAnalysisResult<SSAInstruction, IExplodedBasicBlock>
computeInterprocAnalysis(final CallGraph cg, final IProgressMonitor progress)
throws WalaException, UnsoundGraphException, CancelException {
return computeInterprocAnalysis(DEFAULT_IGNORE_EXCEPTIONS, cg, null, progress);
}
public static InterprocAnalysisResult<SSAInstruction, IExplodedBasicBlock>
computeInterprocAnalysis(
final TypeReference[] ignoredExceptions,
final CallGraph cg,
final MethodState defaultExceptionMethodState,
final IProgressMonitor progress)
throws WalaException, UnsoundGraphException, CancelException {
return computeInterprocAnalysis(
ignoredExceptions, cg, defaultExceptionMethodState, progress, false);
}
public static InterprocAnalysisResult<SSAInstruction, IExplodedBasicBlock>
computeInterprocAnalysis(
final TypeReference[] ignoredExceptions,
final CallGraph cg,
final MethodState defaultExceptionMethodState,
final IProgressMonitor progress,
boolean optHasExceptions)
throws WalaException, UnsoundGraphException, CancelException {
final InterprocNullPointerAnalysis inpa =
InterprocNullPointerAnalysis.compute(
ignoredExceptions, cg, defaultExceptionMethodState, progress, optHasExceptions);
return inpa.getResult();
}
}
| 5,150
| 40.878049
| 100
|
java
|
WALA
|
WALA-master/core/src/main/java/com/ibm/wala/cfg/exc/inter/AnalysisUtil.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.cfg.exc.inter;
import com.ibm.wala.cfg.ControlFlowGraph;
import com.ibm.wala.ipa.callgraph.CGNode;
import com.ibm.wala.ipa.callgraph.CallGraph;
import com.ibm.wala.ssa.SSAAbstractInvokeInstruction;
import com.ibm.wala.ssa.SSAInstruction;
import com.ibm.wala.ssa.analysis.IExplodedBasicBlock;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
/**
* Utility class for the exception pruning analysis.
*
* <p>This class has been developed as part of a student project "Studienarbeit" by Markus
* Herhoffer. It has been adapted and integrated into the WALA project by Juergen Graf.
*
* @author Markus Herhoffer <markus.herhoffer@student.kit.edu>
* @author Juergen Graf <graf@kit.edu>
*/
public final class AnalysisUtil {
private AnalysisUtil() {
throw new IllegalStateException("No instances of this class allowed.");
}
/**
* Checks if a node is FakeRoot
*
* @param node the node to check
* @return true if node is FakeRoot
*/
public static boolean isFakeRoot(CallGraph CG, CGNode node) {
return node.equals(CG.getFakeRootNode());
}
/**
* Returns an array of {@code int} with the parameter's var nums of the invoked method in {@code
* invokeInstruction}.
*
* @param invokeInstruction The instruction that invokes the method.
* @return an array of {@code int} with all parameter's var nums including the this pointer.
*/
public static int[] getParameterNumbers(SSAAbstractInvokeInstruction invokeInstruction) {
final int number = invokeInstruction.getNumberOfPositionalParameters();
final int[] parameterNumbers = new int[number];
assert (parameterNumbers.length == invokeInstruction.getNumberOfUses());
Arrays.setAll(parameterNumbers, invokeInstruction::getUse);
return parameterNumbers;
}
/**
* Returns a Set of all blocks that invoke another method.
*
* @param cfg The Control Flow Graph to analyze
* @return a Set of all blocks that contain an invoke
*/
public static Set<IExplodedBasicBlock> extractInvokeBlocks(
final ControlFlowGraph<SSAInstruction, IExplodedBasicBlock> cfg) {
final HashSet<IExplodedBasicBlock> invokeBlocks = new HashSet<>();
for (final IExplodedBasicBlock block : cfg) {
if (block.getInstruction() instanceof SSAAbstractInvokeInstruction) {
invokeBlocks.add(block);
}
}
return invokeBlocks;
}
}
| 2,806
| 32.023529
| 98
|
java
|
WALA
|
WALA-master/core/src/main/java/com/ibm/wala/cfg/exc/inter/DelegatingMethodState.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.cfg.exc.inter;
import com.ibm.wala.cfg.exc.intra.MethodState;
import com.ibm.wala.ssa.SSAAbstractInvokeInstruction;
/**
* A delegating MethodState for the interprocedural analysis.
*
* <p>This class combines two MethodState objects. A MethodState decides if a given method call may
* throw an exception. If the primary MethodState thinks that the call may throw an exception, the
* fallback MethodState is asked.
*
* @author Juergen Graf <graf@kit.edu>
*/
class DelegatingMethodState extends MethodState {
private final MethodState primary;
private final MethodState fallback;
DelegatingMethodState(final MethodState primary, final MethodState fallback) {
if (primary == null) {
throw new IllegalArgumentException("primary method state is null.");
} else if (fallback == null) {
throw new IllegalArgumentException("fallback method state is null.");
}
this.primary = primary;
this.fallback = fallback;
}
@Override
public boolean throwsException(final SSAAbstractInvokeInstruction node) {
if (primary.throwsException(node)) {
return fallback.throwsException(node);
}
return false;
}
}
| 1,557
| 30.16
| 99
|
java
|
WALA
|
WALA-master/core/src/main/java/com/ibm/wala/cfg/exc/inter/InterprocAnalysisResultWrapper.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.cfg.exc.inter;
import com.ibm.wala.cfg.exc.ExceptionPruningAnalysis;
import com.ibm.wala.cfg.exc.InterprocAnalysisResult;
import com.ibm.wala.ipa.callgraph.CGNode;
import com.ibm.wala.ssa.SSAInstruction;
import com.ibm.wala.ssa.analysis.IExplodedBasicBlock;
import java.util.Map;
import java.util.Map.Entry;
/**
* A wrapper for the interprocedural analysis result.
*
* @author Juergen Graf <graf@kit.edu>
*/
class InterprocAnalysisResultWrapper
implements InterprocAnalysisResult<SSAInstruction, IExplodedBasicBlock> {
private final Map<CGNode, IntraprocAnalysisState> map;
InterprocAnalysisResultWrapper(final Map<CGNode, IntraprocAnalysisState> map) {
if (map == null) {
throw new IllegalArgumentException();
}
this.map = map;
}
@Override
public ExceptionPruningAnalysis<SSAInstruction, IExplodedBasicBlock> getResult(final CGNode n) {
if (!containsResult(n)) {
return null;
}
return map.get(n);
}
@Override
public boolean containsResult(final CGNode n) {
return map.containsKey(n) && map.get(n).canBeAnalyzed();
}
@Override
public String toString() {
final StringBuilder sb = new StringBuilder();
for (final Entry<CGNode, IntraprocAnalysisState> e : map.entrySet()) {
sb.append(e.getValue().hasExceptions() ? "THROWS " : "CLEAN ");
sb.append(e.getKey().toString()).append('\n');
}
return sb.toString();
}
}
| 1,825
| 26.666667
| 98
|
java
|
WALA
|
WALA-master/core/src/main/java/com/ibm/wala/cfg/exc/inter/InterprocMethodState.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.cfg.exc.inter;
import com.ibm.wala.cfg.exc.intra.MethodState;
import com.ibm.wala.ipa.callgraph.CGNode;
import com.ibm.wala.ipa.callgraph.CallGraph;
import com.ibm.wala.ssa.SSAAbstractInvokeInstruction;
import java.util.Map;
/**
* A MethodState for the interprocedural analysis.
*
* <p>This class has been developed as part of a student project "Studienarbeit" by Markus
* Herhoffer. It has been adapted and integrated into the WALA project by Juergen Graf.
*
* @author Markus Herhoffer <markus.herhoffer@student.kit.edu>
* @author Juergen Graf <graf@kit.edu>
*/
class InterprocMethodState extends MethodState {
private final Map<CGNode, IntraprocAnalysisState> map;
private final CGNode method;
private final CallGraph cg;
InterprocMethodState(
final CGNode method, final CallGraph cg, final Map<CGNode, IntraprocAnalysisState> map) {
this.map = map;
this.method = method;
this.cg = cg;
}
/*
* (non-Javadoc)
*
* @see edu.kit.ipd.wala.intra.MethodState#throwsException(com.ibm.wala.ipa.callgraph.CGNode)
*/
@Override
public boolean throwsException(final SSAAbstractInvokeInstruction node) {
for (final CGNode called : cg.getPossibleTargets(method, node.getCallSite())) {
final IntraprocAnalysisState info = map.get(called);
if (info == null || info.hasExceptions()) {
return true;
}
}
return false;
}
}
| 1,813
| 29.233333
| 95
|
java
|
WALA
|
WALA-master/core/src/main/java/com/ibm/wala/cfg/exc/inter/InterprocNullPointerAnalysis.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.cfg.exc.inter;
import com.ibm.wala.cfg.ControlFlowGraph;
import com.ibm.wala.cfg.exc.ExceptionPruningAnalysis;
import com.ibm.wala.cfg.exc.InterprocAnalysisResult;
import com.ibm.wala.cfg.exc.NullPointerAnalysis;
import com.ibm.wala.cfg.exc.intra.MethodState;
import com.ibm.wala.cfg.exc.intra.NullPointerState;
import com.ibm.wala.cfg.exc.intra.NullPointerState.State;
import com.ibm.wala.cfg.exc.intra.ParameterState;
import com.ibm.wala.core.util.strings.Atom;
import com.ibm.wala.ipa.callgraph.CGNode;
import com.ibm.wala.ipa.callgraph.CallGraph;
import com.ibm.wala.ipa.callgraph.impl.PartialCallGraph;
import com.ibm.wala.ssa.IR;
import com.ibm.wala.ssa.SSAAbstractInvokeInstruction;
import com.ibm.wala.ssa.SSAInstruction;
import com.ibm.wala.ssa.analysis.IExplodedBasicBlock;
import com.ibm.wala.types.MethodReference;
import com.ibm.wala.types.TypeReference;
import com.ibm.wala.util.CancelException;
import com.ibm.wala.util.MonitorUtil;
import com.ibm.wala.util.MonitorUtil.IProgressMonitor;
import com.ibm.wala.util.WalaException;
import com.ibm.wala.util.graph.GraphIntegrity.UnsoundGraphException;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
/**
* Interprocedural NullPointer Analysis.
*
* <p>The interprocedural NullPointer analysis builds an implicit ICFG, visits all CFGs in reverse
* invocation order recursively and propagates all parameter states.
*
* <p>1st run: collect and propagate all parameters on ENTRY nodes. 2nd run: collect the results on
* the ENTRY nodes.
*
* <p>This class has been developed as part of a student project "Studienarbeit" by Markus
* Herhoffer. It has been adapted and integrated into the WALA project by Juergen Graf.
*
* @author Markus Herhoffer <markus.herhoffer@student.kit.edu>
* @author Juergen Graf <graf@kit.edu>
*/
public final class InterprocNullPointerAnalysis {
private CallGraph cgFiltered = null;
private final TypeReference[] ignoredExceptions;
private final MethodState defaultMethodState;
private final Map<CGNode, IntraprocAnalysisState> states;
private final boolean optHasExceptions;
private CallGraph cg;
public static InterprocNullPointerAnalysis compute(
final TypeReference[] ignoredExceptions,
final CallGraph cg,
final MethodState defaultMethodState,
final IProgressMonitor progress,
boolean optHasExceptions)
throws WalaException, UnsoundGraphException, CancelException {
final InterprocNullPointerAnalysis inpa =
new InterprocNullPointerAnalysis(ignoredExceptions, defaultMethodState, optHasExceptions);
inpa.run(cg, progress);
return inpa;
}
private InterprocNullPointerAnalysis(
final TypeReference[] ignoredExceptions,
final MethodState defaultMethodState,
boolean optHasExceptions) {
this.ignoredExceptions = ignoredExceptions;
this.defaultMethodState = defaultMethodState;
this.states = new HashMap<>();
this.optHasExceptions = optHasExceptions;
}
private void run(final CallGraph cg, final IProgressMonitor progress)
throws WalaException, UnsoundGraphException, CancelException {
if (this.cgFiltered != null) {
throw new IllegalStateException("This analysis has already been computed.");
}
// we filter out everything we do not need now
this.cg = cg;
this.cgFiltered = computeFilteredCallgraph(cg);
// we start with the first node
final CGNode firstNode = cgFiltered.getNode(0);
findAndInjectInvokes(firstNode, new ParameterState(), new HashSet<>(), progress);
}
/**
* Finds all invokes in a given {@code startNode} and traverses als successors recursively.
*
* @param startNode The node to start
* @param paramState The parameter states of the {@code startNode}. May be {@code null}
*/
private void findAndInjectInvokes(
final CGNode startNode,
final ParameterState paramState,
final Set<CGNode> visited,
final IProgressMonitor progress)
throws UnsoundGraphException, CancelException, WalaException {
assert paramState != null;
if (!visited.add(startNode)) {
return;
}
MonitorUtil.throwExceptionIfCanceled(progress);
final Map<CGNode, Map<SSAAbstractInvokeInstruction, ParameterState>> firstPass =
analysisFirstPass(startNode, paramState, progress);
// visit every invoked invoke
for (final Entry<CGNode, Map<SSAAbstractInvokeInstruction, ParameterState>> nodeEntry :
firstPass.entrySet()) {
MonitorUtil.throwExceptionIfCanceled(progress);
final CGNode node = nodeEntry.getKey();
final Map<SSAAbstractInvokeInstruction, ParameterState> invokes = nodeEntry.getValue();
for (final Entry<SSAAbstractInvokeInstruction, ParameterState> instructionEntry :
invokes.entrySet()) {
findAndInjectInvokes(node, instructionEntry.getValue(), visited, progress);
}
}
MonitorUtil.throwExceptionIfCanceled(progress);
analysisSecondPass(startNode, paramState, progress);
}
private void analysisSecondPass(
final CGNode startNode, final ParameterState paramState, final IProgressMonitor progress)
throws UnsoundGraphException, CancelException {
final IR ir = startNode.getIR();
if (!AnalysisUtil.isFakeRoot(cg, startNode) && !(ir == null || ir.isEmptyIR())) {
final MethodState ims = new InterprocMethodState(startNode, cgFiltered, states);
final MethodState mState =
(defaultMethodState != null ? new DelegatingMethodState(defaultMethodState, ims) : ims);
// run intraprocedural part again with invoke exception info
final ExceptionPruningAnalysis<SSAInstruction, IExplodedBasicBlock> intra2 =
NullPointerAnalysis.createIntraproceduralExplodedCFGAnalysis(
ignoredExceptions, ir, paramState, mState, optHasExceptions);
final int deletedEdges2 = intra2.compute(progress);
final ControlFlowGraph<SSAInstruction, IExplodedBasicBlock> cfg2 = intra2.getCFG();
final IntraprocAnalysisState singleState1 = states.get(startNode);
final int deletedEdges1 = singleState1.compute(progress);
final IntraprocAnalysisState singleState2 =
new IntraprocAnalysisState(intra2, startNode, cfg2, deletedEdges2 + deletedEdges1);
singleState2.setHasExceptions(intra2.hasExceptions());
states.put(startNode, singleState2);
}
}
private Map<CGNode, Map<SSAAbstractInvokeInstruction, ParameterState>> analysisFirstPass(
final CGNode startNode, final ParameterState paramState, final IProgressMonitor progress)
throws UnsoundGraphException, CancelException {
final Map<CGNode, Map<SSAAbstractInvokeInstruction, ParameterState>> result = new HashMap<>();
final IR ir = startNode.getIR();
if (!startNode.getMethod().isStatic()) {
// this pointer is never null
paramState.setState(0, State.NOT_NULL);
}
if (ir == null || ir.isEmptyIR()) {
// we have nothing to tell about the empty IR
states.put(startNode, new IntraprocAnalysisState());
} else {
final ExceptionPruningAnalysis<SSAInstruction, IExplodedBasicBlock> intra =
NullPointerAnalysis.createIntraproceduralExplodedCFGAnalysis(
ignoredExceptions, ir, paramState, defaultMethodState, optHasExceptions);
final int deletedEdges = intra.compute(progress);
// Analyze the method with intraprocedural scope
final ControlFlowGraph<SSAInstruction, IExplodedBasicBlock> cfg = intra.getCFG();
final IntraprocAnalysisState info =
new IntraprocAnalysisState(intra, startNode, cfg, deletedEdges);
info.setHasExceptions(intra.hasExceptions());
states.put(startNode, info);
// get the parameter's state out of the invoke block and collect them
final Set<IExplodedBasicBlock> invokeBlocks = AnalysisUtil.extractInvokeBlocks(cfg);
for (final IExplodedBasicBlock invokeBlock : invokeBlocks) {
final NullPointerState state = intra.getState(invokeBlock);
final SSAAbstractInvokeInstruction invokeInstruction =
(SSAAbstractInvokeInstruction) invokeBlock.getInstruction();
final int[] parameterNumbers = AnalysisUtil.getParameterNumbers(invokeInstruction);
final ParameterState paramStateOfInvokeBlock = new ParameterState(state, parameterNumbers);
final Set<CGNode> targets =
cgFiltered.getPossibleTargets(startNode, invokeInstruction.getCallSite());
for (final CGNode target : targets) {
final HashMap<SSAAbstractInvokeInstruction, ParameterState> stateMap = new HashMap<>();
stateMap.put(invokeInstruction, paramStateOfInvokeBlock);
result.put(target, stateMap);
}
}
}
return result;
}
/**
* Returns the result of the interprocedural analysis.
*
* @return Result of the interprocedural analysis.
*/
public InterprocAnalysisResult<SSAInstruction, IExplodedBasicBlock> getResult() {
return new InterprocAnalysisResultWrapper(states);
}
/** Reduces the Callgraph to only the nodes that we need */
private static CallGraph computeFilteredCallgraph(final CallGraph cg) {
final HashSet<Atom> filterSet = new HashSet<>();
final Atom worldClinit = Atom.findOrCreateAsciiAtom("fakeWorldClinit");
filterSet.add(worldClinit);
filterSet.add(MethodReference.initAtom);
final CallGraphFilter filter = new CallGraphFilter(filterSet);
return filter.filter(cg);
}
/**
* Filter for CallGraphs
*
* @author Markus Herhoffer <markus.herhoffer@student.kit.edu>
*/
private static class CallGraphFilter {
private final Set<Atom> filter;
/**
* Filter for CallGraphs
*
* @param filterSet the MethodReferences to be filtered out
*/
private CallGraphFilter(HashSet<Atom> filterSet) {
this.filter = filterSet;
}
/**
* filters a CallGraph
*
* @param fullCG the original unfiltered CallGraph
* @return the filtered CallGraph
*/
private CallGraph filter(final CallGraph fullCG) {
// collect nodes not named for exclusion
final HashSet<CGNode> nodes = new HashSet<>();
fullCG.forEach(
node -> {
if (!filter.contains(node.getMethod().getName())) nodes.add(node);
});
final Set<CGNode> partialRoots = Collections.singleton(fullCG.getFakeRootNode());
// delete the nodes
final PartialCallGraph partialCG1 = PartialCallGraph.make(fullCG, partialRoots, nodes);
// delete the nodes not reachable by root (consider the different implementations of "make")
final PartialCallGraph partialCG2 = PartialCallGraph.make(partialCG1, partialRoots);
return partialCG2;
}
}
}
| 11,249
| 38.335664
| 99
|
java
|
WALA
|
WALA-master/core/src/main/java/com/ibm/wala/cfg/exc/inter/IntraprocAnalysisState.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.cfg.exc.inter;
import com.ibm.wala.cfg.ControlFlowGraph;
import com.ibm.wala.cfg.exc.ExceptionPruningAnalysis;
import com.ibm.wala.cfg.exc.intra.NullPointerState;
import com.ibm.wala.ipa.callgraph.CGNode;
import com.ibm.wala.ssa.SSAAbstractInvokeInstruction;
import com.ibm.wala.ssa.SSAInstruction;
import com.ibm.wala.ssa.SymbolTable;
import com.ibm.wala.ssa.analysis.IExplodedBasicBlock;
import com.ibm.wala.util.CancelException;
import com.ibm.wala.util.MonitorUtil.IProgressMonitor;
import com.ibm.wala.util.graph.GraphIntegrity.UnsoundGraphException;
import java.util.HashMap;
/**
* Saves interprocedural state of a single method.
*
* <p>This class has been developed as part of a student project "Studienarbeit" by Markus
* Herhoffer. It has been adapted and integrated into the WALA project by Juergen Graf.
*
* @author Markus Herhoffer <markus.herhoffer@student.kit.edu>
* @author Juergen Graf <graf@kit.edu>
*/
final class IntraprocAnalysisState
implements ExceptionPruningAnalysis<SSAInstruction, IExplodedBasicBlock> {
private final ControlFlowGraph<SSAInstruction, IExplodedBasicBlock> cfg;
private final HashMap<IExplodedBasicBlock, NullPointerState> statesOfSsaVars = new HashMap<>();
private final HashMap<IExplodedBasicBlock, Object[]> valuesOfSsaVars = new HashMap<>();
private final HashMap<IExplodedBasicBlock, int[]> numbersOfSsaVarsThatAreParemerters =
new HashMap<>();
private final boolean noAnalysisPossible;
private final int deletedEdges;
private boolean throwsException = true;
/**
* Constructor for the state of a method that has not been analyzed. These are methods with an
* empty IR or methods left out explicitly.
*
* <p>Use it if you have nothing to tell about the node.
*/
IntraprocAnalysisState() {
this.cfg = null;
this.noAnalysisPossible = true;
this.deletedEdges = 0;
}
/**
* Constructor if you have informations on the node.
*
* <p>All values are saved at construction time. So if the analysis changes anything after this
* OptimizationInfo was created, it won't affect its final attributes.
*
* @param intra The {@code node}'s intraprocedural analysis
* @param node the node itself
*/
IntraprocAnalysisState(
final ExceptionPruningAnalysis<SSAInstruction, IExplodedBasicBlock> intra,
final CGNode node,
final ControlFlowGraph<SSAInstruction, IExplodedBasicBlock> cfg,
final int deletedEdges) {
this.cfg = cfg;
this.noAnalysisPossible = false;
this.deletedEdges = deletedEdges;
final SymbolTable sym = node.getIR().getSymbolTable();
for (final IExplodedBasicBlock block : cfg) {
// set states
final NullPointerState state = intra.getState(block);
this.statesOfSsaVars.put(block, state);
// set values
if (block.getInstruction() != null) {
final int numberOfSSAVars = block.getInstruction().getNumberOfUses();
final Object[] values = new Object[numberOfSSAVars];
for (int j = 0; j < numberOfSSAVars; j++) {
final boolean isContant = sym.isConstant(j);
values[j] = (isContant ? sym.getConstantValue(j) : null);
}
this.valuesOfSsaVars.put(block, values);
} else {
this.valuesOfSsaVars.put(block, null);
}
// set nr. of parameters
if (block.getInstruction() instanceof SSAAbstractInvokeInstruction) {
final SSAAbstractInvokeInstruction instr =
(SSAAbstractInvokeInstruction) block.getInstruction();
final int[] numbersOfParams = AnalysisUtil.getParameterNumbers(instr);
this.numbersOfSsaVarsThatAreParemerters.put(block, numbersOfParams);
} else {
// default to null
this.numbersOfSsaVarsThatAreParemerters.put(block, null);
}
}
}
@Override
public int compute(IProgressMonitor progress) throws UnsoundGraphException, CancelException {
return deletedEdges;
}
@Override
public NullPointerState getState(final IExplodedBasicBlock block) {
if (noAnalysisPossible) {
throw new IllegalStateException();
}
return statesOfSsaVars.get(block);
}
public Object[] getValues(final IExplodedBasicBlock block) {
if (noAnalysisPossible) {
throw new IllegalStateException();
}
return valuesOfSsaVars.get(block);
}
public int[] getInjectedParameters(final IExplodedBasicBlock block) {
if (noAnalysisPossible) {
throw new IllegalStateException();
} else if (!(block.getInstruction() instanceof SSAAbstractInvokeInstruction)) {
throw new IllegalArgumentException();
}
assert (block.getInstruction() instanceof SSAAbstractInvokeInstruction);
return numbersOfSsaVarsThatAreParemerters.get(block);
}
/**
* Returns the CFG.
*
* @return the CFG or null if there is no CFG for the CGNode.
*/
@Override
public ControlFlowGraph<SSAInstruction, IExplodedBasicBlock> getCFG() {
return (noAnalysisPossible ? null : this.cfg);
}
public boolean canBeAnalyzed() {
return !noAnalysisPossible;
}
public void setHasExceptions(final boolean throwsException) {
this.throwsException = throwsException;
}
@Override
public boolean hasExceptions() {
return throwsException;
}
@Override
public String toString() {
if (noAnalysisPossible) {
return "";
}
final String ls = System.getProperty("line.separator");
return statesOfSsaVars + ls + valuesOfSsaVars + ls + numbersOfSsaVarsThatAreParemerters;
}
}
| 5,926
| 31.927778
| 97
|
java
|
WALA
|
WALA-master/core/src/main/java/com/ibm/wala/cfg/exc/intra/ExplodedCFGNullPointerAnalysis.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.cfg.exc.intra;
import com.ibm.wala.cfg.ControlFlowGraph;
import com.ibm.wala.cfg.exc.ExceptionPruningAnalysis;
import com.ibm.wala.ssa.IR;
import com.ibm.wala.ssa.SSAInstruction;
import com.ibm.wala.ssa.analysis.ExplodedControlFlowGraph;
import com.ibm.wala.ssa.analysis.IExplodedBasicBlock;
import com.ibm.wala.types.TypeReference;
import com.ibm.wala.util.CancelException;
import com.ibm.wala.util.MonitorUtil.IProgressMonitor;
import com.ibm.wala.util.graph.GraphIntegrity.UnsoundGraphException;
import java.util.List;
/**
* Intraprocedural null pointer analysis for the exploded control flow graph.
*
* @author Juergen Graf <graf@kit.edu>
*/
public class ExplodedCFGNullPointerAnalysis
implements ExceptionPruningAnalysis<SSAInstruction, IExplodedBasicBlock> {
private final TypeReference[] ignoredExceptions;
private IntraprocNullPointerAnalysis<IExplodedBasicBlock> intra;
private final IR ir;
private final ParameterState initialState;
private final MethodState mState;
private final boolean optHasExceptions;
public ExplodedCFGNullPointerAnalysis(
TypeReference[] ignoredExceptions,
IR ir,
ParameterState paramState,
MethodState mState,
boolean optHasExceptions) {
this.ignoredExceptions = (ignoredExceptions != null ? ignoredExceptions.clone() : null);
this.ir = ir;
this.initialState =
(paramState == null ? ParameterState.createDefault(ir.getMethod()) : paramState);
this.mState = (mState == null ? MethodState.DEFAULT : mState);
this.optHasExceptions = optHasExceptions;
}
@Override
public int compute(IProgressMonitor progress) throws UnsoundGraphException, CancelException {
ControlFlowGraph<SSAInstruction, IExplodedBasicBlock> orig = ExplodedControlFlowGraph.make(ir);
intra = new IntraprocNullPointerAnalysis<>(ir, orig, ignoredExceptions, initialState, mState);
intra.run(progress);
return intra.getNumberOfDeletedEdges();
}
/* (non-Javadoc)
* @see jsdg.exceptions.ExceptionPrunedCFGAnalysis#getCFG()
*/
@Override
public ControlFlowGraph<SSAInstruction, IExplodedBasicBlock> getCFG() {
if (intra == null) {
throw new IllegalStateException("Run compute(IProgressMonitor) first.");
}
return intra.getPrunedCFG();
}
/* (non-Javadoc)
* @see edu.kit.ipd.wala.ExceptionPrunedCFGAnalysis#hasExceptions()
*/
@Override
public boolean hasExceptions() {
if (intra == null) {
throw new IllegalStateException("Run compute(IProgressMonitor) first.");
}
ControlFlowGraph<SSAInstruction, IExplodedBasicBlock> cfg = intra.getPrunedCFG();
boolean hasException = false;
for (IExplodedBasicBlock bb : cfg) {
if (bb.getInstruction() == null) continue;
List<IExplodedBasicBlock> succ = cfg.getExceptionalSuccessors(bb);
if (succ != null && !succ.isEmpty() && (!optHasExceptions || succ.contains(cfg.exit()))) {
hasException = true;
break;
}
}
return hasException;
}
@Override
public NullPointerState getState(IExplodedBasicBlock bb) {
if (intra == null) {
throw new IllegalStateException("Run compute(IProgressMonitor) first.");
}
return intra.getState(bb);
}
}
| 3,624
| 31.954545
| 99
|
java
|
WALA
|
WALA-master/core/src/main/java/com/ibm/wala/cfg/exc/intra/IntraprocNullPointerAnalysis.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.cfg.exc.intra;
import com.ibm.wala.cfg.ControlFlowGraph;
import com.ibm.wala.ipa.cfg.PrunedCFG;
import com.ibm.wala.ssa.IR;
import com.ibm.wala.ssa.ISSABasicBlock;
import com.ibm.wala.ssa.SSAAbstractInvokeInstruction;
import com.ibm.wala.ssa.SSAArrayLengthInstruction;
import com.ibm.wala.ssa.SSAArrayLoadInstruction;
import com.ibm.wala.ssa.SSAArrayStoreInstruction;
import com.ibm.wala.ssa.SSABinaryOpInstruction;
import com.ibm.wala.ssa.SSACheckCastInstruction;
import com.ibm.wala.ssa.SSAComparisonInstruction;
import com.ibm.wala.ssa.SSAConditionalBranchInstruction;
import com.ibm.wala.ssa.SSAConversionInstruction;
import com.ibm.wala.ssa.SSAGetCaughtExceptionInstruction;
import com.ibm.wala.ssa.SSAGetInstruction;
import com.ibm.wala.ssa.SSAGotoInstruction;
import com.ibm.wala.ssa.SSAInstanceofInstruction;
import com.ibm.wala.ssa.SSAInstruction;
import com.ibm.wala.ssa.SSAInstruction.IVisitor;
import com.ibm.wala.ssa.SSAInvokeInstruction;
import com.ibm.wala.ssa.SSALoadMetadataInstruction;
import com.ibm.wala.ssa.SSAMonitorInstruction;
import com.ibm.wala.ssa.SSANewInstruction;
import com.ibm.wala.ssa.SSAPhiInstruction;
import com.ibm.wala.ssa.SSAPiInstruction;
import com.ibm.wala.ssa.SSAPutInstruction;
import com.ibm.wala.ssa.SSAReturnInstruction;
import com.ibm.wala.ssa.SSASwitchInstruction;
import com.ibm.wala.ssa.SSAThrowInstruction;
import com.ibm.wala.ssa.SSAUnaryOpInstruction;
import com.ibm.wala.types.TypeReference;
import com.ibm.wala.util.CancelException;
import com.ibm.wala.util.MonitorUtil.IProgressMonitor;
import com.ibm.wala.util.graph.Graph;
import com.ibm.wala.util.graph.impl.SparseNumberedGraph;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
/**
* Intraprocedural dataflow analysis to detect impossible NullPointerExceptions.
*
* @author Juergen Graf <graf@kit.edu>
*/
public class IntraprocNullPointerAnalysis<T extends ISSABasicBlock> {
private NullPointerSolver<T> solver;
private final Set<TypeReference> ignoreExceptions;
private final IR ir;
private final ControlFlowGraph<SSAInstruction, T> cfg;
private final int maxVarNum;
private int deletedEdges;
private ControlFlowGraph<SSAInstruction, T> pruned = null;
private final ParameterState initialState;
private final MethodState mState;
IntraprocNullPointerAnalysis(
IR ir,
ControlFlowGraph<SSAInstruction, T> cfg,
TypeReference[] ignoreExceptions,
ParameterState initialState,
MethodState mState) {
this.cfg = cfg;
this.ir = ir;
if (ir == null || ir.isEmptyIR()) {
maxVarNum = -1;
} else {
maxVarNum = ir.getSymbolTable().getMaxValueNumber();
}
this.ignoreExceptions = new HashSet<>();
if (ignoreExceptions != null) {
this.ignoreExceptions.addAll(Arrays.asList(ignoreExceptions));
}
this.initialState = initialState;
this.mState = mState;
}
private static <T extends ISSABasicBlock> List<T> searchNodesWithPathToCatchAll(
ControlFlowGraph<SSAInstruction, T> cfg) {
final List<T> nodes = new ArrayList<>();
for (final T exp : cfg) {
final List<T> excSucc = cfg.getExceptionalSuccessors(exp);
if (excSucc != null && excSucc.size() > 1) {
boolean foundExit = false;
boolean foundCatchAll = false;
for (final T succ : excSucc) {
if (succ.isExitBlock()) {
foundExit = true;
} else if (succ.isCatchBlock()) {
final Iterator<TypeReference> caught = succ.getCaughtExceptionTypes();
while (caught.hasNext()) {
final TypeReference t = caught.next();
if (t.equals(TypeReference.JavaLangException)
|| t.equals(TypeReference.JavaLangThrowable)) {
foundCatchAll = true;
}
}
}
}
if (foundExit && foundCatchAll) {
nodes.add(exp);
}
}
}
return nodes;
}
void run(IProgressMonitor progress) throws CancelException {
if (pruned == null) {
if (ir == null || ir.isEmptyIR()) {
pruned = cfg;
} else {
final List<T> catched = searchNodesWithPathToCatchAll(cfg);
final NullPointerFrameWork<T> problem = new NullPointerFrameWork<>(cfg, ir);
solver = new NullPointerSolver<>(problem, maxVarNum, cfg.entry(), ir, initialState);
solver.solve(progress);
final Graph<T> deleted = createDeletedGraph();
for (final T ch : catched) {
deleted.addNode(ch);
deleted.addNode(cfg.exit());
deleted.addEdge(ch, cfg.exit());
}
for (T node : deleted) {
deletedEdges += deleted.getSuccNodeCount(node);
}
final NegativeGraphFilter<T> filter = new NegativeGraphFilter<>(deleted);
final PrunedCFG<SSAInstruction, T> newCfg = PrunedCFG.make(cfg, filter);
pruned = newCfg;
}
}
}
private Graph<T> createDeletedGraph() {
NegativeCFGBuilderVisitor nCFGbuilder = new NegativeCFGBuilderVisitor();
for (T bb : cfg) {
nCFGbuilder.work(bb);
}
Graph<T> deleted = nCFGbuilder.getNegativeCFG();
return deleted;
}
ControlFlowGraph<SSAInstruction, T> getPrunedCFG() {
if (pruned == null) {
throw new IllegalStateException("Run analysis first! (call run())");
}
return pruned;
}
int getNumberOfDeletedEdges() {
if (pruned == null) {
throw new IllegalStateException("Run analysis first! (call run())");
}
return deletedEdges;
}
public NullPointerState getState(T block) {
assert pruned != null || solver != null
: "No solver initialized for method " + ir.getMethod().toString();
if (pruned != null && solver == null) {
// empty IR ... so states have not changed and we can return the initial state as a save
// approximation
return new NullPointerState(maxVarNum, ir.getSymbolTable(), initialState);
} else {
return solver.getOut(block);
}
}
private class NegativeCFGBuilderVisitor implements IVisitor {
private final Graph<T> deleted;
private NegativeCFGBuilderVisitor() {
this.deleted = new SparseNumberedGraph<>(2);
for (T bb : cfg) {
deleted.addNode(bb);
}
}
private NullPointerState currentState;
private T currentBlock;
public void work(T bb) {
if (bb == null) {
throw new IllegalArgumentException("Null not allowed");
} else if (!cfg.containsNode(bb)) {
throw new IllegalArgumentException("Block not part of current CFG");
}
SSAInstruction instr = NullPointerTransferFunctionProvider.getRelevantInstruction(bb);
if (instr != null) {
currentState = getState(bb);
currentBlock = bb;
instr.visit(this);
currentState = null;
currentBlock = null;
}
}
public Graph<T> getNegativeCFG() {
return deleted;
}
/**
* We have to be careful here. If the invoke instruction can not throw a NullPointerException,
* because the reference object is not null, the method itself may throw a NullPointerException.
* So we can only remove the edge if the method itself throws no exception.
*/
private boolean isOnlyNullPointerExc(SSAInstruction instr) {
assert instr.isPEI();
if (instr instanceof SSAAbstractInvokeInstruction) {
return mState != null && !mState.throwsException((SSAAbstractInvokeInstruction) instr);
} else {
Collection<TypeReference> exc = instr.getExceptionTypes();
Set<TypeReference> myExcs = new HashSet<>(exc);
myExcs.removeAll(ignoreExceptions);
return myExcs.size() == 1 && myExcs.contains(TypeReference.JavaLangNullPointerException);
}
}
private boolean noExceptions(SSAInstruction instr) {
assert instr.isPEI();
if (instr instanceof SSAAbstractInvokeInstruction) {
assert ((SSAAbstractInvokeInstruction) instr).isStatic();
return mState != null && !mState.throwsException((SSAAbstractInvokeInstruction) instr);
} else {
Collection<TypeReference> exc = instr.getExceptionTypes();
Set<TypeReference> myExcs = new HashSet<>(exc);
myExcs.removeAll(ignoreExceptions);
return myExcs.isEmpty();
}
}
private void removeImpossibleSuccessors(SSAInstruction instr, int varNum) {
if (isOnlyNullPointerExc(instr)) {
if (currentState.isNeverNull(varNum)) {
for (T succ : cfg.getExceptionalSuccessors(currentBlock)) {
deleted.addEdge(currentBlock, succ);
}
} else if (currentState.isAlwaysNull(varNum)) {
for (T succ : cfg.getNormalSuccessors(currentBlock)) {
deleted.addEdge(currentBlock, succ);
}
}
}
}
private void removeImpossibleSuccessors(SSAInstruction instr) {
if (noExceptions(instr)) {
for (T succ : cfg.getExceptionalSuccessors(currentBlock)) {
deleted.addEdge(currentBlock, succ);
}
}
}
/* (non-Javadoc)
* @see com.ibm.wala.ssa.SSAInstruction.IVisitor#visitArrayLength(com.ibm.wala.ssa.SSAArrayLengthInstruction)
*/
@Override
public void visitArrayLength(SSAArrayLengthInstruction instruction) {
int varNum = instruction.getArrayRef();
removeImpossibleSuccessors(instruction, varNum);
}
/* (non-Javadoc)
* @see com.ibm.wala.ssa.SSAInstruction.IVisitor#visitArrayLoad(com.ibm.wala.ssa.SSAArrayLoadInstruction)
*/
@Override
public void visitArrayLoad(SSAArrayLoadInstruction instruction) {
int varNum = instruction.getArrayRef();
removeImpossibleSuccessors(instruction, varNum);
}
/* (non-Javadoc)
* @see com.ibm.wala.ssa.SSAInstruction.IVisitor#visitArrayStore(com.ibm.wala.ssa.SSAArrayStoreInstruction)
*/
@Override
public void visitArrayStore(SSAArrayStoreInstruction instruction) {
int varNum = instruction.getArrayRef();
removeImpossibleSuccessors(instruction, varNum);
}
/* (non-Javadoc)
* @see com.ibm.wala.ssa.SSAInstruction.IVisitor#visitBinaryOp(com.ibm.wala.ssa.SSABinaryOpInstruction)
*/
@Override
public void visitBinaryOp(SSABinaryOpInstruction instruction) {}
/* (non-Javadoc)
* @see com.ibm.wala.ssa.SSAInstruction.IVisitor#visitCheckCast(com.ibm.wala.ssa.SSACheckCastInstruction)
*/
@Override
public void visitCheckCast(SSACheckCastInstruction instruction) {}
/* (non-Javadoc)
* @see com.ibm.wala.ssa.SSAInstruction.IVisitor#visitComparison(com.ibm.wala.ssa.SSAComparisonInstruction)
*/
@Override
public void visitComparison(SSAComparisonInstruction instruction) {}
/* (non-Javadoc)
* @see com.ibm.wala.ssa.SSAInstruction.IVisitor#visitConditionalBranch(com.ibm.wala.ssa.SSAConditionalBranchInstruction)
*/
@Override
public void visitConditionalBranch(SSAConditionalBranchInstruction instruction) {}
/* (non-Javadoc)
* @see com.ibm.wala.ssa.SSAInstruction.IVisitor#visitConversion(com.ibm.wala.ssa.SSAConversionInstruction)
*/
@Override
public void visitConversion(SSAConversionInstruction instruction) {}
/* (non-Javadoc)
* @see com.ibm.wala.ssa.SSAInstruction.IVisitor#visitGet(com.ibm.wala.ssa.SSAGetInstruction)
*/
@Override
public void visitGet(SSAGetInstruction instruction) {
if (!instruction.isStatic()) {
int varNum = instruction.getRef();
removeImpossibleSuccessors(instruction, varNum);
}
}
/* (non-Javadoc)
* @see com.ibm.wala.ssa.SSAInstruction.IVisitor#visitGetCaughtException(com.ibm.wala.ssa.SSAGetCaughtExceptionInstruction)
*/
@Override
public void visitGetCaughtException(SSAGetCaughtExceptionInstruction instruction) {}
/* (non-Javadoc)
* @see com.ibm.wala.ssa.SSAInstruction.IVisitor#visitGoto(com.ibm.wala.ssa.SSAGotoInstruction)
*/
@Override
public void visitGoto(SSAGotoInstruction instruction) {}
/* (non-Javadoc)
* @see com.ibm.wala.ssa.SSAInstruction.IVisitor#visitInstanceof(com.ibm.wala.ssa.SSAInstanceofInstruction)
*/
@Override
public void visitInstanceof(SSAInstanceofInstruction instruction) {}
/* (non-Javadoc)
* @see com.ibm.wala.ssa.SSAInstruction.IVisitor#visitInvoke(com.ibm.wala.ssa.SSAInvokeInstruction)
*/
@Override
public void visitInvoke(SSAInvokeInstruction instruction) {
if (!instruction.isStatic()) {
int varNum = instruction.getReceiver();
removeImpossibleSuccessors(instruction, varNum);
} else {
removeImpossibleSuccessors(instruction);
}
}
/* (non-Javadoc)
* @see com.ibm.wala.ssa.SSAInstruction.IVisitor#visitLoadMetadata(com.ibm.wala.ssa.SSALoadMetadataInstruction)
*/
@Override
public void visitLoadMetadata(SSALoadMetadataInstruction instruction) {}
/* (non-Javadoc)
* @see com.ibm.wala.ssa.SSAInstruction.IVisitor#visitMonitor(com.ibm.wala.ssa.SSAMonitorInstruction)
*/
@Override
public void visitMonitor(SSAMonitorInstruction instruction) {
int varNum = instruction.getRef();
removeImpossibleSuccessors(instruction, varNum);
}
/* (non-Javadoc)
* @see com.ibm.wala.ssa.SSAInstruction.IVisitor#visitNew(com.ibm.wala.ssa.SSANewInstruction)
*/
@Override
public void visitNew(SSANewInstruction instruction) {
removeImpossibleSuccessors(instruction);
}
/* (non-Javadoc)
* @see com.ibm.wala.ssa.SSAInstruction.IVisitor#visitPhi(com.ibm.wala.ssa.SSAPhiInstruction)
*/
@Override
public void visitPhi(SSAPhiInstruction instruction) {}
/* (non-Javadoc)
* @see com.ibm.wala.ssa.SSAInstruction.IVisitor#visitPi(com.ibm.wala.ssa.SSAPiInstruction)
*/
@Override
public void visitPi(SSAPiInstruction instruction) {}
/* (non-Javadoc)
* @see com.ibm.wala.ssa.SSAInstruction.IVisitor#visitPut(com.ibm.wala.ssa.SSAPutInstruction)
*/
@Override
public void visitPut(SSAPutInstruction instruction) {
if (!instruction.isStatic()) {
int varNum = instruction.getRef();
removeImpossibleSuccessors(instruction, varNum);
}
}
/* (non-Javadoc)
* @see com.ibm.wala.ssa.SSAInstruction.IVisitor#visitReturn(com.ibm.wala.ssa.SSAReturnInstruction)
*/
@Override
public void visitReturn(SSAReturnInstruction instruction) {}
/* (non-Javadoc)
* @see com.ibm.wala.ssa.SSAInstruction.IVisitor#visitSwitch(com.ibm.wala.ssa.SSASwitchInstruction)
*/
@Override
public void visitSwitch(SSASwitchInstruction instruction) {}
/* (non-Javadoc)
* @see com.ibm.wala.ssa.SSAInstruction.IVisitor#visitThrow(com.ibm.wala.ssa.SSAThrowInstruction)
*/
@Override
public void visitThrow(SSAThrowInstruction instruction) {}
/* (non-Javadoc)
* @see com.ibm.wala.ssa.SSAInstruction.IVisitor#visitUnaryOp(com.ibm.wala.ssa.SSAUnaryOpInstruction)
*/
@Override
public void visitUnaryOp(SSAUnaryOpInstruction instruction) {}
}
}
| 15,636
| 32.48394
| 127
|
java
|
WALA
|
WALA-master/core/src/main/java/com/ibm/wala/cfg/exc/intra/MethodState.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.cfg.exc.intra;
import com.ibm.wala.ssa.SSAAbstractInvokeInstruction;
/**
* Provides a way for the nullpointer analysis to decide whether or not a called method may throw an
* exception.
*
* @author Juergen Graf <graf@kit.edu>
*/
public abstract class MethodState {
public abstract boolean throwsException(SSAAbstractInvokeInstruction node);
public static final MethodState DEFAULT =
new MethodState() {
@Override
public boolean throwsException(SSAAbstractInvokeInstruction node) {
// per default assume that every call may throw an exception
return true;
}
};
}
| 1,035
| 27.777778
| 100
|
java
|
WALA
|
WALA-master/core/src/main/java/com/ibm/wala/cfg/exc/intra/MutableCFG.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.cfg.exc.intra;
import com.ibm.wala.cfg.ControlFlowGraph;
import com.ibm.wala.cfg.IBasicBlock;
import com.ibm.wala.classLoader.IMethod;
import com.ibm.wala.util.graph.impl.SparseNumberedGraph;
import com.ibm.wala.util.intset.BitVector;
import com.ibm.wala.util.intset.IntSet;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
/**
* A modifiable control flow graph.
*
* @author Juergen Graf <graf@kit.edu>
*/
public class MutableCFG<X, T extends IBasicBlock<X>> extends SparseNumberedGraph<T>
implements ControlFlowGraph<X, T> {
private final ControlFlowGraph<X, T> orig;
private MutableCFG(final ControlFlowGraph<X, T> orig) {
this.orig = orig;
}
public static <I, T extends IBasicBlock<I>> MutableCFG<I, T> copyFrom(
ControlFlowGraph<I, T> cfg) {
MutableCFG<I, T> mutable = new MutableCFG<>(cfg);
for (T node : cfg) {
mutable.addNode(node);
}
for (T node : cfg) {
for (T succ : cfg.getNormalSuccessors(node)) {
mutable.addEdge(node, succ);
}
for (T succ : cfg.getExceptionalSuccessors(node)) {
mutable.addEdge(node, succ);
}
}
return mutable;
}
@Override
public T entry() {
return orig.entry();
}
@Override
public T exit() {
return orig.exit();
}
// slow
@Override
public BitVector getCatchBlocks() {
final BitVector bvOrig = orig.getCatchBlocks();
final BitVector bvThis = new BitVector();
for (final T block : this) {
bvThis.set(block.getNumber());
}
bvThis.and(bvOrig);
return bvThis;
}
@Override
public T getBlockForInstruction(int index) {
final T block = orig.getBlockForInstruction(index);
return (containsNode(block) ? block : null);
}
@Override
public X[] getInstructions() {
return orig.getInstructions();
}
@Override
public int getProgramCounter(int index) {
return orig.getProgramCounter(index);
}
@Override
public IMethod getMethod() {
return orig.getMethod();
}
@Override
public List<T> getExceptionalSuccessors(T b) {
final List<T> origSucc = orig.getExceptionalSuccessors(b);
final IntSet allSuccs = this.getSuccNodeNumbers(b);
final List<T> thisSuccs = new ArrayList<>();
for (final T block : origSucc) {
if (allSuccs.contains(block.getNumber())) {
thisSuccs.add(block);
}
}
return thisSuccs;
}
@Override
public Collection<T> getNormalSuccessors(T b) {
final List<T> excSuccs = getExceptionalSuccessors(b);
final List<T> thisSuccs = new ArrayList<>();
final Iterator<T> succs = getSuccNodes(b);
while (succs.hasNext()) {
final T succ = succs.next();
if (!excSuccs.contains(succ)) {
thisSuccs.add(succ);
}
}
return thisSuccs;
}
@Override
public Collection<T> getExceptionalPredecessors(T b) {
final Collection<T> origPreds = orig.getExceptionalPredecessors(b);
final IntSet allPreds = this.getPredNodeNumbers(b);
final List<T> thisPreds = new ArrayList<>();
for (final T block : origPreds) {
if (allPreds.contains(block.getNumber())) {
thisPreds.add(block);
}
}
return thisPreds;
}
@Override
public Collection<T> getNormalPredecessors(T b) {
final Collection<T> excPreds = getExceptionalPredecessors(b);
final List<T> thisPreds = new ArrayList<>();
final Iterator<T> preds = getPredNodes(b);
while (preds.hasNext()) {
final T pred = preds.next();
if (!excPreds.contains(pred)) {
thisPreds.add(pred);
}
}
return thisPreds;
}
}
| 4,046
| 22.946746
| 83
|
java
|
WALA
|
WALA-master/core/src/main/java/com/ibm/wala/cfg/exc/intra/NegativeGraphFilter.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.cfg.exc.intra;
import com.ibm.wala.cfg.IBasicBlock;
import com.ibm.wala.ipa.cfg.EdgeFilter;
import com.ibm.wala.util.graph.Graph;
/**
* An EdgeFilter that ignores all edges contained in a given graph. This ca be used to subtract a
* subgraph from its main graph.
*
* @author Juergen Graf <graf@kit.edu>
*/
public class NegativeGraphFilter<T extends IBasicBlock<?>> implements EdgeFilter<T> {
private final Graph<T> deleted;
public NegativeGraphFilter(Graph<T> deleted) {
this.deleted = deleted;
}
/* (non-Javadoc)
* @see com.ibm.wala.ipa.cfg.EdgeFilter#hasExceptionalEdge(com.ibm.wala.cfg.IBasicBlock, com.ibm.wala.cfg.IBasicBlock)
*/
@Override
public boolean hasExceptionalEdge(T src, T dst) {
return !deleted.hasEdge(src, dst);
}
/* (non-Javadoc)
* @see com.ibm.wala.ipa.cfg.EdgeFilter#hasNormalEdge(com.ibm.wala.cfg.IBasicBlock, com.ibm.wala.cfg.IBasicBlock)
*/
@Override
public boolean hasNormalEdge(T src, T dst) {
return !deleted.hasEdge(src, dst);
}
}
| 1,419
| 28.583333
| 120
|
java
|
WALA
|
WALA-master/core/src/main/java/com/ibm/wala/cfg/exc/intra/NullPointerFrameWork.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.cfg.exc.intra;
import com.ibm.wala.cfg.ControlFlowGraph;
import com.ibm.wala.dataflow.graph.IKilldallFramework;
import com.ibm.wala.ssa.IR;
import com.ibm.wala.ssa.ISSABasicBlock;
import com.ibm.wala.ssa.SSAInstruction;
import com.ibm.wala.util.graph.Acyclic;
import com.ibm.wala.util.graph.Graph;
import com.ibm.wala.util.intset.IBinaryNaturalRelation;
import com.ibm.wala.util.intset.IntPair;
/**
* Nullpointer analysis - NOT A REAL KILDALL framework instance, because the transfer functions are
* not distribute (similar to constant propagation). Therefore we remove back edges in the flow
* graph.
*
* @author Juergen Graf <graf@kit.edu>
*/
public class NullPointerFrameWork<T extends ISSABasicBlock>
implements IKilldallFramework<T, NullPointerState> {
private final Graph<T> flow;
private final NullPointerTransferFunctionProvider<T> transferFunct;
public NullPointerFrameWork(ControlFlowGraph<SSAInstruction, T> cfg, IR ir) {
final IBinaryNaturalRelation backEdges = Acyclic.computeBackEdges(cfg, cfg.entry());
boolean hasBackEdge = backEdges.iterator().hasNext();
if (hasBackEdge) {
MutableCFG<SSAInstruction, T> cfg2 = MutableCFG.copyFrom(cfg);
for (IntPair edge : backEdges) {
T from = cfg2.getNode(edge.getX());
T to = cfg2.getNode(edge.getY());
cfg2.removeEdge(from, to);
cfg2.addEdge(from, cfg.exit());
}
this.flow = cfg2;
} else {
this.flow = cfg;
}
this.transferFunct = new NullPointerTransferFunctionProvider<>(cfg, ir);
}
/* (non-Javadoc)
* @see com.ibm.wala.dataflow.graph.IKilldallFramework#getFlowGraph()
*/
@Override
public Graph<T> getFlowGraph() {
return flow;
}
/* (non-Javadoc)
* @see com.ibm.wala.dataflow.graph.IKilldallFramework#getTransferFunctionProvider()
*/
@Override
public NullPointerTransferFunctionProvider<T> getTransferFunctionProvider() {
return transferFunct;
}
}
| 2,356
| 30.851351
| 99
|
java
|
WALA
|
WALA-master/core/src/main/java/com/ibm/wala/cfg/exc/intra/NullPointerSolver.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.cfg.exc.intra;
import com.ibm.wala.cfg.exc.intra.NullPointerState.State;
import com.ibm.wala.dataflow.graph.DataflowSolver;
import com.ibm.wala.ssa.IR;
import com.ibm.wala.ssa.ISSABasicBlock;
/**
* Intraprocedural dataflow analysis to detect impossible NullPointerExceptions.
*
* @author Juergen Graf <graf@kit.edu>
*/
public class NullPointerSolver<B extends ISSABasicBlock>
extends DataflowSolver<B, NullPointerState> {
private final int maxVarNum;
private final ParameterState parameterState;
private final B entry;
private final IR ir;
public NullPointerSolver(NullPointerFrameWork<B> problem, int maxVarNum, IR ir, B entry) {
this(problem, maxVarNum, entry, ir, ParameterState.createDefault(ir.getMethod()));
}
public NullPointerSolver(
NullPointerFrameWork<B> problem, int maxVarNum, B entry, IR ir, ParameterState initialState) {
super(problem);
this.maxVarNum = maxVarNum;
this.parameterState = initialState;
this.entry = entry;
this.ir = ir;
}
/* (non-Javadoc)
* @see com.ibm.wala.dataflow.graph.DataflowSolver#makeEdgeVariable(java.lang.Object, java.lang.Object)
*/
@Override
protected NullPointerState makeEdgeVariable(B src, B dst) {
return new NullPointerState(maxVarNum, ir.getSymbolTable(), parameterState);
}
/* (non-Javadoc)
* @see com.ibm.wala.dataflow.graph.DataflowSolver#makeNodeVariable(java.lang.Object, boolean)
*/
@Override
protected NullPointerState makeNodeVariable(B n, boolean IN) {
if (IN && n.equals(entry)) {
return new NullPointerState(maxVarNum, ir.getSymbolTable(), parameterState, State.BOTH);
} else {
return new NullPointerState(maxVarNum, ir.getSymbolTable(), parameterState, State.UNKNOWN);
}
}
@Override
protected NullPointerState[] makeStmtRHS(int size) {
return new NullPointerState[size];
}
}
| 2,260
| 31.768116
| 105
|
java
|
WALA
|
WALA-master/core/src/main/java/com/ibm/wala/cfg/exc/intra/NullPointerState.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.cfg.exc.intra;
import com.ibm.wala.dataflow.graph.AbstractMeetOperator;
import com.ibm.wala.fixpoint.AbstractVariable;
import com.ibm.wala.fixpoint.FixedPointConstants;
import com.ibm.wala.fixpoint.UnaryOperator;
import com.ibm.wala.ssa.SymbolTable;
import java.util.Collection;
/**
* States for the ssa variables.
*
* @author Juergen Graf <graf@kit.edu>
*/
public class NullPointerState extends AbstractVariable<NullPointerState> {
/*
* Inital state is UNKNOWN.
* Lattice: BOTH < { NULL, NOT_NULL } < UNKNOWN
*/
public enum State {
UNKNOWN,
BOTH,
NULL,
NOT_NULL
}
// maps ssa variable number -> State
private final State[] vars;
NullPointerState(int maxVarNum, SymbolTable symbolTable, ParameterState parameterState) {
this(maxVarNum, symbolTable, parameterState, State.UNKNOWN);
}
NullPointerState(
int maxVarNum, SymbolTable symbolTable, ParameterState parameterState, State defaultState) {
this.vars = new State[maxVarNum + 1];
// Initialize the states
for (int i = 0; i < vars.length; i++) {
if (symbolTable.isConstant(i)) {
if (symbolTable.isNullConstant(i)) {
vars[i] = State.NULL;
} else {
vars[i] = State.NOT_NULL;
}
} else {
vars[i] = defaultState;
}
}
// Add what we know about the parameters (if we know anything about them).
// They are the first vars by convention.
if (parameterState != null) {
for (int i = 0; i < parameterState.getStates().size(); i++) {
assert parameterState.getState(i) != null;
vars[i + 1] = parameterState.getState(i);
assert vars[i + 1] != null;
}
}
}
static AbstractMeetOperator<NullPointerState> meetOperator() {
return StateMeet.INSTANCE;
}
/**
* This function is not distributive, therefore we cannot use the kildall framework.
*
* <pre>
* v3 = phi v1, v2
* ^ := Meet-operator
* f := phiValueMeetFunction(3, {1, 2}) = v1,v2,v3 -> v1,v2,[v1 ^ v2]
*
* f(1,?,?) ^ f(?,1,?) = 1,?,? ^ ?,1,? = 1,1,?
*
* f(1,?,? ^ ?,1,?) = f(1,1,?) = 1,1,1
*
* => f(1,?,? ^ ?,1,?) != f(1,?,?) ^ f(?,1,?)
* </pre>
*/
static UnaryOperator<NullPointerState> phiValueMeetFunction(int varNum, int[] fromVars) {
return new PhiValueMeet(varNum, fromVars);
}
static UnaryOperator<NullPointerState> nullifyFunction(int varNum) {
return new NullifyFunction(varNum);
}
static UnaryOperator<NullPointerState> denullifyFunction(int varNum) {
return new DenullifyFunction(varNum);
}
static UnaryOperator<NullPointerState> identityFunction() {
return IndentityFunction.INSTANCE;
}
static UnaryOperator<NullPointerState> phisFunction(
Collection<UnaryOperator<NullPointerState>> phiFunctions) {
return new OperatorUtil.UnaryOperatorSequence<>(phiFunctions);
}
boolean isNeverNull(int varNum) {
assert varNum > 0 && varNum < vars.length;
return vars[varNum] == State.NOT_NULL;
}
boolean isAlwaysNull(int varNum) {
assert varNum > 0 && varNum < vars.length;
return vars[varNum] == State.NULL;
}
/* (non-Javadoc)
* @see com.ibm.wala.fixpoint.IVariable#copyState(com.ibm.wala.fixpoint.IVariable)
*/
@Override
public void copyState(NullPointerState v) {
assert v.vars.length == vars.length;
System.arraycopy(v.vars, 0, vars, 0, v.vars.length);
}
/**
* This is the meet operator for the NullPointerState variables.
*
* <pre>
* ? == unknown, 1 == not null, 0 == null, * == both
*
* meet | ? | 0 | 1 | * | <- rhs
* -----|---|---|---|---|
* ? | ? | 0 | 1 | * |
* -----|---|---|---|---|
* 0 | 0 | 0 | * | * |
* -----|---|---|---|---|
* 1 | 1 | * | 1 | * |
* -----|---|---|---|---|
* * | * | * | * | * |
* ----------------------
* ^
* |
* lhs
* </pre>
*/
boolean meet(final int varNum, final State rhs) {
final State lhs = vars[varNum];
if (lhs != State.BOTH && rhs != lhs && rhs != State.UNKNOWN) {
if (lhs == State.UNKNOWN) {
vars[varNum] = rhs;
} else {
vars[varNum] = State.BOTH;
}
return true;
} else {
return false;
}
}
boolean meet(NullPointerState other) {
assert other.vars.length == vars.length;
boolean changed = false;
for (int i = 0; i < vars.length; i++) {
changed |= meet(i, other.vars[i]);
}
return changed;
}
boolean nullify(int varNum) {
if (vars[varNum] != State.NULL) {
vars[varNum] = State.NULL;
return true;
}
return false;
}
boolean denullify(int varNum) {
if (vars[varNum] != State.NOT_NULL) {
vars[varNum] = State.NOT_NULL;
return true;
}
return false;
}
@Override
public boolean equals(Object obj) {
if (obj instanceof NullPointerState) {
NullPointerState other = (NullPointerState) obj;
assert vars.length == other.vars.length;
for (int i = 0; i < vars.length; i++) {
if (vars[i] != other.vars[i]) {
return false;
}
}
return true;
}
return false;
}
public State getState(int ssaVarNum) {
return vars[ssaVarNum];
}
@Override
public String toString() {
StringBuilder buf = new StringBuilder("<");
for (State var : vars) {
switch (var) {
case BOTH:
buf.append('*');
break;
case NOT_NULL:
buf.append('1');
break;
case NULL:
buf.append('0');
break;
case UNKNOWN:
buf.append('?');
break;
default:
throw new IllegalStateException();
}
}
buf.append('>');
return buf.toString();
}
private static class StateMeet extends AbstractMeetOperator<NullPointerState> {
private static final StateMeet INSTANCE = new StateMeet();
private StateMeet() {}
/* (non-Javadoc)
* @see com.ibm.wala.fixedpoint.impl.AbstractOperator#equals(java.lang.Object)
*/
@Override
public boolean equals(Object o) {
return o instanceof StateMeet;
}
/* (non-Javadoc)
* @see com.ibm.wala.fixedpoint.impl.AbstractOperator#evaluate(com.ibm.wala.fixpoint.IVariable, com.ibm.wala.fixpoint.IVariable[])
*/
@Override
public byte evaluate(NullPointerState lhs, NullPointerState[] rhs) {
boolean changed = false;
// meet rhs first
for (NullPointerState state : rhs) {
changed |= lhs.meet(state);
}
return (changed ? FixedPointConstants.CHANGED : FixedPointConstants.NOT_CHANGED);
}
/* (non-Javadoc)
* @see com.ibm.wala.fixedpoint.impl.AbstractOperator#hashCode()
*/
@Override
public int hashCode() {
return 4711;
}
/* (non-Javadoc)
* @see com.ibm.wala.fixedpoint.impl.AbstractOperator#toString()
*/
@Override
public String toString() {
return "NullPointerStateMeet";
}
}
private static class PhiValueMeet extends UnaryOperator<NullPointerState> {
private final int varNum;
private final int[] fromVars;
/**
* Creates an operator that merges the states of the given variables fromVars into the state of
* the phi varaiable varNum
*
* @param varNum Variable number of a phi value
* @param fromVars Array of variable numbers the phi value refers to.
*/
private PhiValueMeet(int varNum, int[] fromVars) {
this.varNum = varNum;
this.fromVars = fromVars;
}
@Override
public byte evaluate(NullPointerState lhs, NullPointerState rhs) {
boolean changed = false;
if (!lhs.equals(rhs)) {
lhs.copyState(rhs);
changed = true;
}
lhs.vars[varNum] = State.UNKNOWN;
for (int from : fromVars) {
changed |= lhs.meet(varNum, rhs.vars[from]);
}
return (changed ? FixedPointConstants.CHANGED : FixedPointConstants.NOT_CHANGED);
}
/* (non-Javadoc)
* @see com.ibm.wala.fixedpoint.impl.AbstractOperator#equals(java.lang.Object)
*/
@Override
public boolean equals(Object o) {
if (o == this) {
return true;
}
if (o instanceof PhiValueMeet) {
PhiValueMeet other = (PhiValueMeet) o;
if (varNum == other.varNum && fromVars.length == other.fromVars.length) {
for (int i = 0; i < fromVars.length; i++) {
if (fromVars[i] != other.fromVars[i]) {
return false;
}
}
return true;
}
}
return false;
}
/* (non-Javadoc)
* @see com.ibm.wala.fixedpoint.impl.AbstractOperator#hashCode()
*/
@Override
public int hashCode() {
return 11000 + varNum;
}
/* (non-Javadoc)
* @see com.ibm.wala.fixedpoint.impl.AbstractOperator#toString()
*/
@Override
public String toString() {
StringBuilder str = new StringBuilder("PhiValueMeet(" + varNum + ", [");
for (int i = 0; i < fromVars.length; i++) {
str.append(fromVars[i]);
str.append(i == fromVars.length - 1 ? "" : ",");
}
str.append("])");
return str.toString();
}
}
private static class NullifyFunction extends UnaryOperator<NullPointerState> {
private final int varNum;
private NullifyFunction(int varNum) {
this.varNum = varNum;
}
/* (non-Javadoc)
* @see com.ibm.wala.fixedpoint.impl.UnaryOperator#evaluate(com.ibm.wala.fixpoint.IVariable, com.ibm.wala.fixpoint.IVariable)
*/
@Override
public byte evaluate(NullPointerState lhs, NullPointerState rhs) {
byte state = FixedPointConstants.NOT_CHANGED;
if (!lhs.equals(rhs)) {
lhs.copyState(rhs);
state = FixedPointConstants.CHANGED;
}
if (lhs.nullify(varNum)) {
state = FixedPointConstants.CHANGED;
}
return state;
}
/* (non-Javadoc)
* @see com.ibm.wala.fixedpoint.impl.AbstractOperator#equals(java.lang.Object)
*/
@Override
public boolean equals(Object o) {
return o instanceof NullifyFunction && ((NullifyFunction) o).varNum == varNum;
}
/* (non-Javadoc)
* @see com.ibm.wala.fixedpoint.impl.AbstractOperator#hashCode()
*/
@Override
public int hashCode() {
return 47000 + varNum;
}
/* (non-Javadoc)
* @see com.ibm.wala.fixedpoint.impl.AbstractOperator#toString()
*/
@Override
public String toString() {
return "Nullify(" + varNum + ')';
}
}
private static class DenullifyFunction extends UnaryOperator<NullPointerState> {
private final int varNum;
private DenullifyFunction(int varNum) {
assert varNum >= 0;
this.varNum = varNum;
}
/* (non-Javadoc)
* @see com.ibm.wala.fixedpoint.impl.UnaryOperator#evaluate(com.ibm.wala.fixpoint.IVariable, com.ibm.wala.fixpoint.IVariable)
*/
@Override
public byte evaluate(NullPointerState lhs, NullPointerState rhs) {
byte state = FixedPointConstants.NOT_CHANGED;
if (!lhs.equals(rhs)) {
lhs.copyState(rhs);
state = FixedPointConstants.CHANGED;
}
if (lhs.denullify(varNum)) {
state = FixedPointConstants.CHANGED;
}
return state;
}
/* (non-Javadoc)
* @see com.ibm.wala.fixedpoint.impl.AbstractOperator#equals(java.lang.Object)
*/
@Override
public boolean equals(Object o) {
return o instanceof DenullifyFunction && ((DenullifyFunction) o).varNum == varNum;
}
/* (non-Javadoc)
* @see com.ibm.wala.fixedpoint.impl.AbstractOperator#hashCode()
*/
@Override
public int hashCode() {
return -47000 - varNum;
}
/* (non-Javadoc)
* @see com.ibm.wala.fixedpoint.impl.AbstractOperator#toString()
*/
@Override
public String toString() {
return "Denullify(" + varNum + ')';
}
}
private static class IndentityFunction extends UnaryOperator<NullPointerState> {
private static final IndentityFunction INSTANCE = new IndentityFunction();
private IndentityFunction() {}
/* (non-Javadoc)
* @see com.ibm.wala.fixedpoint.impl.UnaryOperator#evaluate(com.ibm.wala.fixpoint.IVariable, com.ibm.wala.fixpoint.IVariable)
*/
@Override
public byte evaluate(NullPointerState lhs, NullPointerState rhs) {
if (lhs.equals(rhs)) {
return FixedPointConstants.NOT_CHANGED;
} else {
lhs.copyState(rhs);
return FixedPointConstants.CHANGED;
}
}
/* (non-Javadoc)
* @see com.ibm.wala.fixedpoint.impl.AbstractOperator#equals(java.lang.Object)
*/
@Override
public boolean equals(Object o) {
return o instanceof IndentityFunction;
}
/* (non-Javadoc)
* @see com.ibm.wala.fixedpoint.impl.AbstractOperator#hashCode()
*/
@Override
public int hashCode() {
return 8911;
}
/* (non-Javadoc)
* @see com.ibm.wala.fixedpoint.impl.AbstractOperator#toString()
*/
@Override
public String toString() {
return "Id";
}
}
}
| 13,501
| 24.57197
| 134
|
java
|
WALA
|
WALA-master/core/src/main/java/com/ibm/wala/cfg/exc/intra/NullPointerTransferFunctionProvider.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.cfg.exc.intra;
import com.ibm.wala.cfg.ControlFlowGraph;
import com.ibm.wala.cfg.Util;
import com.ibm.wala.dataflow.graph.AbstractMeetOperator;
import com.ibm.wala.dataflow.graph.ITransferFunctionProvider;
import com.ibm.wala.fixpoint.UnaryOperator;
import com.ibm.wala.shrike.shrikeBT.IConditionalBranchInstruction;
import com.ibm.wala.ssa.IR;
import com.ibm.wala.ssa.ISSABasicBlock;
import com.ibm.wala.ssa.SSAArrayLengthInstruction;
import com.ibm.wala.ssa.SSAArrayLoadInstruction;
import com.ibm.wala.ssa.SSAArrayStoreInstruction;
import com.ibm.wala.ssa.SSABinaryOpInstruction;
import com.ibm.wala.ssa.SSACFG;
import com.ibm.wala.ssa.SSACheckCastInstruction;
import com.ibm.wala.ssa.SSAComparisonInstruction;
import com.ibm.wala.ssa.SSAConditionalBranchInstruction;
import com.ibm.wala.ssa.SSAConversionInstruction;
import com.ibm.wala.ssa.SSAGetCaughtExceptionInstruction;
import com.ibm.wala.ssa.SSAGetInstruction;
import com.ibm.wala.ssa.SSAGotoInstruction;
import com.ibm.wala.ssa.SSAInstanceofInstruction;
import com.ibm.wala.ssa.SSAInstruction;
import com.ibm.wala.ssa.SSAInstruction.IVisitor;
import com.ibm.wala.ssa.SSAInvokeInstruction;
import com.ibm.wala.ssa.SSALoadMetadataInstruction;
import com.ibm.wala.ssa.SSAMonitorInstruction;
import com.ibm.wala.ssa.SSANewInstruction;
import com.ibm.wala.ssa.SSAPhiInstruction;
import com.ibm.wala.ssa.SSAPiInstruction;
import com.ibm.wala.ssa.SSAPutInstruction;
import com.ibm.wala.ssa.SSAReturnInstruction;
import com.ibm.wala.ssa.SSASwitchInstruction;
import com.ibm.wala.ssa.SSAThrowInstruction;
import com.ibm.wala.ssa.SSAUnaryOpInstruction;
import com.ibm.wala.ssa.SymbolTable;
import com.ibm.wala.ssa.analysis.IExplodedBasicBlock;
import com.ibm.wala.util.collections.Iterator2Iterable;
import java.util.ArrayList;
import java.util.Arrays;
/** @author Juergen Graf <graf@kit.edu> */
class NullPointerTransferFunctionProvider<T extends ISSABasicBlock>
implements ITransferFunctionProvider<T, NullPointerState> {
private final AbstractMeetOperator<NullPointerState> meet = NullPointerState.meetOperator();
private final TransferFunctionSSAVisitor visitor;
private final ControlFlowGraph<SSAInstruction, T> cfg;
NullPointerTransferFunctionProvider(ControlFlowGraph<SSAInstruction, T> cfg, IR ir) {
this.visitor = new TransferFunctionSSAVisitor(ir);
this.cfg = cfg;
}
static <T extends ISSABasicBlock> SSAInstruction getRelevantInstruction(T block) {
SSAInstruction instr = null;
if (block.getLastInstructionIndex() >= 0) {
instr = block.getLastInstruction();
}
if (instr == null && block.isCatchBlock()) {
if (block instanceof IExplodedBasicBlock) {
instr = ((IExplodedBasicBlock) block).getCatchInstruction();
} else if (block instanceof SSACFG.ExceptionHandlerBasicBlock) {
instr = ((SSACFG.ExceptionHandlerBasicBlock) block).getCatchInstruction();
} else {
throw new IllegalStateException(
"Unable to get catch instruction from unknown ISSABasicBlock implementation.");
}
}
return instr;
}
/* (non-Javadoc)
* @see com.ibm.wala.dataflow.graph.ITransferFunctionProvider#getEdgeTransferFunction(java.lang.Object, java.lang.Object)
*/
@Override
public UnaryOperator<NullPointerState> getEdgeTransferFunction(T src, T dst) {
SSAInstruction instr = getRelevantInstruction(src);
assert !(instr instanceof SSAPhiInstruction);
if (instr != null && cfg.hasEdge(src, dst)) {
instr.visit(visitor);
if (visitor.noIdentity) {
// do stuff
if (Util.endsWithConditionalBranch(cfg, src)) {
if (Util.getTakenSuccessor(cfg, src) == dst) {
// condition is true -> take function 1
return visitor.transfer1;
} else if (Util.getNotTakenSuccessor(cfg, src) == dst) {
// condition is true -> take function 2
return visitor.transfer2;
} else {
throw new IllegalStateException(
"Successor of if clause is neither true nor false case.");
}
} else {
if (cfg.getNormalSuccessors(src).contains(dst)) {
// normal case without exception -> take function 1
return visitor.transfer1;
} else if (cfg.getExceptionalSuccessors(src).contains(dst)) {
// exception has been raised -> take function 2
return visitor.transfer2;
} else {
throw new IllegalStateException("Successor not found.");
}
}
}
}
return NullPointerState.identityFunction();
}
/* (non-Javadoc)
* @see com.ibm.wala.dataflow.graph.ITransferFunctionProvider#getMeetOperator()
*/
@Override
public AbstractMeetOperator<NullPointerState> getMeetOperator() {
return meet;
}
/* (non-Javadoc)
* @see com.ibm.wala.dataflow.graph.ITransferFunctionProvider#getNodeTransferFunction(java.lang.Object)
*/
@Override
public UnaryOperator<NullPointerState> getNodeTransferFunction(final T node) {
final ArrayList<UnaryOperator<NullPointerState>> phiTransferFunctions = new ArrayList<>(1);
for (SSAPhiInstruction phi : Iterator2Iterable.make(node.iteratePhis())) {
int[] uses = new int[phi.getNumberOfUses()];
Arrays.setAll(uses, phi::getUse);
phiTransferFunctions.add(NullPointerState.phiValueMeetFunction(phi.getDef(), uses));
}
if (phiTransferFunctions.size() > 0) {
return NullPointerState.phisFunction(phiTransferFunctions);
} else {
return NullPointerState.identityFunction();
}
}
/* (non-Javadoc)
* @see com.ibm.wala.dataflow.graph.ITransferFunctionProvider#hasEdgeTransferFunctions()
*/
@Override
public boolean hasEdgeTransferFunctions() {
return true;
}
/* (non-Javadoc)
* @see com.ibm.wala.dataflow.graph.ITransferFunctionProvider#hasNodeTransferFunctions()
*/
@Override
public boolean hasNodeTransferFunctions() {
return true;
}
private static class TransferFunctionSSAVisitor implements IVisitor {
private final SymbolTable sym;
// used for true case of if clause and non-exception path
private UnaryOperator<NullPointerState> transfer1 = NullPointerState.identityFunction();
// used for false case of if clause and exceptional path
private UnaryOperator<NullPointerState> transfer2 = NullPointerState.identityFunction();
// true if sth will change. false => just use identity transfer function.
private boolean noIdentity = false;
private TransferFunctionSSAVisitor(IR ir) {
this.sym = ir.getSymbolTable();
}
/* (non-Javadoc)
* @see com.ibm.wala.ssa.SSAInstruction.IVisitor#visitArrayLength(com.ibm.wala.ssa.SSAArrayLengthInstruction)
*/
@Override
public void visitArrayLength(SSAArrayLengthInstruction instruction) {
noIdentity = true;
transfer1 = NullPointerState.denullifyFunction(instruction.getArrayRef());
transfer2 = NullPointerState.nullifyFunction(instruction.getArrayRef());
}
/* (non-Javadoc)
* @see com.ibm.wala.ssa.SSAInstruction.IVisitor#visitArrayLoad(com.ibm.wala.ssa.SSAArrayLoadInstruction)
*/
@Override
public void visitArrayLoad(SSAArrayLoadInstruction instruction) {
noIdentity = true;
transfer1 = NullPointerState.denullifyFunction(instruction.getArrayRef());
transfer2 = NullPointerState.nullifyFunction(instruction.getArrayRef());
}
/* (non-Javadoc)
* @see com.ibm.wala.ssa.SSAInstruction.IVisitor#visitArrayStore(com.ibm.wala.ssa.SSAArrayStoreInstruction)
*/
@Override
public void visitArrayStore(SSAArrayStoreInstruction instruction) {
noIdentity = true;
transfer1 = NullPointerState.denullifyFunction(instruction.getArrayRef());
transfer2 = NullPointerState.nullifyFunction(instruction.getArrayRef());
}
/* (non-Javadoc)
* @see com.ibm.wala.ssa.SSAInstruction.IVisitor#visitBinaryOp(com.ibm.wala.ssa.SSABinaryOpInstruction)
*/
@Override
public void visitBinaryOp(SSABinaryOpInstruction instruction) {
noIdentity = false;
transfer1 = NullPointerState.identityFunction();
transfer2 = NullPointerState.identityFunction();
}
/* (non-Javadoc)
* @see com.ibm.wala.ssa.SSAInstruction.IVisitor#visitCheckCast(com.ibm.wala.ssa.SSACheckCastInstruction)
*/
@Override
public void visitCheckCast(SSACheckCastInstruction instruction) {
noIdentity = false;
transfer1 = NullPointerState.identityFunction();
transfer2 = NullPointerState.identityFunction();
}
/* (non-Javadoc)
* @see com.ibm.wala.ssa.SSAInstruction.IVisitor#visitComparison(com.ibm.wala.ssa.SSAComparisonInstruction)
*/
@Override
public void visitComparison(SSAComparisonInstruction instruction) {
noIdentity = false;
transfer1 = NullPointerState.identityFunction();
transfer2 = NullPointerState.identityFunction();
}
/* (non-Javadoc)
* @see com.ibm.wala.ssa.SSAInstruction.IVisitor#visitConditionalBranch(com.ibm.wala.ssa.SSAConditionalBranchInstruction)
*/
@Override
public void visitConditionalBranch(SSAConditionalBranchInstruction instruction) {
int arg1 = instruction.getUse(0);
int arg2 = instruction.getUse(1);
IConditionalBranchInstruction.IOperator testOp = instruction.getOperator();
if (!(testOp instanceof IConditionalBranchInstruction.Operator)) {
throw new IllegalStateException(
"Conditional operator of unknown type: " + testOp.getClass());
}
IConditionalBranchInstruction.Operator op = (IConditionalBranchInstruction.Operator) testOp;
if (sym.isNullConstant(arg1)) {
switch (op) {
case EQ:
noIdentity = true;
transfer1 = NullPointerState.nullifyFunction(arg2);
transfer2 = NullPointerState.denullifyFunction(arg2);
break;
case NE:
noIdentity = true;
transfer1 = NullPointerState.denullifyFunction(arg2);
transfer2 = NullPointerState.nullifyFunction(arg2);
break;
default:
throw new IllegalStateException("Comparision to a null constant using " + op);
}
} else if (sym.isNullConstant(arg2)) {
switch (op) {
case EQ:
noIdentity = true;
transfer1 = NullPointerState.nullifyFunction(arg1);
transfer2 = NullPointerState.denullifyFunction(arg1);
break;
case NE:
noIdentity = true;
transfer1 = NullPointerState.denullifyFunction(arg1);
transfer2 = NullPointerState.nullifyFunction(arg1);
break;
default:
throw new IllegalStateException("Comparision to a null constant using " + op);
}
} else {
noIdentity = false;
transfer1 = NullPointerState.identityFunction();
transfer2 = NullPointerState.identityFunction();
}
}
/* (non-Javadoc)
* @see com.ibm.wala.ssa.SSAInstruction.IVisitor#visitConversion(com.ibm.wala.ssa.SSAConversionInstruction)
*/
@Override
public void visitConversion(SSAConversionInstruction instruction) {
noIdentity = false;
transfer1 = NullPointerState.identityFunction();
transfer2 = NullPointerState.identityFunction();
}
/* (non-Javadoc)
* @see com.ibm.wala.ssa.SSAInstruction.IVisitor#visitGet(com.ibm.wala.ssa.SSAGetInstruction)
*/
@Override
public void visitGet(SSAGetInstruction instruction) {
if (!instruction.isStatic()) {
final int ssaVar = instruction.getRef();
noIdentity = true;
transfer1 = NullPointerState.denullifyFunction(ssaVar);
transfer2 = NullPointerState.nullifyFunction(ssaVar);
} else {
noIdentity = false;
transfer1 = NullPointerState.identityFunction();
transfer2 = NullPointerState.identityFunction();
}
}
/* (non-Javadoc)
* @see com.ibm.wala.ssa.SSAInstruction.IVisitor#visitGetCaughtException(com.ibm.wala.ssa.SSAGetCaughtExceptionInstruction)
*/
@Override
public void visitGetCaughtException(SSAGetCaughtExceptionInstruction instruction) {
noIdentity = false;
transfer1 = NullPointerState.identityFunction();
transfer2 = NullPointerState.identityFunction();
}
/* (non-Javadoc)
* @see com.ibm.wala.ssa.SSAInstruction.IVisitor#visitGoto(com.ibm.wala.ssa.SSAGotoInstruction)
*/
@Override
public void visitGoto(SSAGotoInstruction instruction) {
noIdentity = false;
transfer1 = NullPointerState.identityFunction();
transfer2 = NullPointerState.identityFunction();
}
/* (non-Javadoc)
* @see com.ibm.wala.ssa.SSAInstruction.IVisitor#visitInstanceof(com.ibm.wala.ssa.SSAInstanceofInstruction)
*/
@Override
public void visitInstanceof(SSAInstanceofInstruction instruction) {
noIdentity = false;
transfer1 = NullPointerState.identityFunction();
transfer2 = NullPointerState.identityFunction();
}
/* (non-Javadoc)
* @see com.ibm.wala.ssa.SSAInstruction.IVisitor#visitInvoke(com.ibm.wala.ssa.SSAInvokeInstruction)
*/
@Override
public void visitInvoke(SSAInvokeInstruction instruction) {
if (!instruction.isStatic()) {
// when no exception is raised on a virtual call, the receiver is not null. Otherwise it is
// unsure if the receiver is definitely null as an exception may also stem from the method
// itself.
noIdentity = true;
transfer1 = NullPointerState.denullifyFunction(instruction.getReceiver());
transfer2 = NullPointerState.identityFunction();
} else {
noIdentity = false;
transfer1 = NullPointerState.identityFunction();
transfer2 = NullPointerState.identityFunction();
}
}
/* (non-Javadoc)
* @see com.ibm.wala.ssa.SSAInstruction.IVisitor#visitLoadMetadata(com.ibm.wala.ssa.SSALoadMetadataInstruction)
*/
@Override
public void visitLoadMetadata(SSALoadMetadataInstruction instruction) {
noIdentity = false;
transfer1 = NullPointerState.identityFunction();
transfer2 = NullPointerState.identityFunction();
}
/* (non-Javadoc)
* @see com.ibm.wala.ssa.SSAInstruction.IVisitor#visitMonitor(com.ibm.wala.ssa.SSAMonitorInstruction)
*/
@Override
public void visitMonitor(SSAMonitorInstruction instruction) {
// when no exception is raised on a synchronized statement, the monitor is not null. Otherwise
// it is
// unsure if the monitor is definitely null as other exception may also appear
// (synchronization related).
noIdentity = true;
transfer1 = NullPointerState.denullifyFunction(instruction.getRef());
transfer2 = NullPointerState.identityFunction();
}
/* (non-Javadoc)
* @see com.ibm.wala.ssa.SSAInstruction.IVisitor#visitNew(com.ibm.wala.ssa.SSANewInstruction)
*/
@Override
public void visitNew(SSANewInstruction instruction) {
/*
* If an exception is raised upon new is called, then the defined variable
* is null else it is guaranteed to not be null.
*/
noIdentity = true;
transfer1 = NullPointerState.denullifyFunction(instruction.getDef());
transfer2 = NullPointerState.nullifyFunction(instruction.getDef());
}
/* (non-Javadoc)
* @see com.ibm.wala.ssa.SSAInstruction.IVisitor#visitPhi(com.ibm.wala.ssa.SSAPhiInstruction)
*/
@Override
public void visitPhi(SSAPhiInstruction instruction) {
noIdentity = true;
int[] uses = new int[instruction.getNumberOfUses()];
Arrays.setAll(uses, instruction::getUse);
transfer1 = NullPointerState.phiValueMeetFunction(instruction.getDef(), uses);
// should not be used as no alternative path exists
transfer2 = NullPointerState.identityFunction();
}
/* (non-Javadoc)
* @see com.ibm.wala.ssa.SSAInstruction.IVisitor#visitPi(com.ibm.wala.ssa.SSAPiInstruction)
*/
@Override
public void visitPi(SSAPiInstruction instruction) {
noIdentity = false;
transfer1 = NullPointerState.identityFunction();
transfer2 = NullPointerState.identityFunction();
}
/* (non-Javadoc)
* @see com.ibm.wala.ssa.SSAInstruction.IVisitor#visitPut(com.ibm.wala.ssa.SSAPutInstruction)
*/
@Override
public void visitPut(SSAPutInstruction instruction) {
if (!instruction.isStatic()) {
final int ssaVar = instruction.getRef();
noIdentity = true;
transfer1 = NullPointerState.denullifyFunction(ssaVar);
transfer2 = NullPointerState.nullifyFunction(ssaVar);
} else {
noIdentity = false;
transfer1 = NullPointerState.identityFunction();
transfer2 = NullPointerState.identityFunction();
}
}
/* (non-Javadoc)
* @see com.ibm.wala.ssa.SSAInstruction.IVisitor#visitReturn(com.ibm.wala.ssa.SSAReturnInstruction)
*/
@Override
public void visitReturn(SSAReturnInstruction instruction) {
noIdentity = false;
transfer1 = NullPointerState.identityFunction();
transfer2 = NullPointerState.identityFunction();
}
/* (non-Javadoc)
* @see com.ibm.wala.ssa.SSAInstruction.IVisitor#visitSwitch(com.ibm.wala.ssa.SSASwitchInstruction)
*/
@Override
public void visitSwitch(SSASwitchInstruction instruction) {
noIdentity = false;
transfer1 = NullPointerState.identityFunction();
transfer2 = NullPointerState.identityFunction();
}
/* (non-Javadoc)
* @see com.ibm.wala.ssa.SSAInstruction.IVisitor#visitThrow(com.ibm.wala.ssa.SSAThrowInstruction)
*/
@Override
public void visitThrow(SSAThrowInstruction instruction) {
noIdentity = false;
transfer1 = NullPointerState.identityFunction();
transfer2 = NullPointerState.identityFunction();
}
/* (non-Javadoc)
* @see com.ibm.wala.ssa.SSAInstruction.IVisitor#visitUnaryOp(com.ibm.wala.ssa.SSAUnaryOpInstruction)
*/
@Override
public void visitUnaryOp(SSAUnaryOpInstruction instruction) {
noIdentity = false;
transfer1 = NullPointerState.identityFunction();
transfer2 = NullPointerState.identityFunction();
}
}
}
| 18,744
| 37.022312
| 127
|
java
|
WALA
|
WALA-master/core/src/main/java/com/ibm/wala/cfg/exc/intra/OperatorUtil.java
|
package com.ibm.wala.cfg.exc.intra;
import com.ibm.wala.fixpoint.FixedPointConstants;
import com.ibm.wala.fixpoint.IVariable;
import com.ibm.wala.fixpoint.UnaryOperator;
import java.util.Arrays;
import java.util.Collection;
/**
* Combinators for {@link UnaryOperator}
*
* @author Martin Hecker, martin.hecker@kit.edu
*/
public class OperatorUtil {
/**
* An operator of the form lhs = op_1(op_2(..op_n(rhs)..))
*
* @author Martin Hecker, martin.hecker@kit.edu
*/
public static class UnaryOperatorSequence<T extends IVariable<T>> extends UnaryOperator<T> {
final UnaryOperator<T>[] operators;
@SuppressWarnings("unchecked")
public UnaryOperatorSequence(Collection<UnaryOperator<T>> operators) {
if (operators.size() == 0) throw new IllegalArgumentException("Empty Operator-Sequence");
this.operators = operators.toArray(new UnaryOperator[0]);
}
@SafeVarargs
public UnaryOperatorSequence(UnaryOperator<T>... operators) {
if (operators.length == 0) throw new IllegalArgumentException("Empty Operator-Sequence");
this.operators = Arrays.copyOf(operators, operators.length);
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null) return false;
if (getClass() != o.getClass()) return false;
UnaryOperatorSequence<?> other = (UnaryOperatorSequence<?>) o;
return Arrays.equals(operators, other.operators);
}
@Override
public int hashCode() {
return Arrays.hashCode(operators);
}
@Override
public String toString() {
return Arrays.toString(operators);
}
@Override
public byte evaluate(T lhs, T rhs) {
assert (operators.length > 0);
int result = operators[0].evaluate(lhs, rhs);
for (int i = 1; i < operators.length; i++) {
byte changed = operators[i].evaluate(lhs, lhs);
result =
((result | changed) & FixedPointConstants.CHANGED_MASK)
| ((result | changed) & FixedPointConstants.SIDE_EFFECT_MASK)
| ((result & changed) & FixedPointConstants.FIXED_MASK);
}
return (byte) result;
}
}
}
| 2,177
| 28.04
| 95
|
java
|
WALA
|
WALA-master/core/src/main/java/com/ibm/wala/cfg/exc/intra/ParameterState.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.cfg.exc.intra;
import com.ibm.wala.cfg.exc.intra.NullPointerState.State;
import com.ibm.wala.classLoader.IMethod;
import com.ibm.wala.fixpoint.AbstractVariable;
import java.util.HashMap;
import java.util.Map.Entry;
import java.util.Set;
/**
* Encapsulates the state of all parameters of an invoked method
*
* @author markus
*/
public class ParameterState extends AbstractVariable<ParameterState> {
/*
* Inital state is UNKNOWN.
* Lattice: BOTH < { NULL, NOT_NULL } < UNKNOWN
*
* public enum State { UNKNOWN, BOTH, NULL, NOT_NULL }; as defined in NullPointerState
*
*/
public static final int NO_THIS_PTR = -1;
// maps the parmeter's varNum --> State
private final HashMap<Integer, State> params = new HashMap<>();
public static ParameterState createDefault(IMethod m) {
ParameterState p = new ParameterState();
if (!m.isStatic()) {
// set this pointer to NOT_NULL
p.setState(0, State.NOT_NULL);
}
return p;
}
public ParameterState() {}
/**
* Constructor to make a {@code ParameteState} out of a regular {@code NullPointerState}.
*
* @param state The {@code NullPointerState} to parse.
* @param parameterNumbers The numbers of parameters in {@code state}
*/
public ParameterState(NullPointerState state, int[] parameterNumbers) {
// by convention the first ssa vars are the parameters
for (int i = 0; i < parameterNumbers.length; i++) {
params.put(i, state.getState(parameterNumbers[i]));
}
}
public void setState(int varNum, State state) {
State prev = params.get(varNum);
if (prev != null) {
switch (prev) {
case UNKNOWN:
if (state != State.UNKNOWN) {
throw new IllegalArgumentException("Try to set " + prev + " to " + state);
}
break;
case NULL:
if (!(state == State.BOTH || state == State.NULL)) {
throw new IllegalArgumentException("Try to set " + prev + " to " + state);
}
break;
case NOT_NULL:
if (!(state == State.BOTH || state == State.NOT_NULL)) {
throw new IllegalArgumentException("Try to set " + prev + " to " + state);
}
break;
default:
throw new UnsupportedOperationException(
String.format("unexpected previous state %s", prev));
}
}
params.put(varNum, state);
}
public HashMap<Integer, State> getStates() {
return this.params;
}
/**
* Returns the state of an specified parameter.
*
* @param varNum The SSA var num of the parameter
* @return the state of the parameter defined with {@code varNum}
*/
public State getState(int varNum) {
State state = params.get(varNum);
if (state == null) {
throw new IllegalArgumentException(
"No mapping for variable " + varNum + "in ParameterState " + this);
}
return state;
}
@Override
public void copyState(ParameterState v) {
throw new UnsupportedOperationException();
}
@Override
public String toString() {
StringBuilder buf = new StringBuilder("<");
Set<Entry<Integer, State>> paramsSet = params.entrySet();
for (Entry<Integer, State> param : paramsSet) {
switch (param.getValue()) {
case BOTH:
buf.append('*');
break;
case NOT_NULL:
buf.append('1');
break;
case NULL:
buf.append('0');
break;
case UNKNOWN:
buf.append('?');
break;
default:
throw new IllegalStateException();
}
}
buf.append('>');
return buf.toString();
}
}
| 4,052
| 26.951724
| 91
|
java
|
WALA
|
WALA-master/core/src/main/java/com/ibm/wala/cfg/exc/intra/SSACFGNullPointerAnalysis.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.cfg.exc.intra;
import com.ibm.wala.cfg.ControlFlowGraph;
import com.ibm.wala.cfg.exc.ExceptionPruningAnalysis;
import com.ibm.wala.ssa.IR;
import com.ibm.wala.ssa.ISSABasicBlock;
import com.ibm.wala.ssa.SSAInstruction;
import com.ibm.wala.types.TypeReference;
import com.ibm.wala.util.CancelException;
import com.ibm.wala.util.MonitorUtil.IProgressMonitor;
import com.ibm.wala.util.graph.GraphIntegrity.UnsoundGraphException;
import java.util.List;
public class SSACFGNullPointerAnalysis
implements ExceptionPruningAnalysis<SSAInstruction, ISSABasicBlock> {
private final TypeReference[] ignoredExceptions;
private IntraprocNullPointerAnalysis<ISSABasicBlock> intra = null;
private final IR ir;
private final ParameterState initialState;
private final MethodState mState;
public SSACFGNullPointerAnalysis(
TypeReference[] ignoredExceptions, IR ir, ParameterState paramState, MethodState mState) {
this.ignoredExceptions = (ignoredExceptions != null ? ignoredExceptions.clone() : null);
this.ir = ir;
this.initialState =
(paramState == null ? ParameterState.createDefault(ir.getMethod()) : paramState);
this.mState = (mState == null ? MethodState.DEFAULT : mState);
}
@Override
public int compute(IProgressMonitor progress) throws UnsoundGraphException, CancelException {
ControlFlowGraph<SSAInstruction, ISSABasicBlock> orig = ir.getControlFlowGraph();
intra = new IntraprocNullPointerAnalysis<>(ir, orig, ignoredExceptions, initialState, mState);
intra.run(progress);
return intra.getNumberOfDeletedEdges();
}
/* (non-Javadoc)
* @see jsdg.exceptions.ExceptionPrunedCFGAnalysis#getPruned()
*/
@Override
public ControlFlowGraph<SSAInstruction, ISSABasicBlock> getCFG() {
if (intra == null) {
throw new IllegalStateException("Run compute(IProgressMonitor) first.");
}
return intra.getPrunedCFG();
}
/* (non-Javadoc)
* @see edu.kit.ipd.wala.ExceptionPrunedCFGAnalysis#hasExceptions()
*/
@Override
public boolean hasExceptions() {
if (intra == null) {
throw new IllegalStateException("Run compute(IProgressMonitor) first.");
}
ControlFlowGraph<SSAInstruction, ISSABasicBlock> cfg = intra.getPrunedCFG();
boolean hasException = false;
for (ISSABasicBlock bb : cfg) {
if (bb.getLastInstruction() == null) continue;
List<ISSABasicBlock> succ = cfg.getExceptionalSuccessors(bb);
if (succ != null && !succ.isEmpty()) {
hasException = true;
break;
}
}
return hasException;
}
@Override
public NullPointerState getState(ISSABasicBlock bb) {
if (intra == null) {
throw new IllegalStateException("Run compute(IProgressMonitor) first.");
}
return intra.getState(bb);
}
}
| 3,182
| 31.479592
| 98
|
java
|
WALA
|
WALA-master/core/src/main/java/com/ibm/wala/classLoader/AbstractNestedJarFileModule.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.classLoader;
import com.ibm.wala.core.util.io.FileSuffixes;
import com.ibm.wala.core.util.warnings.Warning;
import com.ibm.wala.core.util.warnings.Warnings;
import com.ibm.wala.util.collections.HashMapFactory;
import com.ibm.wala.util.debug.Assertions;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Iterator;
import java.util.jar.JarInputStream;
import java.util.zip.ZipEntry;
/** A Jar file nested in a parent jar file */
public abstract class AbstractNestedJarFileModule implements Module {
private static final boolean DEBUG = false;
private final Module container;
/**
* For efficiency, we cache the byte[] holding each ZipEntry's contents; this will help avoid
* multiple unzipping TODO: use a soft reference?
*/
private HashMap<String, byte[]> cache = null;
protected abstract InputStream getNestedContents() throws IOException;
protected AbstractNestedJarFileModule(Module container) {
this.container = container;
}
public InputStream getInputStream(String name) {
populateCache();
byte[] b = cache.get(name);
return new ByteArrayInputStream(b);
}
private void populateCache() {
if (cache != null) {
return;
}
cache = HashMapFactory.make();
try (final JarInputStream stream = new JarInputStream(getNestedContents(), false)) {
for (ZipEntry z = stream.getNextEntry(); z != null; z = stream.getNextEntry()) {
final String name = z.getName();
if (DEBUG) {
System.err.println(("got entry: " + name));
}
if (FileSuffixes.isClassFile(name) || FileSuffixes.isSourceFile(name)) {
ByteArrayOutputStream out = new ByteArrayOutputStream();
byte[] temp = new byte[1024];
int n = stream.read(temp);
while (n != -1) {
out.write(temp, 0, n);
n = stream.read(temp);
}
byte[] bb = out.toByteArray();
cache.put(name, bb);
}
}
} catch (IOException e) {
// just go with what we have
Warnings.add(
new Warning() {
@Override
public String getMsg() {
return "could not read contents of nested jar file "
+ AbstractNestedJarFileModule.this;
}
});
}
}
protected long getEntrySize(String name) {
populateCache();
byte[] b = cache.get(name);
return b.length;
}
@Override
public Iterator<ModuleEntry> getEntries() {
populateCache();
final Iterator<String> it = cache.keySet().iterator();
return new Iterator<>() {
String next = null;
{
advance();
}
private void advance() {
if (it.hasNext()) {
next = it.next();
} else {
next = null;
}
}
@Override
public boolean hasNext() {
return next != null;
}
@Override
public ModuleEntry next() {
ModuleEntry result = new Entry(next);
advance();
return result;
}
@Override
public void remove() {
Assertions.UNREACHABLE();
}
};
}
/** @author sfink an entry in a nested jar file. */
private class Entry implements ModuleEntry {
private final String name;
Entry(String name) {
this.name = name;
}
@Override
public String getName() {
return name;
}
@Override
public Module getContainer() {
return container;
}
@Override
public boolean isClassFile() {
return FileSuffixes.isClassFile(getName());
}
@Override
public InputStream getInputStream() {
return AbstractNestedJarFileModule.this.getInputStream(name);
}
@Override
public boolean isModuleFile() {
return false;
}
@Override
public Module asModule() {
Assertions.UNREACHABLE();
return null;
}
@Override
public String toString() {
return "nested entry: " + name;
}
@Override
public String getClassName() {
return FileSuffixes.stripSuffix(getName());
}
@Override
public boolean isSourceFile() {
return FileSuffixes.isSourceFile(getName());
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + getOuterType().hashCode();
result = prime * result + ((name == null) ? 0 : name.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;
Entry other = (Entry) obj;
if (!getOuterType().equals(other.getOuterType())) return false;
if (name == null) {
if (other.name != null) return false;
} else if (!name.equals(other.name)) return false;
return true;
}
private AbstractNestedJarFileModule getOuterType() {
return AbstractNestedJarFileModule.this;
}
}
}
| 5,503
| 24.6
| 95
|
java
|
WALA
|
WALA-master/core/src/main/java/com/ibm/wala/classLoader/AbstractURLModule.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.classLoader;
import com.ibm.wala.core.util.io.FileProvider;
import com.ibm.wala.util.collections.NonNullSingletonIterator;
import com.ibm.wala.util.debug.Assertions;
import com.ibm.wala.util.debug.UnimplementedError;
import java.io.IOException;
import java.io.InputStream;
import java.net.JarURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.Iterator;
public abstract class AbstractURLModule implements Module, ModuleEntry {
private final URL url;
public AbstractURLModule(URL url) {
assert url != null;
this.url = url;
}
public URL getURL() {
return url;
}
@Override
public String getName() {
try {
URLConnection con = url.openConnection();
if (con instanceof JarURLConnection) return ((JarURLConnection) con).getEntryName();
else return new FileProvider().filePathFromURL(url);
} catch (IOException e) {
Assertions.UNREACHABLE();
return null;
}
}
@Override
public InputStream getInputStream() {
try {
return url.openConnection().getInputStream();
} catch (IOException e) {
assert false : "cannot find stream for " + url;
return null;
}
}
@Override
public boolean isModuleFile() {
return false;
}
@Override
public Module asModule() throws UnimplementedError {
Assertions.UNREACHABLE();
return null;
}
@Override
public String getClassName() throws UnsupportedOperationException {
throw new UnsupportedOperationException();
}
@Override
public Iterator<ModuleEntry> getEntries() {
return new NonNullSingletonIterator<>(this);
}
@Override
public Module getContainer() {
// URLs are freestanding, without containers
return null;
}
@Override
public String toString() {
return "module:" + url;
}
}
| 2,209
| 23.285714
| 90
|
java
|
WALA
|
WALA-master/core/src/main/java/com/ibm/wala/classLoader/ArrayClass.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.classLoader;
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.core.util.strings.Atom;
import com.ibm.wala.ipa.cha.IClassHierarchy;
import com.ibm.wala.shrike.shrikeBT.Constants;
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;
/**
* Implementation of {@link IClass} for array classes. Such classes would be best called 'broken
* covariant array types', since that is the semantics that they implement.
*/
public class ArrayClass implements IClass, Constants {
private final IClassHierarchy cha;
/**
* Package-visible constructor; only for use by ArrayClassLoader class. 'loader' must be the
* Primordial IClassLoader.
*
* <p>[WHY? -- array classes are loaded by the element classloader??]
*/
ArrayClass(TypeReference type, IClassLoader loader, IClassHierarchy cha) {
this.type = type;
this.loader = loader;
this.cha = cha;
TypeReference elementType = type.getInnermostElementType();
if (!elementType.isPrimitiveType()) {
IClass klass = loader.lookupClass(elementType.getName());
if (klass == null) {
Assertions.UNREACHABLE("caller should not attempt to create an array with type " + type);
}
} else {
// assert loader.getReference().equals(ClassLoaderReference.Primordial);
}
}
private final TypeReference type;
private final IClassLoader loader;
@Override
public IClassLoader getClassLoader() {
return loader;
}
@Override
public TypeName getName() {
return getReference().getName();
}
/** Does this class represent an array of primitives? */
public boolean isOfPrimitives() {
return this.type.getInnermostElementType().isPrimitiveType();
}
@Override
public boolean isInterface() {
return false;
}
@Override
public boolean isAbstract() {
return false;
}
@Override
public int getModifiers() {
return ACC_PUBLIC | ACC_FINAL;
}
public String getQualifiedNameForReflection() {
return type.getName().toString(); // XXX is this the right string?
}
@Override
public IClass getSuperclass() {
IClass elt = getElementClass();
assert getReference().getArrayElementType().isPrimitiveType() || elt != null;
// super is Ljava/lang/Object in two cases:
// 1) [Ljava/lang/Object
// 2) [? for primitive arrays (null from getElementClass)
if (elt == null || elt.getReference() == getClassLoader().getLanguage().getRootType()) {
return loader.lookupClass(getClassLoader().getLanguage().getRootType().getName());
}
// else it is array of super of element type (yuck)
else {
TypeReference eltSuperRef = elt.getSuperclass().getReference();
TypeReference superRef = TypeReference.findOrCreateArrayOf(eltSuperRef);
return elt.getSuperclass().getClassLoader().lookupClass(superRef.getName());
}
}
@Override
public IMethod getMethod(Selector sig) {
return cha.lookupClass(getClassLoader().getLanguage().getRootType()).getMethod(sig);
}
@Override
public IField getField(Atom name) {
return getSuperclass().getField(name);
}
@Override
public IField getField(Atom name, TypeName typeName) {
return getSuperclass().getField(name, typeName);
}
@Override
public Collection<IMethod> getDeclaredMethods() {
return Collections.emptySet();
}
public int getNumberOfDeclaredMethods() {
return 0;
}
@Override
public TypeReference getReference() {
return type;
}
@Override
public String getSourceFileName() {
return null;
}
@Override
public IMethod getClassInitializer() {
return null;
}
@Override
public boolean isArrayClass() {
return true;
}
@Override
public String toString() {
return getReference().toString();
}
/**
* @return the IClass that represents the array element type, or null if the element type is a
* primitive
*/
public IClass getElementClass() {
TypeReference elementType = getReference().getArrayElementType();
if (elementType.isPrimitiveType()) {
return null;
}
return loader.lookupClass(elementType.getName());
}
@Override
public int hashCode() {
return type.hashCode();
}
@Override
public Collection<IField> getDeclaredInstanceFields() throws UnsupportedOperationException {
throw new UnsupportedOperationException();
}
@Override
public Collection<IField> getDeclaredStaticFields() throws UnimplementedError {
Assertions.UNREACHABLE();
return null;
}
@Override
public Collection<IClass> getAllImplementedInterfaces() {
HashSet<IClass> result = HashSetFactory.make(2);
for (TypeReference ref : getClassLoader().getLanguage().getArrayInterfaces()) {
IClass klass = loader.lookupClass(ref.getName());
if (klass != null) {
result.add(klass);
}
}
return result;
}
/** @see IClass#getAllImplementedInterfaces() */
public Collection<IClass> getAllAncestorInterfaces() throws UnsupportedOperationException {
throw new UnsupportedOperationException();
}
@Override
public boolean isReferenceType() {
return true;
}
public int getDimensionality() {
return getArrayTypeDimensionality(getReference());
}
/**
* @param reference a type reference for an array type
* @return the dimensionality of the array
*/
public static int getArrayTypeDimensionality(TypeReference reference) {
int mask = reference.getDerivedMask();
if ((mask & PrimitiveMask) == PrimitiveMask) {
mask >>= ElementBits;
}
int dims = 0;
while ((mask & ArrayMask) == ArrayMask) {
mask >>= ElementBits;
dims++;
}
assert dims > 0;
return dims;
}
/**
* @return the IClass that represents the innermost array element type, or null if the element
* type is a primitive
*/
public IClass getInnermostElementClass() {
TypeReference elementType = getReference().getInnermostElementType();
if (elementType.isPrimitiveType()) {
return null;
}
return loader.lookupClass(elementType.getName());
}
@Override
public Collection<IClass> getDirectInterfaces() throws UnimplementedError {
// TODO Auto-generated method stub
Assertions.UNREACHABLE();
return null;
}
@Override
public boolean equals(Object obj) {
if (obj instanceof ArrayClass) {
ArrayClass other = (ArrayClass) obj;
return loader.equals(other.loader) && type.equals(other.type);
} else {
return false;
}
}
@Override
public Collection<IField> getAllInstanceFields() {
Assertions.UNREACHABLE();
return null;
}
@Override
public Collection<IField> getAllStaticFields() {
Assertions.UNREACHABLE();
return null;
}
@Override
public Collection<? extends IMethod> getAllMethods() {
return loader
.lookupClass(getClassLoader().getLanguage().getRootType().getName())
.getAllMethods();
}
@Override
public Collection<IField> getAllFields() {
Assertions.UNREACHABLE();
return null;
}
@Override
public IClassHierarchy getClassHierarchy() {
return cha;
}
@Override
public boolean isPublic() {
return true;
}
@Override
public boolean isPrivate() {
return false;
}
@Override
public boolean isSynthetic() {
return false;
}
@Override
public Reader getSource() {
return null;
}
@Override
public Collection<Annotation> getAnnotations() {
return Collections.emptySet();
}
}
| 8,348
| 24.689231
| 97
|
java
|
WALA
|
WALA-master/core/src/main/java/com/ibm/wala/classLoader/ArrayClassLoader.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.classLoader;
import com.ibm.wala.ipa.cha.IClassHierarchy;
import com.ibm.wala.types.TypeName;
import com.ibm.wala.types.TypeReference;
import com.ibm.wala.util.collections.HashMapFactory;
import java.util.HashMap;
/**
* Pseudo-classloader for all array classes; all other IClassLoader implementations should delegate
* to this one for array classes only.
*/
public class ArrayClassLoader {
private static final boolean DEBUG = false;
/** map: TypeReference -> ArrayClass */
private final HashMap<TypeReference, ArrayClass> arrayClasses = HashMapFactory.make();
/**
* @param className name of the array class
* @param delegator class loader to look up element type with
*/
public IClass lookupClass(TypeName className, IClassLoader delegator, IClassHierarchy cha)
throws IllegalArgumentException {
ArrayClass arrayClass;
if (DEBUG) {
assert className.toString().startsWith("[");
}
if (delegator == null) {
throw new IllegalArgumentException("delegator must not be null");
}
TypeReference type = TypeReference.findOrCreate(delegator.getReference(), className);
TypeReference elementType = type.getArrayElementType();
if (elementType.isPrimitiveType()) {
TypeReference aRef = TypeReference.findOrCreateArrayOf(elementType);
arrayClass = arrayClasses.get(aRef);
IClassLoader primordial = getRootClassLoader(delegator);
if (arrayClass == null) {
arrayClasses.put(aRef, arrayClass = new ArrayClass(aRef, primordial, cha));
}
} else {
arrayClass = arrayClasses.get(type);
if (arrayClass == null) {
// check that the element class is loadable. If not, return null.
IClass elementCls = delegator.lookupClass(elementType.getName());
if (elementCls == null) {
return null;
}
TypeReference realType = TypeReference.findOrCreateArrayOf(elementCls.getReference());
arrayClass = arrayClasses.get(realType);
if (arrayClass == null) {
arrayClass = new ArrayClass(realType, elementCls.getClassLoader(), cha);
}
}
arrayClasses.put(type, arrayClass);
}
return arrayClass;
}
private static IClassLoader getRootClassLoader(IClassLoader l) {
while (l.getParent() != null) {
l = l.getParent();
}
return l;
}
public int getNumberOfClasses() {
return arrayClasses.size();
}
}
| 2,821
| 32.2
| 99
|
java
|
WALA
|
WALA-master/core/src/main/java/com/ibm/wala/classLoader/BinaryDirectoryTreeModule.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.classLoader;
import com.ibm.wala.core.util.warnings.Warning;
import com.ibm.wala.core.util.warnings.Warnings;
import com.ibm.wala.shrike.shrikeCT.InvalidClassFileException;
import java.io.File;
/** Module representing a directory of .class files */
public class BinaryDirectoryTreeModule extends DirectoryTreeModule {
public BinaryDirectoryTreeModule(File root) {
super(root);
}
@Override
protected boolean includeFile(File file) {
return file.getName().endsWith("class");
}
@Override
protected FileModule makeFile(final File file) {
try {
return new ClassFileModule(file, this);
} catch (InvalidClassFileException e) {
Warnings.add(
new Warning(Warning.MODERATE) {
@Override
public String getMsg() {
return "Invalid class file at path " + file.getAbsolutePath();
}
});
return null;
}
}
}
| 1,315
| 27
| 76
|
java
|
WALA
|
WALA-master/core/src/main/java/com/ibm/wala/classLoader/BytecodeClass.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.classLoader;
import com.ibm.wala.core.util.strings.Atom;
import com.ibm.wala.core.util.strings.ImmutableByteArray;
import com.ibm.wala.core.util.warnings.Warning;
import com.ibm.wala.core.util.warnings.Warnings;
import com.ibm.wala.ipa.cha.ClassHierarchy;
import com.ibm.wala.ipa.cha.ClassHierarchyWarning;
import com.ibm.wala.ipa.cha.IClassHierarchy;
import com.ibm.wala.shrike.shrikeCT.InvalidClassFileException;
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.types.annotations.Annotation;
import com.ibm.wala.types.annotations.TypeAnnotation;
import com.ibm.wala.types.generics.TypeSignature;
import com.ibm.wala.util.collections.BimodalMap;
import com.ibm.wala.util.collections.HashMapFactory;
import com.ibm.wala.util.collections.HashSetFactory;
import com.ibm.wala.util.collections.SmallMap;
import com.ibm.wala.util.debug.Assertions;
import java.io.Reader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* A class representing which originates in some form of bytecode.
*
* @param <T> type of classloader which loads this format of class.
*/
public abstract class BytecodeClass<T extends IClassLoader> implements IClass {
protected BytecodeClass(T loader, IClassHierarchy cha) {
this.loader = loader;
this.cha = cha;
}
/** An Atom which holds the name of the super class. We cache this for efficiency reasons. */
protected ImmutableByteArray superName;
/** The names of interfaces for this class. We cache this for efficiency reasons. */
protected ImmutableByteArray[] interfaceNames;
/** The object that loaded this class. */
protected final T loader;
/** Governing class hierarchy for this class */
protected final IClassHierarchy cha;
/**
* A mapping from Selector to IMethod
*
* <p>TODO: get rid of this for classes (though keep it for interfaces) instead ... use a VMT.
*/
protected volatile Map<Selector, IMethod> methodMap;
/** A mapping from Selector to IMethod used to cache method lookups from superclasses */
protected Map<Selector, IMethod> inheritCache;
/** Canonical type representation */
protected TypeReference typeReference;
/** superclass */
protected IClass superClass;
/** Compute the superclass lazily. */
protected boolean superclassComputed = false;
/**
* The IClasses that represent all interfaces this class implements (if it's a class) or extends
* (it it's an interface)
*/
protected Collection<IClass> allInterfaces = null;
/** The instance fields declared in this class. */
protected IField[] instanceFields;
/** The static fields declared in this class. */
protected IField[] staticFields;
/** hash code; cached here for efficiency */
protected int hashCode;
private final HashMap<Atom, IField> fieldMap = HashMapFactory.make(5);
/** A warning for when we get a class not found exception */
private static class ClassNotFoundWarning extends Warning {
final ImmutableByteArray className;
ClassNotFoundWarning(ImmutableByteArray className) {
super(Warning.SEVERE);
this.className = className;
}
@Override
public String getMsg() {
return getClass().toString() + " : " + className;
}
public static ClassNotFoundWarning create(ImmutableByteArray className) {
return new ClassNotFoundWarning(className);
}
}
public abstract Module getContainer();
@Override
public IClassLoader getClassLoader() {
return loader;
}
protected abstract IMethod[] computeDeclaredMethods() throws InvalidClassFileException;
@Override
public TypeReference getReference() {
return typeReference;
}
@Override
public String getSourceFileName() {
return loader.getSourceFileName(this);
}
@Override
public Reader getSource() {
return loader.getSource(this);
}
@Override
public int hashCode() {
return hashCode;
}
@Override
public String toString() {
return getReference().toString();
}
@Override
public boolean isArrayClass() {
return false;
}
@Override
public IClassHierarchy getClassHierarchy() {
return cha;
}
@Override
public TypeName getName() {
return getReference().getName();
}
@Override
public boolean isReferenceType() {
return getReference().isReferenceType();
}
@Override
public IField getField(Atom name) {
if (fieldMap.containsKey(name)) {
return fieldMap.get(name);
} else {
List<IField> fields = findDeclaredField(name);
if (!fields.isEmpty()) {
if (fields.size() == 1) {
IField f = fields.iterator().next();
fieldMap.put(name, f);
return f;
} else {
throw new IllegalStateException("multiple fields with name " + name);
}
} else if ((superClass = getSuperclass()) != null) {
IField f = superClass.getField(name);
if (f != null) {
fieldMap.put(name, f);
return f;
}
}
// try superinterfaces
for (IClass i : getAllImplementedInterfaces()) {
IField f = i.getField(name);
if (f != null) {
fieldMap.put(name, f);
return f;
}
}
}
return null;
}
@Override
public IField getField(Atom name, TypeName type) {
boolean unresolved = false;
try {
// typically, there will be at most one field with the name
IField field = getField(name);
if (field != null && field.getFieldTypeReference().getName().equals(type)) {
return field;
} else {
unresolved = true;
}
} catch (IllegalStateException e) {
assert e.getMessage().startsWith("multiple fields with");
unresolved = true;
}
if (unresolved) {
// multiple fields. look through all of them and see if any have the appropriate type
List<IField> fields = findDeclaredField(name);
for (IField f : fields) {
if (f.getFieldTypeReference().getName().equals(type)) {
return f;
}
}
// check superclass
if (getSuperclass() != null) {
IField f = superClass.getField(name, type);
if (f != null) {
return f;
}
}
// try superinterfaces
for (IClass i : getAllImplementedInterfaces()) {
IField f = i.getField(name, type);
if (f != null) {
return f;
}
}
}
return null;
}
private void computeSuperclass() {
superclassComputed = true;
if (superName == null) {
if (!getReference().equals(loader.getLanguage().getRootType())) {
superClass = loader.lookupClass(loader.getLanguage().getRootType().getName());
}
return;
}
superClass = loader.lookupClass(TypeName.findOrCreate(superName));
}
@Override
public IClass getSuperclass() {
if (!superclassComputed) {
computeSuperclass();
}
if (superClass == null && !getReference().equals(TypeReference.JavaLangObject)) {
// TODO MissingSuperClassHandling.Phantom needs to be implemented
if (cha instanceof ClassHierarchy
&& ((ClassHierarchy) cha)
.getSuperClassHandling()
.equals(ClassHierarchy.MissingSuperClassHandling.ROOT)) {
superClass = loader.lookupClass(loader.getLanguage().getRootType().getName());
} else
throw new NoSuperclassFoundException(
"No superclass found for " + this + " Superclass name " + superName);
}
return superClass;
}
public TypeName getSuperName() {
return TypeName.findOrCreate(superName);
}
@Override
public Collection<IField> getAllFields() {
Collection<IField> result = new ArrayList<>();
result.addAll(getAllInstanceFields());
result.addAll(getAllStaticFields());
return result;
}
@Override
public Collection<IClass> getAllImplementedInterfaces() {
if (allInterfaces == null) {
Collection<IClass> C = computeAllInterfacesAsCollection();
allInterfaces = Collections.unmodifiableCollection(C);
}
return allInterfaces;
}
@Override
public Collection<IField> getDeclaredInstanceFields() {
if (instanceFields == null) {
return Collections.emptySet();
} else {
return Collections.unmodifiableList(Arrays.asList(instanceFields));
}
}
@Override
public Collection<IField> getDeclaredStaticFields() {
return Collections.unmodifiableList(Arrays.asList(staticFields));
}
@Override
public Collection<? extends IClass> getDirectInterfaces() {
return array2IClassSet(interfaceNames);
}
@Override
public Collection<IField> getAllInstanceFields() {
Collection<IField> result = new ArrayList<>(getDeclaredInstanceFields());
IClass s = getSuperclass();
while (s != null) {
result.addAll(s.getDeclaredInstanceFields());
s = s.getSuperclass();
}
return result;
}
@Override
public Collection<IField> getAllStaticFields() {
Collection<IField> result = new ArrayList<>(getDeclaredStaticFields());
IClass s = getSuperclass();
while (s != null) {
result.addAll(s.getDeclaredStaticFields());
s = s.getSuperclass();
}
return result;
}
@Override
public Collection<IMethod> getAllMethods() {
Collection<IMethod> result = new ArrayList<>(getDeclaredMethods());
if (isInterface()) {
for (IClass i : getDirectInterfaces()) {
result.addAll(i.getAllMethods());
}
} else {
// for non-interfaces, add default methods inherited from interfaces #219.
for (IClass i : this.getAllImplementedInterfaces())
for (IMethod m : i.getDeclaredMethods()) if (!m.isAbstract()) result.add(m);
}
IClass s = getSuperclass();
while (s != null) {
result.addAll(s.getDeclaredMethods());
s = s.getSuperclass();
}
return result;
}
@Override
public Collection<IMethod> getDeclaredMethods() {
try {
computeMethodMapIfNeeded();
} catch (InvalidClassFileException e) {
e.printStackTrace();
Assertions.UNREACHABLE();
}
return Collections.unmodifiableCollection(methodMap.values());
}
@Override
public IMethod getMethod(Selector selector) {
try {
computeMethodMapIfNeeded();
} catch (InvalidClassFileException e1) {
e1.printStackTrace();
Assertions.UNREACHABLE();
}
// my methods + cached parent stuff
IMethod result = methodMap.get(selector);
if (result != null) {
return result;
}
if (inheritCache != null) {
result = inheritCache.get(selector);
if (result != null) {
return result;
}
}
// check parent, caching if found
if (!selector.equals(MethodReference.clinitSelector)
&& !selector.getName().equals(MethodReference.initAtom)) {
IClass superclass = getSuperclass();
if (superclass != null) {
IMethod inherit = superclass.getMethod(selector);
if (inherit != null) {
if (inheritCache == null) {
inheritCache = new BimodalMap<>(5);
}
inheritCache.put(selector, inherit);
return inherit;
}
}
}
// check interfaces for Java 8 default implementation
// Java seems to require a single default implementation, so take that on faith here
for (IClass iface : getAllImplementedInterfaces()) {
for (IMethod m : iface.getDeclaredMethods()) {
if (!m.isAbstract() && m.getSelector().equals(selector)) {
if (inheritCache == null) {
inheritCache = new BimodalMap<>(5);
}
inheritCache.put(selector, m);
return m;
}
}
}
// no method found
if (inheritCache == null) {
inheritCache = new BimodalMap<>(5);
}
inheritCache.put(selector, null);
return null;
}
/** @return Collection of IClasses, representing the interfaces this class implements. */
protected Collection<IClass> computeAllInterfacesAsCollection() {
Collection<? extends IClass> c = getDirectInterfaces();
Set<IClass> result = HashSetFactory.make();
for (IClass klass : c) {
if (klass.isInterface()) {
result.add(klass);
} else {
Warnings.add(ClassHierarchyWarning.create("expected an interface " + klass));
}
}
// at this point result holds all interfaces the class directly extends.
// now expand to a fixed point.
Set<IClass> last = null;
do {
last = HashSetFactory.make(result);
for (IClass i : last) {
result.addAll(i.getDirectInterfaces());
}
} while (last.size() < result.size());
// now add any interfaces implemented by the super class
IClass sup = getSuperclass();
if (sup != null) {
result.addAll(sup.getAllImplementedInterfaces());
}
return result;
}
/**
* @param interfaces a set of class names
* @return Set of all IClasses that can be loaded corresponding to the class names in the
* interfaces array; raise warnings if classes can not be loaded
*/
private Collection<IClass> array2IClassSet(ImmutableByteArray[] interfaces) {
ArrayList<IClass> result = new ArrayList<>(interfaces.length);
for (ImmutableByteArray name : interfaces) {
IClass klass = loader.lookupClass(TypeName.findOrCreate(name));
if (klass == null) {
Warnings.add(ClassNotFoundWarning.create(name));
} else {
result.add(klass);
}
}
return result;
}
protected List<IField> findDeclaredField(Atom name) {
List<IField> result = new ArrayList<>(1);
if (instanceFields != null) {
for (IField instanceField : instanceFields) {
if (instanceField.getName() == name) {
result.add(instanceField);
}
}
}
if (staticFields != null) {
for (IField staticField : staticFields) {
if (staticField.getName() == name) {
result.add(staticField);
}
}
}
return result;
}
protected void addFieldToList(
List<FieldImpl> L,
Atom name,
ImmutableByteArray fieldType,
int accessFlags,
Collection<Annotation> annotations,
Collection<TypeAnnotation> typeAnnotations,
TypeSignature sig) {
TypeName T = null;
if (fieldType.get(fieldType.length() - 1) == ';') {
T = TypeName.findOrCreate(fieldType, 0, fieldType.length() - 1);
} else {
T = TypeName.findOrCreate(fieldType);
}
TypeReference type = TypeReference.findOrCreate(getClassLoader().getReference(), T);
FieldReference fr = FieldReference.findOrCreate(getReference(), name, type);
FieldImpl f = new FieldImpl(this, fr, accessFlags, annotations, typeAnnotations, sig);
L.add(f);
}
/** set up the methodMap mapping */
protected void computeMethodMapIfNeeded() throws InvalidClassFileException {
if (methodMap == null) {
synchronized (this) {
if (methodMap == null) {
IMethod[] methods = computeDeclaredMethods();
final Map<Selector, IMethod> tmpMethodMap;
if (methods.length > 5) {
tmpMethodMap = HashMapFactory.make(methods.length);
} else {
tmpMethodMap = new SmallMap<>();
}
for (IMethod m : methods) {
tmpMethodMap.put(m.getReference().getSelector(), m);
}
methodMap = tmpMethodMap;
}
}
}
}
public abstract Collection<Annotation> getAnnotations(boolean runtimeVisible)
throws InvalidClassFileException;
}
| 16,199
| 28.032258
| 98
|
java
|
WALA
|
WALA-master/core/src/main/java/com/ibm/wala/classLoader/BytecodeLanguage.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.classLoader;
import com.ibm.wala.shrike.shrikeBT.IInstruction;
import com.ibm.wala.shrike.shrikeBT.IInvokeInstruction;
import com.ibm.wala.types.ClassLoaderReference;
import com.ibm.wala.types.MethodReference;
import com.ibm.wala.types.TypeReference;
import java.util.Collection;
public interface BytecodeLanguage extends Language {
Collection<TypeReference> getImplicitExceptionTypes(IInstruction pei);
MethodReference getInvokeMethodReference(
ClassLoaderReference loader, IInvokeInstruction instruction);
}
| 913
| 32.851852
| 72
|
java
|
WALA
|
WALA-master/core/src/main/java/com/ibm/wala/classLoader/CallSiteReference.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.classLoader;
import com.ibm.wala.ipa.callgraph.CGNode;
import com.ibm.wala.ipa.callgraph.ContextItem;
import com.ibm.wala.shrike.shrikeBT.BytecodeConstants;
import com.ibm.wala.shrike.shrikeBT.IInvokeInstruction;
import com.ibm.wala.ssa.IR;
import com.ibm.wala.types.MethodReference;
import com.ibm.wala.util.debug.Assertions;
/**
* Simple object that represents a static call site (ie., an invoke instruction in the bytecode)
*
* <p>Note that the identity of a call site reference depends on two things: the program counter,
* and the containing IR. Thus, it suffices to define equals() and hashCode() from {@link
* ProgramCounter}, since this class does not maintain a pointer to the containing {@link IR} (or
* {@link CGNode}) anyway. If using a hashtable of CallSiteReference from different IRs, you
* probably want to use a wrapper which also holds a pointer to the governing CGNode.
*/
public abstract class CallSiteReference extends ProgramCounter
implements BytecodeConstants, ContextItem {
private final MethodReference declaredTarget;
/**
* @param programCounter Index into bytecode describing this instruction
* @param declaredTarget The method target as declared at the call site
*/
protected CallSiteReference(int programCounter, MethodReference declaredTarget) {
super(programCounter);
this.declaredTarget = declaredTarget;
}
@Override
public int hashCode() {
final int prime = 31;
int result = super.hashCode();
result = prime * result + ((declaredTarget == null) ? 0 : declaredTarget.hashCode());
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;
CallSiteReference other = (CallSiteReference) obj;
if (declaredTarget == null) {
if (other.declaredTarget != null) return false;
} else if (!declaredTarget.equals(other.declaredTarget)) return false;
return true;
}
// the following atrocities are needed to save a word of space by
// declaring these classes static, so they don't keep a pointer
// to the enclosing environment
// Java makes you type!
static class StaticCall extends CallSiteReference {
StaticCall(int programCounter, MethodReference declaredTarget) {
super(programCounter, declaredTarget);
}
@Override
public IInvokeInstruction.IDispatch getInvocationCode() {
return IInvokeInstruction.Dispatch.STATIC;
}
}
static class SpecialCall extends CallSiteReference {
SpecialCall(int programCounter, MethodReference declaredTarget) {
super(programCounter, declaredTarget);
}
@Override
public IInvokeInstruction.IDispatch getInvocationCode() {
return IInvokeInstruction.Dispatch.SPECIAL;
}
}
static class VirtualCall extends CallSiteReference {
VirtualCall(int programCounter, MethodReference declaredTarget) {
super(programCounter, declaredTarget);
}
@Override
public IInvokeInstruction.IDispatch getInvocationCode() {
return IInvokeInstruction.Dispatch.VIRTUAL;
}
}
static class InterfaceCall extends CallSiteReference {
InterfaceCall(int programCounter, MethodReference declaredTarget) {
super(programCounter, declaredTarget);
}
@Override
public IInvokeInstruction.IDispatch getInvocationCode() {
return IInvokeInstruction.Dispatch.INTERFACE;
}
}
/**
* This factory method plays a little game to avoid storing the invocation code in the object;
* this saves a byte (probably actually a whole word) in each created object.
*
* <p>TODO: Consider canonicalization?
*/
public static CallSiteReference make(
int programCounter,
MethodReference declaredTarget,
IInvokeInstruction.IDispatch invocationCode) {
if (invocationCode == IInvokeInstruction.Dispatch.SPECIAL)
return new SpecialCall(programCounter, declaredTarget);
if (invocationCode == IInvokeInstruction.Dispatch.VIRTUAL)
return new VirtualCall(programCounter, declaredTarget);
if (invocationCode == IInvokeInstruction.Dispatch.INTERFACE)
return new InterfaceCall(programCounter, declaredTarget);
if (invocationCode == IInvokeInstruction.Dispatch.STATIC)
return new StaticCall(programCounter, declaredTarget);
throw new IllegalArgumentException("unsupported code: " + invocationCode);
}
/**
* Return the Method that this call site calls. This represents the method declared in the invoke
* instruction only.
*/
public MethodReference getDeclaredTarget() {
return declaredTarget;
}
/** Return one of INVOKESPECIAL, INVOKESTATIC, INVOKEVIRTUAL, or INVOKEINTERFACE */
public abstract IInvokeInstruction.IDispatch getInvocationCode();
@Override
public String toString() {
return "invoke"
+ getInvocationString(getInvocationCode())
+ ' '
+ declaredTarget
+ '@'
+ getProgramCounter();
}
protected String getInvocationString(IInvokeInstruction.IDispatch invocationCode) {
if (invocationCode == IInvokeInstruction.Dispatch.STATIC) return "static";
if (invocationCode == IInvokeInstruction.Dispatch.SPECIAL) return "special";
if (invocationCode == IInvokeInstruction.Dispatch.VIRTUAL) return "virtual";
if (invocationCode == IInvokeInstruction.Dispatch.INTERFACE) return "interface";
Assertions.UNREACHABLE();
return null;
}
public String getInvocationString() {
return getInvocationString(getInvocationCode());
}
/** Is this an invokeinterface call site? */
public final boolean isInterface() {
return (getInvocationCode() == IInvokeInstruction.Dispatch.INTERFACE);
}
/** Is this an invokevirtual call site? */
public final boolean isVirtual() {
return (getInvocationCode() == IInvokeInstruction.Dispatch.VIRTUAL);
}
/** Is this an invokespecial call site? */
public final boolean isSpecial() {
return (getInvocationCode() == IInvokeInstruction.Dispatch.SPECIAL);
}
/** Is this an invokestatic call site? */
public boolean isStatic() {
return (getInvocationCode() == IInvokeInstruction.Dispatch.STATIC);
}
public boolean isFixed() {
return isStatic() || isSpecial();
}
public boolean isDispatch() {
return isVirtual() || isInterface();
}
}
| 6,763
| 33.161616
| 99
|
java
|
WALA
|
WALA-master/core/src/main/java/com/ibm/wala/classLoader/ClassFileModule.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.classLoader;
import com.ibm.wala.core.util.shrike.ShrikeClassReaderHandle;
import com.ibm.wala.core.util.strings.ImmutableByteArray;
import com.ibm.wala.shrike.shrikeCT.InvalidClassFileException;
import java.io.File;
/** A module which is a wrapper around a .class file */
public class ClassFileModule extends FileModule {
private final String className;
public ClassFileModule(File f, Module container) throws InvalidClassFileException {
super(f, container);
ShrikeClassReaderHandle reader = new ShrikeClassReaderHandle(this);
ImmutableByteArray name = ImmutableByteArray.make(reader.get().getName());
className = name.toString();
}
@Override
public String toString() {
return "ClassFileModule:" + getFile();
}
@Override
public boolean isClassFile() {
return true;
}
@Override
public String getClassName() {
return className;
}
@Override
public boolean isSourceFile() {
return false;
}
}
| 1,356
| 25.607843
| 85
|
java
|
WALA
|
WALA-master/core/src/main/java/com/ibm/wala/classLoader/ClassFileURLModule.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.classLoader;
import com.ibm.wala.core.util.shrike.ShrikeClassReaderHandle;
import com.ibm.wala.core.util.strings.ImmutableByteArray;
import com.ibm.wala.shrike.shrikeCT.InvalidClassFileException;
import java.net.URL;
public class ClassFileURLModule extends AbstractURLModule {
private final String className;
public ClassFileURLModule(URL url) throws InvalidClassFileException {
super(url);
ShrikeClassReaderHandle reader = new ShrikeClassReaderHandle(this);
ImmutableByteArray name = ImmutableByteArray.make(reader.get().getName());
className = name.toString();
}
@Override
public boolean isClassFile() {
return true;
}
@Override
public String getClassName() {
return className;
}
@Override
public boolean isSourceFile() {
return false;
}
}
| 1,197
| 26.227273
| 78
|
java
|
WALA
|
WALA-master/core/src/main/java/com/ibm/wala/classLoader/ClassLoaderFactory.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.classLoader;
import com.ibm.wala.ipa.callgraph.AnalysisScope;
import com.ibm.wala.ipa.cha.IClassHierarchy;
import com.ibm.wala.types.ClassLoaderReference;
import java.io.IOException;
/** */
public interface ClassLoaderFactory {
/**
* Return a class loader corresponding to a given class loader identifier. Create one if
* necessary.
*
* @param classLoaderReference identifier for the desired class loader
* @return IClassLoader
*/
IClassLoader getLoader(
ClassLoaderReference classLoaderReference, IClassHierarchy cha, AnalysisScope scope)
throws IOException;
}
| 996
| 29.212121
| 90
|
java
|
WALA
|
WALA-master/core/src/main/java/com/ibm/wala/classLoader/ClassLoaderFactoryImpl.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.classLoader;
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.ipa.cha.IClassHierarchy;
import com.ibm.wala.types.ClassLoaderReference;
import com.ibm.wala.util.collections.HashMapFactory;
import com.ibm.wala.util.config.SetOfClasses;
import java.io.IOException;
import java.lang.reflect.Constructor;
import java.util.HashMap;
/** An implementation of the class loader factory that produces ClassLoaderImpls */
public class ClassLoaderFactoryImpl implements ClassLoaderFactory {
/**
* Set of classes that class loaders should ignore; classloaders should pretend these classes
* don't exit.
*/
private final SetOfClasses exclusions;
/** A Mapping from ClassLoaderReference to IClassLoader */
private final HashMap<ClassLoaderReference, IClassLoader> map = HashMapFactory.make(3);
/** @param exclusions A set of classes that class loaders should pretend don't exist. */
public ClassLoaderFactoryImpl(SetOfClasses exclusions) {
this.exclusions = exclusions;
}
/**
* Return a class loader corresponding to a given class loader identifier. Create one if
* necessary.
*
* @param classLoaderReference identifier for the desired class loader
*/
@Override
public IClassLoader getLoader(
ClassLoaderReference classLoaderReference, IClassHierarchy cha, AnalysisScope scope)
throws IOException {
if (classLoaderReference == null) {
throw new IllegalArgumentException("null classLoaderReference");
}
IClassLoader result = map.get(classLoaderReference);
if (result == null) {
ClassLoaderReference parentRef = classLoaderReference.getParent();
IClassLoader parent = null;
if (parentRef != null) {
parent = getLoader(parentRef, cha, scope);
}
IClassLoader cl = makeNewClassLoader(classLoaderReference, cha, parent, scope);
map.put(classLoaderReference, cl);
result = cl;
}
return result;
}
/**
* Create a new class loader for a given key
*
* @param classLoaderReference the key
* @param parent parent classloader to be used for delegation
* @return a new ClassLoaderImpl
* @throws IOException if the desired loader cannot be instantiated, usually because the specified
* module can't be found.
*/
protected IClassLoader makeNewClassLoader(
ClassLoaderReference classLoaderReference,
IClassHierarchy cha,
IClassLoader parent,
AnalysisScope scope)
throws IOException {
String implClass = scope.getLoaderImpl(classLoaderReference);
IClassLoader cl;
if (implClass == null) {
cl =
new ClassLoaderImpl(
classLoaderReference, scope.getArrayClassLoader(), parent, exclusions, cha);
} else
try {
// this is fragile. why are we doing things this way again?
Class<?> impl = Class.forName(implClass);
Constructor<?> ctor =
impl.getDeclaredConstructor(
new Class[] {
ClassLoaderReference.class,
IClassLoader.class,
SetOfClasses.class,
IClassHierarchy.class
});
cl =
(IClassLoader)
ctor.newInstance(new Object[] {classLoaderReference, parent, exclusions, cha});
} catch (Exception e) {
try {
Class<?> impl = Class.forName(implClass);
Constructor<?> ctor =
impl.getDeclaredConstructor(
new Class[] {
ClassLoaderReference.class,
ArrayClassLoader.class,
IClassLoader.class,
SetOfClasses.class,
IClassHierarchy.class
});
cl =
(IClassLoader)
ctor.newInstance(
new Object[] {
classLoaderReference, scope.getArrayClassLoader(), parent, exclusions, cha
});
} catch (Exception e2) {
System.err.println("failed to load impl class " + implClass);
e2.printStackTrace(System.err);
Warnings.add(InvalidClassLoaderImplementation.create(implClass));
cl =
new ClassLoaderImpl(
classLoaderReference, scope.getArrayClassLoader(), parent, exclusions, cha);
}
}
cl.init(scope.getModules(classLoaderReference));
return cl;
}
/** A waring when we fail to load an appropriate class loader implementation */
private static class InvalidClassLoaderImplementation extends Warning {
final String impl;
InvalidClassLoaderImplementation(String impl) {
super(Warning.SEVERE);
this.impl = impl;
}
@Override
public String getMsg() {
return getClass().toString() + " : " + impl;
}
public static InvalidClassLoaderImplementation create(String impl) {
return new InvalidClassLoaderImplementation(impl);
}
}
/** @return the set of classes that will be ignored. */
public SetOfClasses getExclusions() {
return exclusions;
}
}
| 5,585
| 33.9125
| 100
|
java
|
WALA
|
WALA-master/core/src/main/java/com/ibm/wala/classLoader/ClassLoaderImpl.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.classLoader;
import com.ibm.wala.core.util.io.FileProvider;
import com.ibm.wala.core.util.io.FileSuffixes;
import com.ibm.wala.core.util.shrike.ShrikeClassReaderHandle;
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.cha.IClassHierarchy;
import com.ibm.wala.shrike.shrikeCT.ClassReader;
import com.ibm.wala.shrike.shrikeCT.InvalidClassFileException;
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.collections.HashSetFactory;
import com.ibm.wala.util.collections.Iterator2Iterable;
import com.ibm.wala.util.config.SetOfClasses;
import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.util.Collection;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import java.util.jar.JarInputStream;
/** A class loader that reads class definitions from a set of Modules. */
public class ClassLoaderImpl implements IClassLoader {
public static final int DEBUG_LEVEL = 0;
private static final boolean OPTIMIZE_JAR_FILE_IO = true;
/** classes to ignore */
private final SetOfClasses exclusions;
/** Identity for this class loader */
private final ClassLoaderReference loader;
/** A mapping from class name (TypeName) to IClass */
protected final Map<TypeName, IClass> loadedClasses = HashMapFactory.make();
/** A mapping from class name (TypeName) to String (source file name) */
private final Map<TypeName, ModuleEntry> sourceMap = HashMapFactory.make();
/** Parent classloader */
private final IClassLoader parent;
/** Governing class hierarchy */
protected final IClassHierarchy cha;
/** an object to delegate to for loading of array classes */
private final ArrayClassLoader arrayClassLoader;
/**
* @param loader class loader reference identifying this loader
* @param parent parent loader for delegation
* @param exclusions set of classes to exclude from loading
*/
@SuppressWarnings("unused")
public ClassLoaderImpl(
ClassLoaderReference loader,
ArrayClassLoader arrayClassLoader,
IClassLoader parent,
SetOfClasses exclusions,
IClassHierarchy cha) {
if (loader == null) {
throw new IllegalArgumentException("null loader");
}
this.arrayClassLoader = arrayClassLoader;
this.parent = parent;
this.loader = loader;
this.exclusions = exclusions;
this.cha = cha;
if (DEBUG_LEVEL > 0) {
System.err.println("Creating class loader for " + loader);
}
}
/**
* Return the Set of (ModuleEntry) source files found in a module.
*
* @param M the module
* @return the Set of source files in the module
*/
@SuppressWarnings("unused")
private Set<ModuleEntry> getSourceFiles(Module M) throws IOException {
if (DEBUG_LEVEL > 0) {
System.err.println("Get source files for " + M);
}
HashSet<ModuleEntry> result = HashSetFactory.make();
for (ModuleEntry entry : Iterator2Iterable.make(M.getEntries())) {
if (DEBUG_LEVEL > 0) {
System.err.println("consider entry for source information: " + entry);
}
if (entry.isSourceFile()) {
if (DEBUG_LEVEL > 0) {
System.err.println("found source file: " + entry);
}
result.add(entry);
} else if (entry.isModuleFile()) {
result.addAll(getSourceFiles(entry.asModule()));
}
}
return result;
}
/**
* Return the Set of (ModuleEntry) class files found in a module.
*
* @param M the module
* @return the Set of class Files in the module
*/
@SuppressWarnings("unused")
private Set<ModuleEntry> getClassFiles(Module M) throws IOException {
if (DEBUG_LEVEL > 0) {
System.err.println("Get class files for " + M);
}
HashSet<ModuleEntry> result = HashSetFactory.make();
for (ModuleEntry entry : Iterator2Iterable.make(M.getEntries())) {
if (DEBUG_LEVEL > 0) {
System.err.println("ClassLoaderImpl.getClassFiles:Got entry: " + entry);
}
if (entry.isClassFile()) {
if (DEBUG_LEVEL > 0) {
System.err.println("result contains: " + entry);
}
result.add(entry);
} else if (entry.isModuleFile()) {
Set<ModuleEntry> s = getClassFiles(entry.asModule());
removeClassFiles(s, result);
result.addAll(s);
} else {
if (DEBUG_LEVEL > 0) {
System.err.println("Ignoring entry: " + entry);
}
}
}
return result;
}
/** Remove from s any class file module entries which already are in t */
private static void removeClassFiles(Set<ModuleEntry> s, Set<ModuleEntry> t) {
s.removeAll(t);
}
/** Return a Set of IClasses, which represents all classes this class loader can load. */
private Collection<IClass> getAllClasses() {
assert loadedClasses != null;
return loadedClasses.values();
}
static class ByteArrayReaderHandle extends ShrikeClassReaderHandle {
public ByteArrayReaderHandle(ModuleEntry entry, byte[] contents) {
super(entry);
assert contents != null && contents.length > 0;
this.contents = contents;
}
private byte[] contents;
private boolean cleared;
@Override
public ClassReader get() throws InvalidClassFileException {
if (cleared) {
return super.get();
} else {
return new ClassReader(contents);
}
}
@Override
public void clear() {
if (cleared) {
super.clear();
} else {
contents = null;
cleared = true;
}
}
}
/** Set up the set of classes loaded by this object. */
@SuppressWarnings("unused")
private void loadAllClasses(
Collection<ModuleEntry> moduleEntries, Map<String, Object> fileContents, boolean isJMODType) {
for (ModuleEntry entry : moduleEntries) {
// java11 support for jmod files
if (!entry.isClassFile()
|| (isJMODType && entry.getClassName().startsWith("classes/module-info"))) {
continue;
}
@SuppressWarnings("NonConstantStringShouldBeStringBuffer")
String className = entry.getClassName().replace('.', '/');
// java11 support for jmod files
if (isJMODType && className.startsWith("classes/")) {
className = className.replace("classes/", "");
}
if (DEBUG_LEVEL > 0) {
System.err.println("Consider " + className);
}
if (exclusions != null && exclusions.contains(className)) {
if (DEBUG_LEVEL > 0) {
System.err.println("Excluding " + className);
}
continue;
}
ShrikeClassReaderHandle entryReader = new ShrikeClassReaderHandle(entry);
className = 'L' + className;
if (DEBUG_LEVEL > 0) {
System.err.println("Load class " + className);
}
try {
TypeName T = TypeName.string2TypeName(className);
if (loadedClasses.get(T) != null) {
Warnings.add(MultipleImplementationsWarning.create(className));
} else if (parent != null && parent.lookupClass(T) != null) {
Warnings.add(MultipleImplementationsWarning.create(className));
} else {
// try to read from memory
ShrikeClassReaderHandle reader = entryReader;
if (fileContents != null) {
final Object contents = fileContents.get(entry.getName());
if (contents != null) {
// reader that uses the in-memory bytes
reader = new ByteArrayReaderHandle(entry, (byte[]) contents);
}
}
ShrikeClass tmpKlass = new ShrikeClass(reader, this, cha);
if (tmpKlass.getReference().getName().equals(T)) {
// always used the reader based on the entry after this point,
// so we can null out and re-read class file contents
loadedClasses.put(T, new ShrikeClass(entryReader, this, cha));
if (DEBUG_LEVEL > 1) {
System.err.println("put " + T + ' ');
}
} else {
Warnings.add(InvalidClassFile.create(className));
}
}
} catch (InvalidClassFileException e) {
if (DEBUG_LEVEL > 0) {
System.err.println("Ignoring class " + className + " due to InvalidClassFileException");
}
Warnings.add(InvalidClassFile.create(className));
}
}
}
@SuppressWarnings("unused")
private Map<String, Object> getAllClassAndSourceFileContents(
byte[] jarFileContents, String fileName, Map<String, Map<String, Long>> entrySizes) {
if (jarFileContents == null) {
return null;
}
Map<String, Long> entrySizesForFile = entrySizes.get(fileName);
if (entrySizesForFile == null) {
return null;
}
Map<String, Object> result = HashMapFactory.make();
try (final JarInputStream s =
new JarInputStream(new ByteArrayInputStream(jarFileContents), false)) {
JarEntry entry = null;
while ((entry = s.getNextJarEntry()) != null) {
byte[] entryBytes = getEntryBytes(entrySizesForFile.get(entry.getName()), s);
if (entryBytes == null) {
return null;
}
String name = entry.getName();
if (FileSuffixes.isJarFile(name) || FileSuffixes.isWarFile(name)) {
Map<String, Object> nestedResult =
getAllClassAndSourceFileContents(entryBytes, name, entrySizes);
if (nestedResult == null) {
return null;
}
for (Map.Entry<String, Object> nestedEntry : nestedResult.entrySet()) {
final String entryName = nestedEntry.getKey();
if (!result.containsKey(entryName)) {
result.put(entryName, nestedEntry.getValue());
}
}
} else if (FileSuffixes.isClassFile(name) || FileSuffixes.isSourceFile(name)) {
result.put(name, entryBytes);
}
}
} catch (IOException e) {
assert false;
}
return result;
}
private static byte[] getEntryBytes(Long size, InputStream is) throws IOException {
if (size == null) {
return null;
}
ByteArrayOutputStream S = new ByteArrayOutputStream();
int n = 0;
long count = 0;
byte[] buffer = new byte[1024];
while (n > -1 && count < size) {
n = is.read(buffer, 0, 1024);
if (n > -1) {
S.write(buffer, 0, n);
count += n;
}
}
return S.toByteArray();
}
/** A warning when we find more than one implementation of a given class name */
private static class MultipleImplementationsWarning extends Warning {
final String className;
MultipleImplementationsWarning(String className) {
super(Warning.SEVERE);
this.className = className;
}
@Override
public String getMsg() {
return getClass().toString() + " : " + className;
}
public static MultipleImplementationsWarning create(String className) {
return new MultipleImplementationsWarning(className);
}
}
/** A warning when we encounter InvalidClassFileException */
private static class InvalidClassFile extends Warning {
final String className;
InvalidClassFile(String className) {
super(Warning.SEVERE);
this.className = className;
}
@Override
public String getMsg() {
return getClass().toString() + " : " + className;
}
public static InvalidClassFile create(String className) {
return new InvalidClassFile(className);
}
}
/** Set up mapping from type name to Module Entry */
@SuppressWarnings("unused")
protected void loadAllSources(Set<ModuleEntry> sourceModules) {
for (ModuleEntry entry : sourceModules) {
String className = entry.getClassName().replace('.', '/');
className = className.replace(File.separatorChar, '/');
className = 'L' + (className.startsWith("/") ? className.substring(1) : className);
TypeName T = TypeName.string2TypeName(className);
// Note: entry.getClassName() may not return the correct class name, for example,
// com.ibm.wala.classLoader.SourceFileModule.getClassName()
// {
// return FileSuffixes.stripSuffix(fileName).replace(File.separator.charAt(0), '/');
// }
// If fileName includes the full path, such as
// C:\TestApps\HelloWorld\src\main\java\com\ibm\helloworld\MyClass.java
// Then above method would return the class name as:
// C:/TestApps/HelloWorld/src/main/java/com/ibm/helloworld/MyClass
// However, in WALA, we represent class name as:
// PackageName.className, such as com.ibm.helloworld.MyClass
//
// In method "void init(List<Module> modules)", We loadAllClasses firstly, then
// loadAllSources. Therefore, all the classes should be in the map loadedClasses
// when this method loadAllSources is called. To ensure we add the correct class
// name to the sourceMap, here we look up the class name from the map "loadedClasses"
// before adding the source info to the sourceMap. If we could not find the class,
// we edit the className and try again.
boolean success = false;
if (loadedClasses.get(T) != null) {
if (DEBUG_LEVEL > 0) {
System.err.println("adding to source map: " + T + " -> " + entry.getName());
}
sourceMap.put(T, entry);
success = true;
}
// Class does not exist
else {
// look at substrings starting after '/' characters, in the hope
// that we find a known class name
while (className.indexOf('/') > 0) {
className = 'L' + className.substring(className.indexOf('/') + 1);
TypeName T2 = TypeName.string2TypeName(className);
if (loadedClasses.get(T2) != null) {
if (DEBUG_LEVEL > 0) {
System.err.println("adding to source map: " + T2 + " -> " + entry.getName());
}
sourceMap.put(T2, entry);
success = true;
break;
}
}
}
if (success == false) {
// Add the T and entry to the sourceMap anyway, just in case in some special
// cases, we add new classes later.
if (DEBUG_LEVEL > 0) {
System.err.println("adding to source map: " + T + " -> " + entry.getName());
}
sourceMap.put(T, entry);
}
}
}
/**
* Initialize internal data structures
*
* @throws IllegalArgumentException if modules is null
*/
@SuppressWarnings("unused")
@Override
public void init(List<Module> modules) throws IOException {
if (modules == null) {
throw new IllegalArgumentException("modules is null");
}
// module are loaded according to the given order (same as in Java VM)
Set<ModuleEntry> classModuleEntries = HashSetFactory.make();
Set<ModuleEntry> sourceModuleEntries = HashSetFactory.make();
for (Module archive : modules) {
boolean isJMODType = false;
if (archive instanceof JarFileModule) {
JarFile jarFile = ((JarFileModule) archive).getJarFile();
isJMODType = (jarFile != null) && jarFile.getName().endsWith(".jmod");
}
if (DEBUG_LEVEL > 0) {
System.err.println("add archive: " + archive);
}
// byte[] jarFileContents = null;
if (OPTIMIZE_JAR_FILE_IO && archive instanceof JarFileModule) {
// if we have a jar file, we read the whole thing into memory and operate on that; enables
// more
// efficient sequential I/O
// this is work in progress; for now, we read the file into memory and throw away the
// contents, which
// still gives a speedup for large jar files since it reads sequentially and warms up the FS
// cache. we get a small slowdown
// for smaller jar files or for jar files already in the FS cache. eventually, we should
// actually use the bytes read and eliminate the slowdown
// 11/22/10: I can't figure out a way to actually use the bytes without hurting performance.
// Apparently,
// extracting files from a jar stored in memory via a JarInputStream is really slow compared
// to using
// a JarFile. Will leave this as is for now. --MS
// jarFileContents = archive instanceof JarFileModule ? getJarFileContents((JarFileModule)
// archive) : null;
getJarFileContents((JarFileModule) archive);
}
Set<ModuleEntry> classFiles = getClassFiles(archive);
removeClassFiles(classFiles, classModuleEntries);
Set<ModuleEntry> sourceFiles = getSourceFiles(archive);
Map<String, Object> allClassAndSourceFileContents = null;
if (OPTIMIZE_JAR_FILE_IO) {
// work in progress --MS
// if (archive instanceof JarFileModule) {
// final JarFileModule jfModule = (JarFileModule) archive;
// final String name = jfModule.getJarFile().getName();
// Map<String, Map<String, Long>> entrySizes = getEntrySizes(jfModule, name);
// allClassAndSourceFileContents = getAllClassAndSourceFileContents(jarFileContents, name,
// entrySizes);
// }
// jarFileContents = null;
}
loadAllClasses(classFiles, allClassAndSourceFileContents, isJMODType);
loadAllSources(sourceFiles);
classModuleEntries.addAll(classFiles);
sourceModuleEntries.addAll(sourceFiles);
}
}
@SuppressWarnings("unused")
private Map<String, Map<String, Long>> getEntrySizes(Module module, String name) {
Map<String, Map<String, Long>> result = HashMapFactory.make();
Map<String, Long> curFileResult = HashMapFactory.make();
for (ModuleEntry e : Iterator2Iterable.make(module.getEntries())) {
if (e.isModuleFile()) {
result.putAll(getEntrySizes(e.asModule(), e.getName()));
} else {
if (e instanceof JarFileEntry) {
curFileResult.put(e.getName(), ((JarFileEntry) e).getSize());
}
}
}
result.put(name, curFileResult);
return result;
}
/** get the contents of a jar file. if any IO exceptions occur, catch and return null. */
private static void getJarFileContents(JarFileModule archive) {
String jarFileName = archive.getJarFile().getName();
InputStream s = null;
try {
File jarFile = new FileProvider().getFile(jarFileName);
int bufferSize = 65536;
s = new BufferedInputStream(new FileInputStream(jarFile), bufferSize);
byte[] b = new byte[1024];
int n = s.read(b);
while (n != -1) {
n = s.read(b);
}
} catch (IOException e) {
} finally {
try {
if (s != null) {
s.close();
}
} catch (IOException e) {
}
}
}
@Override
public ClassLoaderReference getReference() {
return loader;
}
@Override
public Iterator<IClass> iterateAllClasses() {
return getAllClasses().iterator();
}
@SuppressWarnings("unused")
@Override
public IClass lookupClass(TypeName className) {
if (className == null) {
throw new IllegalArgumentException("className is null");
}
if (DEBUG_LEVEL > 1) {
System.err.println(this + ": lookupClass " + className);
}
// treat arrays specially:
if (className.isArrayType()) {
return arrayClassLoader.lookupClass(className, this, cha);
}
// try delegating first.
IClassLoader parent = getParent();
if (parent != null) {
IClass result = parent.lookupClass(className);
if (result != null) {
return result;
}
}
// delegating failed. Try our own namespace.
IClass result = loadedClasses.get(className);
return result;
}
/** Method getParent. */
@Override
public IClassLoader getParent() {
return parent;
}
@Override
public Atom getName() {
return loader.getName();
}
@Override
public Language getLanguage() {
return Language.JAVA;
}
@Override
public String toString() {
return getName().toString();
}
@Override
public int getNumberOfClasses() {
return getAllClasses().size();
}
@Override
public int getNumberOfMethods() {
int result = 0;
for (IClass klass : Iterator2Iterable.make(iterateAllClasses())) {
result += klass.getDeclaredMethods().size();
}
return result;
}
@Override
public String getSourceFileName(IClass klass) {
if (klass == null) {
throw new IllegalArgumentException("klass is null");
}
ModuleEntry e = sourceMap.get(klass.getName());
return e == null ? null : e.getName();
}
@Override
public Reader getSource(IMethod method, int offset) {
return getSource(method.getDeclaringClass());
}
@Override
public String getSourceFileName(IMethod method, int offset) {
return getSourceFileName(method.getDeclaringClass());
}
@Override
public Reader getSource(IClass klass) {
if (klass == null) {
throw new IllegalArgumentException("klass is null");
}
ModuleEntry e = sourceMap.get(klass.getName());
return e == null ? null : new InputStreamReader(e.getInputStream());
}
@Override
public void removeAll(Collection<IClass> toRemove) {
if (toRemove == null) {
throw new IllegalArgumentException("toRemove is null");
}
toRemove.stream().map(IClass::getName).peek(loadedClasses::remove).forEach(sourceMap::remove);
}
@Override
public SSAInstructionFactory getInstructionFactory() {
return getLanguage().instructionFactory();
}
}
| 22,344
| 32.50075
| 100
|
java
|
WALA
|
WALA-master/core/src/main/java/com/ibm/wala/classLoader/CodeScanner.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.classLoader;
import com.ibm.wala.shrike.shrikeCT.InvalidClassFileException;
import com.ibm.wala.ssa.SSAArrayLoadInstruction;
import com.ibm.wala.ssa.SSAArrayStoreInstruction;
import com.ibm.wala.ssa.SSACheckCastInstruction;
import com.ibm.wala.ssa.SSAGetCaughtExceptionInstruction;
import com.ibm.wala.ssa.SSAGetInstruction;
import com.ibm.wala.ssa.SSAInstruction;
import com.ibm.wala.ssa.SSAInstruction.Visitor;
import com.ibm.wala.ssa.SSAInvokeInstruction;
import com.ibm.wala.ssa.SSANewInstruction;
import com.ibm.wala.ssa.SSAPutInstruction;
import com.ibm.wala.types.FieldReference;
import com.ibm.wala.types.TypeReference;
import com.ibm.wala.util.collections.HashSetFactory;
import com.ibm.wala.util.collections.Iterator2Iterable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
/** Simple utilities to scan {@link IMethod}s to gather information without building an IR. */
public class CodeScanner {
/** @throws IllegalArgumentException if m is null */
public static Collection<CallSiteReference> getCallSites(IMethod m)
throws InvalidClassFileException {
if (m == null) {
throw new IllegalArgumentException("m is null");
}
if (m.isWalaSynthetic()) {
SyntheticMethod sm = (SyntheticMethod) m;
return getCallSites(sm.getStatements());
} else {
IBytecodeMethod<?> bm = (IBytecodeMethod<?>) m;
return bm.getCallSites();
}
}
/** @throws IllegalArgumentException if m is null */
public static Collection<FieldReference> getFieldsRead(IMethod m)
throws InvalidClassFileException {
if (m == null) {
throw new IllegalArgumentException("m is null");
}
if (m.isWalaSynthetic()) {
SyntheticMethod sm = (SyntheticMethod) m;
return getFieldsRead(sm.getStatements());
} else {
IBytecodeMethod<?> bm = (IBytecodeMethod<?>) m;
ArrayList<FieldReference> result = new ArrayList<>();
for (FieldReference fr : Iterator2Iterable.make(bm.getFieldsRead())) {
result.add(fr);
}
return result;
}
}
/** @throws IllegalArgumentException if m is null */
public static Collection<FieldReference> getFieldsWritten(IMethod m)
throws InvalidClassFileException {
if (m == null) {
throw new IllegalArgumentException("m is null");
}
if (m.isWalaSynthetic()) {
SyntheticMethod sm = (SyntheticMethod) m;
return getFieldsWritten(sm.getStatements());
} else {
IBytecodeMethod<?> bm = (IBytecodeMethod<?>) m;
ArrayList<FieldReference> result = new ArrayList<>();
for (FieldReference fr : Iterator2Iterable.make(bm.getFieldsWritten())) {
result.add(fr);
}
return result;
}
}
/** get the element types of the arrays that m may update */
public static Collection<TypeReference> getArraysWritten(IMethod m)
throws InvalidClassFileException {
if (m == null) {
throw new IllegalArgumentException("m is null");
}
if (m.isWalaSynthetic()) {
SyntheticMethod sm = (SyntheticMethod) m;
return getArraysWritten(sm.getStatements());
} else {
IBytecodeMethod<?> bm = (IBytecodeMethod<?>) m;
ArrayList<TypeReference> result = new ArrayList<>();
for (TypeReference tr : Iterator2Iterable.make(bm.getArraysWritten())) {
result.add(tr);
}
return result;
}
}
/** @throws IllegalArgumentException if m is null */
public static Collection<NewSiteReference> getNewSites(IMethod m)
throws InvalidClassFileException {
if (m == null) {
throw new IllegalArgumentException("m is null");
}
if (m.isWalaSynthetic()) {
SyntheticMethod sm = (SyntheticMethod) m;
return getNewSites(sm.getStatements());
} else {
IBytecodeMethod<?> bm = (IBytecodeMethod<?>) m;
return bm.getNewSites();
}
}
public static boolean hasObjectArrayLoad(IMethod m) throws InvalidClassFileException {
if (m == null) {
throw new IllegalArgumentException("m is null");
}
if (m.isWalaSynthetic()) {
SyntheticMethod sm = (SyntheticMethod) m;
return hasObjectArrayLoad(sm.getStatements());
} else {
return hasShrikeBTObjectArrayLoad((ShrikeCTMethod) m);
}
}
public static boolean hasObjectArrayStore(IMethod m) throws InvalidClassFileException {
if (m == null) {
throw new IllegalArgumentException("m is null");
}
if (m.isWalaSynthetic()) {
SyntheticMethod sm = (SyntheticMethod) m;
return hasObjectArrayStore(sm.getStatements());
} else {
return hasShrikeBTObjectArrayStore((ShrikeCTMethod) m);
}
}
public static Set<TypeReference> getCaughtExceptions(IMethod m) throws InvalidClassFileException {
if (m == null) {
throw new IllegalArgumentException("m is null");
}
if (m.isWalaSynthetic()) {
SyntheticMethod sm = (SyntheticMethod) m;
return getCaughtExceptions(sm.getStatements());
} else {
return getShrikeBTCaughtExceptions((ShrikeCTMethod) m);
}
}
/**
* Return the types this method may cast to
*
* @return iterator of TypeReference
* @throws IllegalArgumentException if m is null
*/
public static Iterator<TypeReference> iterateCastTypes(IMethod m)
throws InvalidClassFileException {
if (m == null) {
throw new IllegalArgumentException("m is null");
}
if (m.isWalaSynthetic()) {
SyntheticMethod sm = (SyntheticMethod) m;
return iterateCastTypes(sm.getStatements());
} else {
return iterateShrikeBTCastTypes((ShrikeCTMethod) m);
}
}
private static Iterator<TypeReference> iterateShrikeBTCastTypes(ShrikeCTMethod wrapper)
throws InvalidClassFileException {
return wrapper.getCastTypes();
}
private static Set<TypeReference> getShrikeBTCaughtExceptions(ShrikeCTMethod method)
throws InvalidClassFileException {
return method.getCaughtExceptionTypes();
}
private static boolean hasShrikeBTObjectArrayStore(ShrikeCTMethod M)
throws InvalidClassFileException {
for (TypeReference t : Iterator2Iterable.make(M.getArraysWritten())) {
if (t.isReferenceType()) {
return true;
}
}
return false;
}
private static boolean hasShrikeBTObjectArrayLoad(ShrikeCTMethod M)
throws InvalidClassFileException {
for (TypeReference tr : Iterator2Iterable.make(M.getArraysRead())) {
if (tr.isReferenceType()) {
return true;
}
}
return false;
}
/**
* @return {@link Set}<{@link TypeReference}>
* @throws IllegalArgumentException if statements == null
*/
public static Set<TypeReference> getCaughtExceptions(SSAInstruction[] statements)
throws IllegalArgumentException {
if (statements == null) {
throw new IllegalArgumentException("statements == null");
}
final HashSet<TypeReference> result = HashSetFactory.make(10);
Visitor v =
new Visitor() {
@Override
public void visitGetCaughtException(SSAGetCaughtExceptionInstruction instruction) {
Collection<TypeReference> t = instruction.getExceptionTypes();
result.addAll(t);
}
};
for (SSAInstruction s : statements) {
if (s != null) {
s.visit(v);
}
}
return result;
}
/** @throws IllegalArgumentException if statements == null */
public static Iterator<TypeReference> iterateCastTypes(SSAInstruction[] statements)
throws IllegalArgumentException {
if (statements == null) {
throw new IllegalArgumentException("statements == null");
}
final HashSet<TypeReference> result = HashSetFactory.make(10);
for (SSAInstruction statement : statements) {
if (statement != null) {
if (statement instanceof SSACheckCastInstruction) {
SSACheckCastInstruction c = (SSACheckCastInstruction) statement;
result.addAll(Arrays.asList(c.getDeclaredResultTypes()));
}
}
}
return result.iterator();
}
/**
* @param statements list of ssa statements
* @return List of InvokeInstruction
*/
private static List<CallSiteReference> getCallSites(SSAInstruction[] statements) {
final List<CallSiteReference> result = new ArrayList<>();
Visitor v =
new Visitor() {
@Override
public void visitInvoke(SSAInvokeInstruction instruction) {
result.add(instruction.getCallSite());
}
};
for (SSAInstruction s : statements) {
if (s != null) {
s.visit(v);
}
}
return result;
}
/**
* @param statements list of ssa statements
* @return List of InvokeInstruction
*/
private static List<NewSiteReference> getNewSites(SSAInstruction[] statements) {
final List<NewSiteReference> result = new ArrayList<>();
Visitor v =
new Visitor() {
@Override
public void visitNew(SSANewInstruction instruction) {
result.add(instruction.getNewSite());
}
};
for (SSAInstruction s : statements) {
if (s != null) {
s.visit(v);
}
}
return result;
}
/**
* @param statements list of ssa statements
* @return List of FieldReference
* @throws IllegalArgumentException if statements == null
*/
public static List<FieldReference> getFieldsRead(SSAInstruction[] statements)
throws IllegalArgumentException {
if (statements == null) {
throw new IllegalArgumentException("statements == null");
}
final List<FieldReference> result = new ArrayList<>();
Visitor v =
new Visitor() {
@Override
public void visitGet(SSAGetInstruction instruction) {
result.add(instruction.getDeclaredField());
}
};
for (SSAInstruction s : statements) {
if (s != null) {
s.visit(v);
}
}
return result;
}
/**
* @param statements list of ssa statements
* @return List of FieldReference
* @throws IllegalArgumentException if statements == null
*/
public static List<FieldReference> getFieldsWritten(SSAInstruction[] statements)
throws IllegalArgumentException {
if (statements == null) {
throw new IllegalArgumentException("statements == null");
}
final List<FieldReference> result = new ArrayList<>();
Visitor v =
new Visitor() {
@Override
public void visitPut(SSAPutInstruction instruction) {
result.add(instruction.getDeclaredField());
}
};
for (SSAInstruction s : statements) {
if (s != null) {
s.visit(v);
}
}
return result;
}
/**
* @param statements list of ssa statements
* @return List of TypeReference
* @throws IllegalArgumentException if statements == null
*/
public static List<TypeReference> getArraysWritten(SSAInstruction[] statements)
throws IllegalArgumentException {
if (statements == null) {
throw new IllegalArgumentException("statements == null");
}
final List<TypeReference> result = new ArrayList<>();
Visitor v =
new Visitor() {
@Override
public void visitArrayStore(SSAArrayStoreInstruction instruction) {
result.add(instruction.getElementType());
}
};
for (SSAInstruction s : statements) {
if (s != null) {
s.visit(v);
}
}
return result;
}
public static boolean hasObjectArrayLoad(SSAInstruction[] statements)
throws IllegalArgumentException {
if (statements == null) {
throw new IllegalArgumentException("statements == null");
}
class ScanVisitor extends Visitor {
boolean foundOne = false;
@Override
public void visitArrayLoad(SSAArrayLoadInstruction instruction) {
if (!instruction.typeIsPrimitive()) {
foundOne = true;
}
}
}
ScanVisitor v = new ScanVisitor();
for (SSAInstruction s : statements) {
if (s != null) {
s.visit(v);
}
if (v.foundOne) {
return true;
}
}
return false;
}
public static boolean hasObjectArrayStore(SSAInstruction[] statements)
throws IllegalArgumentException {
if (statements == null) {
throw new IllegalArgumentException("statements == null");
}
class ScanVisitor extends Visitor {
boolean foundOne = false;
@Override
public void visitArrayStore(SSAArrayStoreInstruction instruction) {
if (!instruction.typeIsPrimitive()) {
foundOne = true;
}
}
}
ScanVisitor v = new ScanVisitor();
for (SSAInstruction s : statements) {
if (s != null) {
s.visit(v);
}
if (v.foundOne) {
return true;
}
}
return false;
}
}
| 13,310
| 29.8125
| 100
|
java
|
WALA
|
WALA-master/core/src/main/java/com/ibm/wala/classLoader/CompoundModule.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.classLoader;
import com.ibm.wala.util.collections.NonNullSingletonIterator;
import com.ibm.wala.util.collections.Pair;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.LineNumberReader;
import java.net.URL;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class CompoundModule implements ModuleEntry, Module, SourceModule {
private final SourceModule[] constituents;
private final URL name;
public CompoundModule(URL name, SourceModule[] constituents) {
this.name = name;
this.constituents = constituents;
}
public SourceModule[] getConstituents() {
return constituents.clone();
}
@Override
public Iterator<ModuleEntry> getEntries() {
return new NonNullSingletonIterator<>(this);
}
@Override
public boolean isModuleFile() {
return false;
}
@Override
public Module asModule() {
throw new UnsupportedOperationException();
}
@Override
public String getClassName() {
throw new UnsupportedOperationException();
}
@Override
public String getName() {
return name.toString();
}
@Override
public URL getURL() {
return name;
}
@Override
public boolean isClassFile() {
return false;
}
@Override
public boolean isSourceFile() {
return true;
}
@Override
public InputStream getInputStream() {
return new InputStream() {
private int index = 0;
private InputStream currentStream;
@Override
public int read() throws IOException {
if (currentStream == null) {
if (index < constituents.length) {
currentStream = constituents[index++].getInputStream();
} else {
return -1;
}
}
int b = currentStream.read();
if (b == -1) {
currentStream = null;
return read();
}
return b;
}
};
}
public class Reader extends java.io.Reader {
private final List<Pair<Integer, URL>> locations = new ArrayList<>();
private int line = 0;
private int index = 0;
private LineNumberReader currentReader;
private URL currentName;
@Override
public int read(char[] cbuf, int off, int len) throws IOException {
if (currentReader == null) {
if (index < constituents.length) {
currentName = constituents[index].getURL();
currentReader =
new LineNumberReader(new InputStreamReader(constituents[index++].getInputStream()));
} else {
return -1;
}
}
int x;
if ((x = currentReader.read(cbuf, off, len)) == -1) {
line += currentReader.getLineNumber();
locations.add(Pair.make(line, currentName));
currentReader.close();
currentReader = null;
return read(cbuf, off, len);
}
return x;
}
@Override
public void close() throws IOException {
if (currentReader != null) {
currentReader.close();
currentReader = null;
}
}
public Pair<Integer, URL> getOriginalPosition(int lineNumber) {
int start = 0;
for (Pair<Integer, URL> location : locations) {
if (location.fst >= lineNumber) {
return Pair.make(lineNumber - start, location.snd);
} else {
start = location.fst;
}
}
throw new IllegalArgumentException("line number " + lineNumber + " too high");
}
}
@Override
public Reader getInputReader() {
return new Reader();
}
@Override
public Module getContainer() {
// stitched together module has no single container
return null;
}
}
| 4,058
| 23.305389
| 98
|
java
|
WALA
|
WALA-master/core/src/main/java/com/ibm/wala/classLoader/DirectoryTreeModule.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.classLoader;
import com.ibm.wala.util.collections.HashSetFactory;
import java.io.File;
import java.util.Iterator;
import java.util.Set;
/** A module containing files under some directory. */
public abstract class DirectoryTreeModule implements Module {
protected final File root;
/** @param root a directory */
DirectoryTreeModule(File root) throws IllegalArgumentException {
this.root = root;
if (root == null) {
throw new IllegalArgumentException("null root");
}
if (!root.exists()) {
throw new IllegalArgumentException("root does not exist " + root);
}
if (!root.isDirectory()) {
throw new IllegalArgumentException("root is not a directory " + root);
}
}
/** returns null if unsuccessful in creating FileModule */
protected abstract FileModule makeFile(File file);
protected abstract boolean includeFile(File file);
private Set<FileModule> getEntriesRecursive(File dir) {
Set<FileModule> result = HashSetFactory.make();
File[] files = dir.listFiles();
if (files != null) {
for (File file : files) {
if (file.isDirectory()) {
result.addAll(getEntriesRecursive(file));
} else if (includeFile(file)) {
FileModule fileModule = makeFile(file);
if (fileModule != null) {
result.add(fileModule);
}
}
}
} else {
// TODO: replace this with a real warning when the WarningSets are
// revamped
System.err.println(("Warning: failed to retrieve files in " + dir));
}
return result;
}
@Override
public Iterator<FileModule> getEntries() {
return getEntriesRecursive(root).iterator();
}
public String getPath() {
return root.getAbsolutePath();
}
@Override
public String toString() {
return getClass().getName() + ':' + getPath();
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((root == null) ? 0 : root.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 DirectoryTreeModule other = (DirectoryTreeModule) obj;
if (root == null) {
if (other.root != null) return false;
} else if (!root.equals(other.root)) return false;
return true;
}
}
| 2,809
| 27.383838
| 76
|
java
|
WALA
|
WALA-master/core/src/main/java/com/ibm/wala/classLoader/FieldImpl.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.classLoader;
import com.ibm.wala.core.util.strings.Atom;
import com.ibm.wala.ipa.cha.IClassHierarchy;
import com.ibm.wala.shrike.shrikeCT.ClassConstants;
import com.ibm.wala.types.FieldReference;
import com.ibm.wala.types.TypeReference;
import com.ibm.wala.types.annotations.Annotation;
import com.ibm.wala.types.annotations.TypeAnnotation;
import com.ibm.wala.types.generics.TypeSignature;
import java.util.Collection;
import java.util.Collections;
/**
* Implementation of a canonical field reference. TODO: canonicalize these? TODO: don't cache
* fieldType here .. move to class?
*/
public final class FieldImpl implements IField {
private final IClass declaringClass;
private final FieldReference fieldRef;
private final int accessFlags;
private final Collection<Annotation> annotations;
private final Collection<TypeAnnotation> typeAnnotations;
private final TypeSignature genericSignature;
public FieldImpl(
IClass declaringClass,
FieldReference canonicalRef,
int accessFlags,
Collection<Annotation> annotations,
TypeSignature sig) {
this(declaringClass, canonicalRef, accessFlags, annotations, null, sig);
}
public FieldImpl(
IClass declaringClass,
FieldReference canonicalRef,
int accessFlags,
Collection<Annotation> annotations,
Collection<TypeAnnotation> typeAnnotations,
TypeSignature sig) {
this.declaringClass = declaringClass;
this.fieldRef = canonicalRef;
this.accessFlags = accessFlags;
this.annotations = annotations;
this.typeAnnotations = typeAnnotations;
this.genericSignature = sig;
if (declaringClass == null) {
throw new IllegalArgumentException("null declaringClass");
}
if (fieldRef == null) {
throw new IllegalArgumentException("null canonicalRef");
}
}
public FieldImpl(
IClass declaringClass,
FieldReference canonicalRef,
int accessFlags,
Collection<Annotation> annotations) {
this(declaringClass, canonicalRef, accessFlags, annotations, null);
}
/** @return the genericSignature */
public TypeSignature getGenericSignature() {
return genericSignature;
}
/** @see com.ibm.wala.classLoader.IMember#getDeclaringClass() */
@Override
public IClass getDeclaringClass() {
return declaringClass;
}
@Override
public boolean equals(Object obj) {
// instanceof is OK because this class is final
if (obj instanceof FieldImpl) {
FieldImpl other = (FieldImpl) obj;
return fieldRef.equals(other.fieldRef) && declaringClass.equals(other.declaringClass);
} else {
return false;
}
}
@Override
public int hashCode() {
return 87049 * declaringClass.hashCode() + fieldRef.hashCode();
}
@Override
public String toString() {
FieldReference fr = getReference();
return fr.toString();
}
@Override
public FieldReference getReference() {
return FieldReference.findOrCreate(
getDeclaringClass().getReference(), getName(), getFieldTypeReference());
}
/** @see com.ibm.wala.classLoader.IMember#getName() */
@Override
public Atom getName() {
return fieldRef.getName();
}
@Override
public TypeReference getFieldTypeReference() {
return fieldRef.getFieldType();
}
@Override
public boolean isStatic() {
return ((accessFlags & ClassConstants.ACC_STATIC) != 0);
}
@Override
public boolean isFinal() {
return ((accessFlags & ClassConstants.ACC_FINAL) != 0);
}
@Override
public boolean isPrivate() {
return ((accessFlags & ClassConstants.ACC_PRIVATE) != 0);
}
@Override
public boolean isProtected() {
return ((accessFlags & ClassConstants.ACC_PROTECTED) != 0);
}
@Override
public boolean isPublic() {
return ((accessFlags & ClassConstants.ACC_PUBLIC) != 0);
}
@Override
public boolean isVolatile() {
return ((accessFlags & ClassConstants.ACC_VOLATILE) != 0);
}
@Override
public IClassHierarchy getClassHierarchy() {
return declaringClass.getClassHierarchy();
}
@Override
public Collection<Annotation> getAnnotations() {
return annotations == null ? null : Collections.unmodifiableCollection(annotations);
}
public Collection<TypeAnnotation> getTypeAnnotations() {
return typeAnnotations == null ? null : Collections.unmodifiableCollection(typeAnnotations);
}
}
| 4,766
| 26.396552
| 96
|
java
|
WALA
|
WALA-master/core/src/main/java/com/ibm/wala/classLoader/FileModule.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.classLoader;
import com.ibm.wala.util.collections.NonNullSingletonIterator;
import com.ibm.wala.util.debug.Assertions;
import com.ibm.wala.util.debug.UnimplementedError;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.Iterator;
/** A module which is a wrapper around a file in the filesystem */
public abstract class FileModule implements Module, ModuleEntry {
private final File file;
private final Module container;
public FileModule(File f, Module container) throws IllegalArgumentException {
if (f == null) {
throw new IllegalArgumentException("f is null");
}
this.file = f;
this.container = container;
if (!f.exists()) {
throw new IllegalArgumentException("bad file " + f.getAbsolutePath());
}
}
public String getAbsolutePath() {
return file.getAbsolutePath();
}
@Override
public Iterator<ModuleEntry> getEntries() {
return new NonNullSingletonIterator<>(this);
}
@Override
public int hashCode() {
return file.hashCode();
}
@Override
public boolean equals(Object o) {
if (o == null) {
return false;
}
if (o.getClass().equals(getClass())) {
FileModule other = (FileModule) o;
return getName().equals(other.getName());
} else {
return false;
}
}
@Override
public String getName() {
return file.getName();
}
@Override
public InputStream getInputStream() {
try {
if (!file.exists()) {
System.err.println("PANIC: File does not exist! " + file);
}
return new FileInputStream(file);
} catch (FileNotFoundException e) {
e.printStackTrace();
Assertions.UNREACHABLE("could not read " + file);
return null;
}
}
@Override
public boolean isModuleFile() {
return false;
}
/** @return Returns the file. */
public File getFile() {
return file;
}
@Override
public Module asModule() throws UnimplementedError {
Assertions.UNREACHABLE("implement me");
return null;
}
@Override
public Module getContainer() {
return container;
}
}
| 2,553
| 22.869159
| 79
|
java
|
WALA
|
WALA-master/core/src/main/java/com/ibm/wala/classLoader/IBytecodeMethod.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.classLoader;
import com.ibm.wala.shrike.shrikeBT.ExceptionHandler;
import com.ibm.wala.shrike.shrikeBT.IndirectionData;
import com.ibm.wala.shrike.shrikeCT.InvalidClassFileException;
import com.ibm.wala.types.FieldReference;
import com.ibm.wala.types.TypeReference;
import com.ibm.wala.types.annotations.Annotation;
import java.util.Collection;
import java.util.Iterator;
/** A method which originated in bytecode, decoded by Shrike */
public interface IBytecodeMethod<I> extends IMethod {
/** @return the bytecode index corresponding to instruction i in the getInstructions() array */
int getBytecodeIndex(int i) throws InvalidClassFileException;
/**
* @return the instuction index i in the getInstructions() array corresponding to the bytecode
* index bcIndex
*/
int getInstructionIndex(int bcIndex) throws InvalidClassFileException;
/** @return the Shrike representation of the exception handlers */
ExceptionHandler[][] getHandlers() throws InvalidClassFileException;
/** @return the Shrike instructions decoded from the bytecode */
I[] getInstructions() throws InvalidClassFileException;
/**
* there
*
* @return the call sites declared in the bytecode for this method
*/
Collection<CallSiteReference> getCallSites() throws InvalidClassFileException;
Iterator<FieldReference> getFieldsRead() throws InvalidClassFileException;
Iterator<FieldReference> getFieldsWritten() throws InvalidClassFileException;
Iterator<TypeReference> getArraysWritten() throws InvalidClassFileException;
/** @return the new sites declared in the bytecode for this method */
Collection<NewSiteReference> getNewSites() throws InvalidClassFileException;
/** @return information about any indirect uses of local variables */
IndirectionData getIndirectionData();
Collection<Annotation>[] getParameterAnnotations();
Collection<Annotation> getAnnotations(boolean runtimeInvisible) throws InvalidClassFileException;
}
| 2,358
| 36.444444
| 99
|
java
|
WALA
|
WALA-master/core/src/main/java/com/ibm/wala/classLoader/IClass.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.classLoader;
import com.ibm.wala.core.util.strings.Atom;
import com.ibm.wala.ipa.cha.IClassHierarchyDweller;
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 java.io.Reader;
import java.util.Collection;
import java.util.NoSuchElementException;
/**
* Basic interface for an object that represents a single Java class for analysis purposes,
* including array classes.
*/
public interface IClass extends IClassHierarchyDweller {
/**
* Return the object that represents the defining class loader for this class.
*
* @return the object that represents the defining class loader for this class.
*/
IClassLoader getClassLoader();
/** Is this class a Java interface? */
boolean isInterface();
/** @return true iff this class is abstract */
boolean isAbstract();
/** @return true iff this class is public */
boolean isPublic();
/** @return true iff this class is private */
boolean isPrivate();
/** @return true iff this class is synthetic, i.e., compiler-generated */
boolean isSynthetic();
/**
* Return the integer that encodes the class's modifiers, as defined by the JVM specification
*
* @return the integer that encodes the class's modifiers, as defined by the JVM specification
*/
int getModifiers() throws UnsupportedOperationException;
/**
* @return the superclass, or null if java.lang.Object
* @throws IllegalStateException if there's some problem determining the superclass
*/
IClass getSuperclass();
/**
* @return Collection of (IClass) interfaces this class directly implements. If this class is an
* interface, returns the interfaces it immediately extends.
*/
Collection<? extends IClass> getDirectInterfaces();
/**
* @return Collection of (IClass) interfaces this class implements, including all ancestors of
* interfaces immediately implemented. If this class is an interface, it returns all
* super-interfaces.
*/
Collection<IClass> getAllImplementedInterfaces();
/**
* Finds method matching signature. Delegates to superclass if not found.
*
* @param selector a method signature
* @return IMethod from this class matching the signature; null if not found in this class or any
* superclass.
*/
IMethod getMethod(Selector selector);
/**
* Finds a field.
*
* @throws IllegalStateException if the class contains multiple fields with name {@code name}.
*/
IField getField(Atom name);
/** Finds a field, given a name and a type. Returns {@code null} if not found. */
IField getField(Atom name, TypeName type);
/** @return canonical TypeReference corresponding to this class */
TypeReference getReference();
/**
* @return String holding the name of the source file that defined this class, or null if none
* found
* @throws NoSuchElementException if this class was generated from more than one source file The
* assumption that a class is generated from a single source file is java specific, and will
* change in the future. In place of this API, use the APIs in IClassLoader. SJF .. we should
* think about this deprecation. postponing deprecation for now.
*/
String getSourceFileName() throws NoSuchElementException;
/**
* @return String representing the source file holding this class, or null if not found
* @throws NoSuchElementException if this class was generated from more than one source file The
* assumption that a class is generated from a single source file is java specific, and will
* change in the future. In place of this API, use the APIs in IClassLoader. SJF .. we should
* think about this deprecation. postponing deprecation for now.
*/
Reader getSource() throws NoSuchElementException;
/** @return the method that is this class's initializer, or null if none */
IMethod getClassInitializer();
/** @return true iff the class is an array class. */
boolean isArrayClass();
/** @return an Iterator of the IMethods declared by this class. */
Collection<? extends IMethod> getDeclaredMethods();
/** Compute the instance fields declared by this class or any of its superclasses. */
Collection<IField> getAllInstanceFields();
/** Compute the static fields declared by this class or any of its superclasses. */
Collection<IField> getAllStaticFields();
/** Compute the instance and static fields declared by this class or any of its superclasses. */
Collection<IField> getAllFields();
/** Compute the methods declared by this class or any of its superclasses. */
Collection<? extends IMethod> getAllMethods();
/**
* Compute the instance fields declared by this class.
*
* @return Collection of IFields
*/
Collection<IField> getDeclaredInstanceFields();
/** @return Collection of IField */
Collection<IField> getDeclaredStaticFields();
/** @return the TypeName for this class */
TypeName getName();
/** Does 'this' refer to a reference type? If not, then it refers to a primitive type. */
boolean isReferenceType();
/** get annotations, if any */
Collection<Annotation> getAnnotations();
}
| 5,648
| 34.528302
| 99
|
java
|
WALA
|
WALA-master/core/src/main/java/com/ibm/wala/classLoader/IClassLoader.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.classLoader;
import com.ibm.wala.core.util.strings.Atom;
import com.ibm.wala.ssa.SSAInstructionFactory;
import com.ibm.wala.types.ClassLoaderReference;
import com.ibm.wala.types.TypeName;
import java.io.IOException;
import java.io.Reader;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.NoSuchElementException;
/** Base class for an object that represents a single Java classloader for analysis purposes. */
public interface IClassLoader {
/**
* Find and return the IClass defined by this class loader that corresponds to the given class
* name.
*
* @param className name of the class
* @return the IClass defined by this class loader that corresponds to the given class name, or
* null if not found.
*/
IClass lookupClass(TypeName className);
/**
* Return the ClassLoaderReference for this class loader.
*
* @return ClassLoaderReference
*/
ClassLoaderReference getReference();
/** @return an Iterator of all classes loaded by this loader */
Iterator<IClass> iterateAllClasses();
/** @return the number of classes in scope to be loaded by this loader */
int getNumberOfClasses();
/** @return the unique name that identifies this class loader. */
Atom getName();
/**
* @return the unique name that identifies the programming language from which this class loader
* loads code.
*/
Language getLanguage();
SSAInstructionFactory getInstructionFactory();
int getNumberOfMethods();
/**
* @param method The method for which information is desired
* @param offset an offset into the bytecode of the given method.
* @return name of the source file corresponding to the given offset in the given method. Note
* that this api allows a single method to arise from multiple source files, which is
* deliberate as it can happen in some languages.
*/
String getSourceFileName(IMethod method, int offset);
/**
* @param method The method for which information is desired
* @param offset an offset into the bytecode of the given method.
* @return input stream representing the source file for a given bytecode index of a given method,
* or null if not available
*/
Reader getSource(IMethod method, int offset);
/**
* @param klass the class for which information is desired.
* @return name of source file corresponding to the class, or null if not available
* @throws NoSuchElementException if this class was generated from more than one source file The
* assumption that a class is generated from a single source file is java specific, and will
* change in the future. In place of this API, use the version that takes a method and an
* offset, since that is now the granularity at which source file information will be
* recorded. SJF .. we should think about this deprecation. postponing deprecation for now.
*/
String getSourceFileName(IClass klass) throws NoSuchElementException;
/**
* @return input stream representing the source file for a class, or null if not available
* @throws NoSuchElementException if this class was generated from more than one source file The
* assumption that a class is generated from a single source file is java specific, and will
* change in the future. In place of this API, use the version that takes a method and an
* offset, since that is now the granularity at which source file information will be
* recorded. SJF .. we should think about this deprecation. postponing deprecation for now.
*/
Reader getSource(IClass klass) throws NoSuchElementException;
/** @return the parent IClassLoader, if any, or null */
IClassLoader getParent();
/**
* Initialize internal data structures.
*
* @throws IllegalArgumentException if modules is null
*/
void init(List<Module> modules) throws IOException;
/**
* blow away references to any classes in the set
*
* @param toRemove Collection<IClass>
*/
void removeAll(Collection<IClass> toRemove);
}
| 4,474
| 36.923729
| 100
|
java
|
WALA
|
WALA-master/core/src/main/java/com/ibm/wala/classLoader/IField.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.classLoader;
import com.ibm.wala.types.FieldReference;
import com.ibm.wala.types.TypeReference;
/** */
public interface IField extends IMember {
/** @return the canonical TypeReference of the declared type of the field */
TypeReference getFieldTypeReference();
/** @return canonical FieldReference representing this field */
FieldReference getReference();
/** Is this field final? */
boolean isFinal();
boolean isPrivate();
boolean isProtected();
boolean isPublic();
@Override
boolean isStatic();
/** Is this member volatile? */
boolean isVolatile();
}
| 985
| 23.65
| 78
|
java
|
WALA
|
WALA-master/core/src/main/java/com/ibm/wala/classLoader/IMember.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.classLoader;
import com.ibm.wala.core.util.strings.Atom;
import com.ibm.wala.ipa.cha.IClassHierarchyDweller;
import com.ibm.wala.types.annotations.Annotation;
import java.util.Collection;
/**
* Basic interface for an object that represents a single Java member (method or field) for analysis
* purposes.
*/
public interface IMember extends IClassHierarchyDweller {
/**
* Return the object that represents the declaring class for this member.
*
* @return the object that represents the declaring class for this member.
*/
IClass getDeclaringClass();
/** @return the name of this member */
Atom getName();
/** Is this member static? */
boolean isStatic();
/** Get the annotations on this member, if any */
Collection<Annotation> getAnnotations();
}
| 1,180
| 28.525
| 100
|
java
|
WALA
|
WALA-master/core/src/main/java/com/ibm/wala/classLoader/IMethod.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.classLoader;
import com.ibm.wala.ipa.callgraph.ContextItem;
import com.ibm.wala.shrike.shrikeCT.InvalidClassFileException;
import com.ibm.wala.types.Descriptor;
import com.ibm.wala.types.MethodReference;
import com.ibm.wala.types.Selector;
import com.ibm.wala.types.TypeReference;
/** Basic interface for an object that represents a single Java method for analysis purposes. */
public interface IMethod extends IMember, ContextItem {
/** Is this method synchronized? */
boolean isSynchronized();
/** Is this method a class initializer? */
boolean isClinit();
/** Is this method an object initializer? */
boolean isInit();
/** Is this method native? */
boolean isNative();
/**
* Is the implementation of this method a model generated by WALA? For compiler-generated
* synthetic methods, refer to {@link #isSynthetic()}
*/
boolean isWalaSynthetic();
/**
* Is this method synthetic, i.e., compiler-generated (this refers to the synthetic flag in
* java/dex bytecode)
*/
boolean isSynthetic();
/** Is this method abstract? */
boolean isAbstract();
/** Is this method private? */
boolean isPrivate();
/** Is this method protected? */
boolean isProtected();
/** Is this method public? */
boolean isPublic();
/** Is this method final? */
boolean isFinal();
/** Is this method a bridge method? See JLS 3rd Edition 15.12.4.5 */
boolean isBridge();
/** @return canonical MethodReference corresponding to this method */
MethodReference getReference();
/** @return true iff this method has at least one exception handler */
boolean hasExceptionHandler();
/** By convention, for a non-static method, getParameterType(0) is the this pointer */
TypeReference getParameterType(int i);
/** @return the name of the return type for this method */
TypeReference getReturnType();
/** Method getNumberOfParameters. This result includes the "this" pointer if applicable */
int getNumberOfParameters();
/**
* @return an array of the exception types declared by the throws clause for this method, or null
* if there are none
*/
TypeReference[] getDeclaredExceptions()
throws InvalidClassFileException, UnsupportedOperationException;
/**
* @return the source line number corresponding to a particular bytecode index, or -1 if the
* information is not available.
*/
int getLineNumber(int bcIndex);
/* BEGIN Custom change: precise positions */
interface SourcePosition extends Comparable<SourcePosition> {
int getFirstLine();
int getLastLine();
int getFirstCol();
int getLastCol();
int getFirstOffset();
int getLastOffset();
}
SourcePosition getSourcePosition(int instructionIndex) throws InvalidClassFileException;
SourcePosition getParameterSourcePosition(int paramNum) throws InvalidClassFileException;
/* END Custom change: precise positions */
/**
* @return the (source code) name of the local variable of a given number at the specified program
* counter, or null if the information is not available.
*/
String getLocalVariableName(int bcIndex, int localNumber);
/**
* something like:
* com.foo.bar.createLargeOrder(IILjava.lang.String;SLjava.sql.Date;)Ljava.lang.Integer;
*/
String getSignature();
/** something like: foo(Ljava/langString;)Ljava/lang/Class; */
Selector getSelector();
/** something like: (IILjava.lang.String;SLjava.sql.Date;)Ljava.lang.Integer; */
Descriptor getDescriptor();
/** @return true iff the local variable table information for this method is available */
boolean hasLocalVariableTable();
default int getNumberOfDefaultParameters() {
return 0;
}
boolean isAnnotation();
boolean isEnum();
boolean isModule();
}
| 4,168
| 28.153846
| 100
|
java
|
WALA
|
WALA-master/core/src/main/java/com/ibm/wala/classLoader/JVMClass.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.classLoader;
import com.ibm.wala.ipa.cha.IClassHierarchy;
import com.ibm.wala.shrike.shrikeBT.Constants;
import com.ibm.wala.shrike.shrikeCT.InvalidClassFileException;
import com.ibm.wala.types.MethodReference;
import com.ibm.wala.util.debug.Assertions;
/**
* Note that classes from JVML have some features that are not present in all "bytecode" languages
* currently supported.
*
* @param <T> type of classloader which loads this format of class.
*/
public abstract class JVMClass<T extends IClassLoader> extends BytecodeClass<T> {
protected JVMClass(T loader, IClassHierarchy cha) {
super(loader, cha);
}
/** JVM-level modifiers; cached here for efficiency */
protected int modifiers;
@Override
public int getModifiers() {
return modifiers;
}
@Override
public boolean isPublic() {
boolean result = ((modifiers & Constants.ACC_PUBLIC) != 0);
return result;
}
@Override
public boolean isPrivate() {
boolean result = ((modifiers & Constants.ACC_PRIVATE) != 0);
return result;
}
@Override
public boolean isInterface() {
boolean result = ((modifiers & Constants.ACC_INTERFACE) != 0);
return result;
}
/** @see com.ibm.wala.classLoader.IClass#isAbstract() */
@Override
public boolean isAbstract() {
boolean result = ((modifiers & Constants.ACC_ABSTRACT) != 0);
return result;
}
/** @see com.ibm.wala.classLoader.IClass#isSynthetic() */
@Override
public boolean isSynthetic() {
boolean result = ((modifiers & Constants.ACC_SYNTHETIC) != 0);
return result;
}
/** @see com.ibm.wala.classLoader.IClass#getClassInitializer() */
@Override
public IMethod getClassInitializer() {
try {
computeMethodMapIfNeeded();
} catch (InvalidClassFileException e) {
e.printStackTrace();
Assertions.UNREACHABLE();
}
return methodMap.get(MethodReference.clinitSelector);
}
}
| 2,292
| 26.626506
| 98
|
java
|
WALA
|
WALA-master/core/src/main/java/com/ibm/wala/classLoader/JarFileEntry.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.classLoader;
import com.ibm.wala.core.util.io.FileSuffixes;
import com.ibm.wala.util.debug.Assertions;
import java.io.InputStream;
import java.util.jar.JarFile;
/** An entry in a Jar file. */
public class JarFileEntry implements ModuleEntry {
private final String entryName;
private final JarFileModule jarFileModule;
protected JarFileEntry(String entryName, JarFileModule jarFile) {
this.entryName = entryName;
this.jarFileModule = jarFile;
}
@Override
public String getName() {
return entryName;
}
@Override
public boolean isClassFile() {
return FileSuffixes.isClassFile(getName());
}
@Override
public InputStream getInputStream() {
try {
JarFile jarFile = jarFileModule.getJarFile();
return jarFile.getInputStream(jarFile.getEntry(entryName));
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
Assertions.UNREACHABLE();
return null;
}
}
public long getSize() {
// TODO: cache this?
return jarFileModule.getJarFile().getEntry(entryName).getSize();
}
@Override
public String toString() {
return jarFileModule.getJarFile().getName() + ':' + getName();
}
@Override
public boolean isModuleFile() {
return FileSuffixes.isJarFile(getName()) || FileSuffixes.isWarFile(getName());
}
@Override
public Module asModule() {
return new NestedJarFileModule(jarFileModule, jarFileModule.getJarFile().getEntry(entryName));
}
public JarFile getJarFile() {
return jarFileModule.getJarFile();
}
@Override
public JarFileModule getContainer() {
return jarFileModule;
}
@Override
public int hashCode() {
return entryName.hashCode() * 5059 + jarFileModule.getJarFile().hashCode();
}
@Override
public String getClassName() {
return FileSuffixes.stripSuffix(getName());
}
@Override
public boolean isSourceFile() {
return FileSuffixes.isSourceFile(getName());
}
@Override
public boolean equals(Object obj) {
return this == obj;
}
}
| 2,443
| 22.728155
| 98
|
java
|
WALA
|
WALA-master/core/src/main/java/com/ibm/wala/classLoader/JarFileModule.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.classLoader;
import com.ibm.wala.core.util.ref.CacheReference;
import com.ibm.wala.util.collections.HashMapFactory;
import com.ibm.wala.util.debug.Assertions;
import com.ibm.wala.util.io.FileUtil;
import java.io.IOException;
import java.io.InputStream;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import java.util.zip.ZipEntry;
/** A module which is a wrapper around a Jar file */
public class JarFileModule implements Module {
private final JarFile file;
/**
* For efficiency, try to cache the byte[] holding each ZipEntries contents; this will help avoid
* multiple unzipping
*/
private final HashMap<ZipEntry, Object> cache = HashMapFactory.make();
public JarFileModule(JarFile f) {
if (f == null) {
throw new IllegalArgumentException("null f");
}
this.file = f;
}
public String getAbsolutePath() {
return file.getName();
}
@Override
public String toString() {
return "JarFileModule:" + file.getName();
}
protected ModuleEntry createEntry(ZipEntry z) {
return new JarFileEntry(z.getName(), this);
}
@Override
public Iterator<ModuleEntry> getEntries() {
return new Iterator<>() {
private final Enumeration<JarEntry> zipEntryEnumerator = file.entries();
@Override
public boolean hasNext() {
return zipEntryEnumerator.hasMoreElements();
}
@Override
public ModuleEntry next() {
return createEntry(zipEntryEnumerator.nextElement());
}
};
}
// need to do equals() and hashCode() based on file name, since JarFile
// does not implement equals() / hashCode()
@Override
public int hashCode() {
return file.getName().hashCode();
}
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (obj == null) return false;
if (getClass() != obj.getClass()) return false;
final JarFileModule other = (JarFileModule) obj;
if (!file.getName().equals(other.file.getName())) return false;
return true;
}
public byte[] getContents(ZipEntry entry) {
byte[] b = (byte[]) CacheReference.get(cache.get(entry));
if (b != null) {
return b;
}
try {
InputStream s = file.getInputStream(entry);
byte[] bb = FileUtil.readBytes(s);
cache.put(entry, CacheReference.make(bb));
s.close();
return bb;
} catch (IOException e) {
e.printStackTrace();
Assertions.UNREACHABLE();
return null;
}
}
public JarFile getJarFile() {
return file;
}
}
| 3,009
| 24.726496
| 99
|
java
|
WALA
|
WALA-master/core/src/main/java/com/ibm/wala/classLoader/JarStreamModule.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.classLoader;
import com.ibm.wala.core.util.io.FileSuffixes;
import com.ibm.wala.core.util.warnings.Warning;
import com.ibm.wala.core.util.warnings.Warnings;
import com.ibm.wala.util.collections.HashMapFactory;
import com.ibm.wala.util.debug.Assertions;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Iterator;
import java.util.jar.JarInputStream;
import java.util.zip.ZipEntry;
/**
* Read in a jar file from an input stream. Most parts are copied from the NestedJarFileModule class
* and adapted to work with an input stream.
*
* @author Juergen Graf <juergen.graf@gmail.com>
*/
public class JarStreamModule extends JarInputStream implements Module {
private static final boolean DEBUG = false;
/**
* For efficiency, we cache the byte[] holding each ZipEntry's contents; this will help avoid
* multiple unzipping TODO: use a soft reference?
*/
private HashMap<String, byte[]> cache = null;
public JarStreamModule(InputStream stream) throws IOException {
super(stream);
}
public InputStream getInputStream(String name) {
populateCache();
byte[] b = cache.get(name);
return new ByteArrayInputStream(b);
}
private void populateCache() {
if (cache != null) {
return;
}
cache = HashMapFactory.make();
try {
for (ZipEntry z = getNextEntry(); z != null; z = getNextEntry()) {
final String name = z.getName();
if (DEBUG) {
System.err.println(("got entry: " + name));
}
if (FileSuffixes.isClassFile(name) || FileSuffixes.isSourceFile(name)) {
ByteArrayOutputStream out = new ByteArrayOutputStream();
byte[] temp = new byte[1024];
int n = read(temp);
while (n != -1) {
out.write(temp, 0, n);
n = read(temp);
}
byte[] bb = out.toByteArray();
cache.put(name, bb);
}
}
} catch (IOException e) {
// just go with what we have
Warnings.add(
new Warning() {
@Override
public String getMsg() {
return "could not read contents of jar input stream.";
}
});
}
}
protected long getEntrySize(String name) {
populateCache();
byte[] b = cache.get(name);
return b.length;
}
@Override
public Iterator<ModuleEntry> getEntries() {
populateCache();
final Iterator<String> it = cache.keySet().iterator();
return new Iterator<>() {
String next = null;
{
advance();
}
private void advance() {
if (it.hasNext()) {
next = it.next();
} else {
next = null;
}
}
@Override
public boolean hasNext() {
return next != null;
}
@Override
public ModuleEntry next() {
ModuleEntry result = new Entry(next);
advance();
return result;
}
@Override
public void remove() {
Assertions.UNREACHABLE();
}
};
}
/** @author sfink an entry in a nested jar file. */
private class Entry implements ModuleEntry {
private final String name;
Entry(String name) {
this.name = name;
}
@Override
public String getName() {
return name;
}
@Override
public boolean isClassFile() {
return FileSuffixes.isClassFile(getName());
}
@Override
public InputStream getInputStream() {
return JarStreamModule.this.getInputStream(name);
}
@Override
public boolean isModuleFile() {
return false;
}
@Override
public Module asModule() {
Assertions.UNREACHABLE();
return null;
}
@Override
public String toString() {
return "nested entry: " + name;
}
@Override
public String getClassName() {
return FileSuffixes.stripSuffix(getName());
}
@Override
public boolean isSourceFile() {
return FileSuffixes.isSourceFile(getName());
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + getOuterType().hashCode();
result = prime * result + ((name == null) ? 0 : name.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;
Entry other = (Entry) obj;
if (!getOuterType().equals(other.getOuterType())) return false;
if (name == null) {
if (other.name != null) return false;
} else if (!name.equals(other.name)) return false;
return true;
}
private JarStreamModule getOuterType() {
return JarStreamModule.this;
}
@Override
public Module getContainer() {
return JarStreamModule.this;
}
}
@Override
public String toString() {
return "Jar input stream " + super.toString();
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + super.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;
JarStreamModule other = (JarStreamModule) obj;
return super.equals(other);
}
}
| 5,884
| 23.726891
| 100
|
java
|
WALA
|
WALA-master/core/src/main/java/com/ibm/wala/classLoader/JavaLanguage.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.classLoader;
import com.ibm.wala.analysis.typeInference.JavaPrimitiveType;
import com.ibm.wala.analysis.typeInference.PrimitiveType;
import com.ibm.wala.core.util.shrike.Exceptions.MethodResolutionFailure;
import com.ibm.wala.core.util.shrike.ShrikeUtil;
import com.ibm.wala.core.util.strings.Atom;
import com.ibm.wala.core.util.warnings.Warnings;
import com.ibm.wala.ipa.callgraph.AnalysisOptions;
import com.ibm.wala.ipa.callgraph.CGNode;
import com.ibm.wala.ipa.callgraph.IAnalysisCacheView;
import com.ibm.wala.ipa.callgraph.impl.AbstractRootMethod;
import com.ibm.wala.ipa.callgraph.impl.FakeRootClass;
import com.ibm.wala.ipa.callgraph.impl.FakeRootMethod;
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.ExtendedHeapModel;
import com.ibm.wala.ipa.modref.ModRef.ModVisitor;
import com.ibm.wala.ipa.modref.ModRef.RefVisitor;
import com.ibm.wala.shrike.shrikeBT.ConstantInstruction;
import com.ibm.wala.shrike.shrikeBT.ConstantInstruction.ClassToken;
import com.ibm.wala.shrike.shrikeBT.Constants;
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.IInstruction;
import com.ibm.wala.shrike.shrikeBT.IInvokeInstruction;
import com.ibm.wala.shrike.shrikeBT.IUnaryOpInstruction;
import com.ibm.wala.shrike.shrikeBT.Instruction;
import com.ibm.wala.shrike.shrikeCT.BootstrapMethodsReader.BootstrapMethod;
import com.ibm.wala.shrike.shrikeCT.ConstantPoolParser.ReferenceToken;
import com.ibm.wala.shrike.shrikeCT.InvalidClassFileException;
import com.ibm.wala.ssa.SSAAbstractBinaryInstruction;
import com.ibm.wala.ssa.SSAAbstractInvokeInstruction;
import com.ibm.wala.ssa.SSAAddressOfInstruction;
import com.ibm.wala.ssa.SSAArrayLengthInstruction;
import com.ibm.wala.ssa.SSAArrayLoadInstruction;
import com.ibm.wala.ssa.SSAArrayStoreInstruction;
import com.ibm.wala.ssa.SSABinaryOpInstruction;
import com.ibm.wala.ssa.SSACheckCastInstruction;
import com.ibm.wala.ssa.SSAComparisonInstruction;
import com.ibm.wala.ssa.SSAConditionalBranchInstruction;
import com.ibm.wala.ssa.SSAConversionInstruction;
import com.ibm.wala.ssa.SSAGetCaughtExceptionInstruction;
import com.ibm.wala.ssa.SSAGetInstruction;
import com.ibm.wala.ssa.SSAGotoInstruction;
import com.ibm.wala.ssa.SSAInstanceofInstruction;
import com.ibm.wala.ssa.SSAInstruction;
import com.ibm.wala.ssa.SSAInstructionFactory;
import com.ibm.wala.ssa.SSAInvokeDynamicInstruction;
import com.ibm.wala.ssa.SSAInvokeInstruction;
import com.ibm.wala.ssa.SSALoadIndirectInstruction;
import com.ibm.wala.ssa.SSALoadMetadataInstruction;
import com.ibm.wala.ssa.SSAMonitorInstruction;
import com.ibm.wala.ssa.SSANewInstruction;
import com.ibm.wala.ssa.SSAPhiInstruction;
import com.ibm.wala.ssa.SSAPiInstruction;
import com.ibm.wala.ssa.SSAPutInstruction;
import com.ibm.wala.ssa.SSAReturnInstruction;
import com.ibm.wala.ssa.SSAStoreIndirectInstruction;
import com.ibm.wala.ssa.SSASwitchInstruction;
import com.ibm.wala.ssa.SSAThrowInstruction;
import com.ibm.wala.ssa.SSAUnaryOpInstruction;
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.TypeName;
import com.ibm.wala.types.TypeReference;
import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodType;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
/** The implementation of {@link Language} which defines Java semantics. */
public class JavaLanguage extends LanguageImpl implements BytecodeLanguage, Constants {
public static class JavaInstructionFactory implements SSAInstructionFactory {
@Override
public SSAArrayLengthInstruction ArrayLengthInstruction(int iindex, int result, int arrayref) {
return new SSAArrayLengthInstruction(iindex, result, arrayref) {
@Override
public Collection<TypeReference> getExceptionTypes() {
return getNullPointerException();
}
};
}
@Override
public SSAArrayLoadInstruction ArrayLoadInstruction(
int iindex, int result, int arrayref, int index, TypeReference declaredType) {
return new SSAArrayLoadInstruction(iindex, result, arrayref, index, declaredType) {
@Override
public Collection<TypeReference> getExceptionTypes() {
return getArrayAccessExceptions();
}
};
}
@Override
public SSAArrayStoreInstruction ArrayStoreInstruction(
int iindex, int arrayref, int index, int value, TypeReference declaredType) {
return new SSAArrayStoreInstruction(iindex, arrayref, index, value, declaredType) {
@Override
public Collection<TypeReference> getExceptionTypes() {
if (typeIsPrimitive()) {
return getArrayAccessExceptions();
} else {
return getAaStoreExceptions();
}
}
};
}
@Override
public SSAAbstractBinaryInstruction BinaryOpInstruction(
int iindex,
IBinaryOpInstruction.IOperator operator,
boolean overflow,
boolean unsigned,
int result,
int val1,
int val2,
boolean mayBeInteger) {
assert !overflow;
// assert (!unsigned) : "BinaryOpInstuction: unsigned disallowed! iIndex: " + iindex + ",
// operation: " + val1 + " " + operator.toString() + " " + val2 ;
return new SSABinaryOpInstruction(iindex, operator, result, val1, val2, mayBeInteger) {
@Override
public SSAInstruction copyForSSA(SSAInstructionFactory insts, int[] defs, int[] uses) {
return insts.BinaryOpInstruction(
iIndex(),
getOperator(),
false,
false,
defs == null || defs.length == 0 ? getDef(0) : defs[0],
uses == null ? getUse(0) : uses[0],
uses == null ? getUse(1) : uses[1],
mayBeIntegerOp());
}
@Override
public Collection<TypeReference> getExceptionTypes() {
if (isPEI()) {
return getArithmeticException();
} else {
return Collections.emptySet();
}
}
};
}
@Override
public SSACheckCastInstruction CheckCastInstruction(
int iindex, int result, int val, int[] typeValues, boolean isPEI) {
throw new UnsupportedOperationException();
}
@Override
public SSACheckCastInstruction CheckCastInstruction(
int iindex, int result, int val, TypeReference[] types, boolean isPEI) {
assert types.length == 1;
assert isPEI;
return new SSACheckCastInstruction(iindex, result, val, types, true) {
@Override
public Collection<TypeReference> getExceptionTypes() {
return getClassCastException();
}
};
}
@Override
public SSACheckCastInstruction CheckCastInstruction(
int iindex, int result, int val, int typeValue, boolean isPEI) {
assert isPEI;
return CheckCastInstruction(iindex, result, val, new int[] {typeValue}, true);
}
@Override
public SSACheckCastInstruction CheckCastInstruction(
int iindex, int result, int val, TypeReference type, boolean isPEI) {
assert isPEI;
return CheckCastInstruction(iindex, result, val, new TypeReference[] {type}, true);
}
@Override
public SSAComparisonInstruction ComparisonInstruction(
int iindex, IComparisonInstruction.Operator operator, int result, int val1, int val2) {
return new SSAComparisonInstruction(iindex, operator, result, val1, val2);
}
@Override
public SSAConditionalBranchInstruction ConditionalBranchInstruction(
int iindex,
IConditionalBranchInstruction.IOperator operator,
TypeReference type,
int val1,
int val2,
int target) {
return new SSAConditionalBranchInstruction(iindex, operator, type, val1, val2, target);
}
@Override
public SSAConversionInstruction ConversionInstruction(
int iindex,
int result,
int val,
TypeReference fromType,
TypeReference toType,
boolean overflow) {
assert !overflow;
return new SSAConversionInstruction(iindex, result, val, fromType, toType) {
@Override
public SSAInstruction copyForSSA(SSAInstructionFactory insts, int[] defs, int[] uses)
throws IllegalArgumentException {
if (uses != null && uses.length == 0) {
throw new IllegalArgumentException("(uses != null) and (uses.length == 0)");
}
return insts.ConversionInstruction(
iIndex(),
defs == null || defs.length == 0 ? getDef(0) : defs[0],
uses == null ? getUse(0) : uses[0],
getFromType(),
getToType(),
false);
}
};
}
@Override
public SSAGetCaughtExceptionInstruction GetCaughtExceptionInstruction(
int iindex, int bbNumber, int exceptionValueNumber) {
return new SSAGetCaughtExceptionInstruction(iindex, bbNumber, exceptionValueNumber);
}
@Override
public SSAGetInstruction GetInstruction(int iindex, int result, FieldReference field) {
return new SSAGetInstruction(iindex, result, field) {};
}
@Override
public SSAGetInstruction GetInstruction(int iindex, int result, int ref, FieldReference field) {
return new SSAGetInstruction(iindex, result, ref, field) {
@Override
public Collection<TypeReference> getExceptionTypes() {
return getNullPointerException();
}
};
}
@Override
public SSAGotoInstruction GotoInstruction(int iindex, int target) {
return new SSAGotoInstruction(iindex, target);
}
@Override
public SSAInstanceofInstruction InstanceofInstruction(
int iindex, int result, int ref, TypeReference checkedType) {
return new SSAInstanceofInstruction(iindex, result, ref, checkedType);
}
@Override
public SSAAbstractInvokeInstruction InvokeInstruction(
int iindex,
int result,
int[] params,
int exception,
CallSiteReference site,
BootstrapMethod bootstrap) {
if (bootstrap != null) {
return new SSAInvokeDynamicInstruction(iindex, result, params, exception, site, bootstrap) {
@Override
public Collection<TypeReference> getExceptionTypes() {
if (!isStatic()) {
return getNullPointerException();
} else {
return Collections.emptySet();
}
}
};
} else {
return new SSAInvokeInstruction(iindex, result, params, exception, site) {
@Override
public Collection<TypeReference> getExceptionTypes() {
if (!isStatic()) {
return getNullPointerException();
} else {
return Collections.emptySet();
}
}
};
}
}
@Override
public SSAAbstractInvokeInstruction InvokeInstruction(
int iindex,
int[] params,
int exception,
CallSiteReference site,
BootstrapMethod bootstrap) {
// -1 is used to represent no result
return InvokeInstruction(iindex, -1, params, exception, site, bootstrap);
}
@Override
public SSAMonitorInstruction MonitorInstruction(int iindex, int ref, boolean isEnter) {
return new SSAMonitorInstruction(iindex, ref, isEnter) {
@Override
public Collection<TypeReference> getExceptionTypes() {
return getNullPointerException();
}
};
}
@Override
public SSANewInstruction NewInstruction(int iindex, int result, NewSiteReference site) {
return new SSANewInstruction(iindex, result, site) {
@Override
public Collection<TypeReference> getExceptionTypes() {
if (getNewSite().getDeclaredType().isArrayType()) {
return getNewArrayExceptions();
} else {
return getNewScalarExceptions();
}
}
};
}
@Override
public SSAPhiInstruction PhiInstruction(int iindex, int result, int[] params)
throws IllegalArgumentException {
return new SSAPhiInstruction(iindex, result, params) {};
}
@Override
public SSAPutInstruction PutInstruction(int iindex, int ref, int value, FieldReference field) {
return new SSAPutInstruction(iindex, ref, value, field) {
@Override
public Collection<TypeReference> getExceptionTypes() {
return getNullPointerException();
}
};
}
@Override
public SSAPutInstruction PutInstruction(int iindex, int value, FieldReference field) {
return new SSAPutInstruction(iindex, value, field) {};
}
@Override
public SSAReturnInstruction ReturnInstruction(int iindex) {
return new SSAReturnInstruction(iindex);
}
@Override
public SSAReturnInstruction ReturnInstruction(int iindex, int result, boolean isPrimitive) {
return new SSAReturnInstruction(iindex, result, isPrimitive);
}
@Override
public SSASwitchInstruction SwitchInstruction(
int iindex, int val, int defaultLabel, int[] casesAndLabels) {
return new SSASwitchInstruction(iindex, val, defaultLabel, casesAndLabels);
}
@Override
public SSAThrowInstruction ThrowInstruction(int iindex, int exception) {
return new SSAThrowInstruction(iindex, exception) {
@Override
public Collection<TypeReference> getExceptionTypes() {
return getNullPointerException();
}
};
}
@Override
public SSAUnaryOpInstruction UnaryOpInstruction(
int iindex, IUnaryOpInstruction.IOperator operator, int result, int val) {
return new SSAUnaryOpInstruction(iindex, operator, result, val);
}
@Override
public SSALoadMetadataInstruction LoadMetadataInstruction(
int iindex, int lval, TypeReference entityType, Object token) {
return new SSALoadMetadataInstruction(iindex, lval, entityType, token) {
@Override
public Collection<TypeReference> getExceptionTypes() {
return loadClassExceptions;
}
};
}
@Override
public SSANewInstruction NewInstruction(
int iindex, int result, NewSiteReference site, int[] params) {
return new SSANewInstruction(iindex, result, site, params) {
@Override
public Collection<TypeReference> getExceptionTypes() {
return getNewArrayExceptions();
}
};
}
@Override
public SSAPiInstruction PiInstruction(
int iindex, int result, int val, int piBlock, int successorBlock, SSAInstruction cause) {
return new SSAPiInstruction(iindex, result, val, piBlock, successorBlock, cause);
}
@Override
public SSAAddressOfInstruction AddressOfInstruction(
int iindex, int lval, int local, TypeReference pointeeType) {
throw new UnsupportedOperationException();
}
@Override
public SSAAddressOfInstruction AddressOfInstruction(
int iindex, int lval, int local, int indexVal, TypeReference pointeeType) {
throw new UnsupportedOperationException();
}
@Override
public SSAAddressOfInstruction AddressOfInstruction(
int iindex, int lval, int local, FieldReference field, TypeReference pointeeType) {
throw new UnsupportedOperationException();
}
@Override
public SSALoadIndirectInstruction LoadIndirectInstruction(
int iindex, int lval, TypeReference t, int addressVal) {
throw new UnsupportedOperationException();
}
@Override
public SSAStoreIndirectInstruction StoreIndirectInstruction(
int iindex, int addressVal, int rval, TypeReference pointeeType) {
throw new UnsupportedOperationException();
}
}
private static final Collection<TypeReference> arrayAccessExceptions =
Collections.unmodifiableCollection(
Arrays.asList(
new TypeReference[] {
TypeReference.JavaLangNullPointerException,
TypeReference.JavaLangArrayIndexOutOfBoundsException
}));
private static final Collection<TypeReference> aaStoreExceptions =
Collections.unmodifiableCollection(
Arrays.asList(
new TypeReference[] {
TypeReference.JavaLangNullPointerException,
TypeReference.JavaLangArrayIndexOutOfBoundsException,
TypeReference.JavaLangArrayStoreException
}));
private static final Collection<TypeReference> newScalarExceptions =
Collections.unmodifiableCollection(
Arrays.asList(
new TypeReference[] {
TypeReference.JavaLangExceptionInInitializerError,
TypeReference.JavaLangOutOfMemoryError
}));
private static final Collection<TypeReference> newArrayExceptions =
Collections.unmodifiableCollection(
Arrays.asList(
new TypeReference[] {
TypeReference.JavaLangOutOfMemoryError,
TypeReference.JavaLangNegativeArraySizeException
}));
private static final Collection<TypeReference> newSafeArrayExceptions =
Collections.unmodifiableCollection(
Arrays.asList(new TypeReference[] {TypeReference.JavaLangOutOfMemoryError}));
private static final Collection<TypeReference> exceptionInInitializerError =
Collections.singleton(TypeReference.JavaLangExceptionInInitializerError);
private static final Collection<TypeReference> nullPointerException =
Collections.singleton(TypeReference.JavaLangNullPointerException);
private static final Collection<TypeReference> arithmeticException =
Collections.singleton(TypeReference.JavaLangArithmeticException);
private static final Collection<TypeReference> classCastException =
Collections.singleton(TypeReference.JavaLangClassCastException);
private static final Collection<TypeReference> classNotFoundException =
Collections.singleton(TypeReference.JavaLangClassNotFoundException);
private static final Collection<TypeReference> loadClassExceptions =
Collections.singleton(TypeReference.JavaLangClassNotFoundException);
public static Collection<TypeReference> getAaStoreExceptions() {
return aaStoreExceptions;
}
public static Collection<TypeReference> getArithmeticException() {
return arithmeticException;
}
public static Collection<TypeReference> getArrayAccessExceptions() {
return arrayAccessExceptions;
}
public static Collection<TypeReference> getClassCastException() {
return classCastException;
}
public static Collection<TypeReference> getClassNotFoundException() {
return classNotFoundException;
}
public static Collection<TypeReference> getNewArrayExceptions() {
return newArrayExceptions;
}
public static Collection<TypeReference> getNewSafeArrayExceptions() {
return newSafeArrayExceptions;
}
public static Collection<TypeReference> getNewScalarExceptions() {
return newScalarExceptions;
}
public static Collection<TypeReference> getNullPointerException() {
return nullPointerException;
}
public static Collection<TypeReference> getExceptionInInitializerError() {
return exceptionInInitializerError;
}
@Override
public Atom getName() {
return ClassLoaderReference.Java;
}
@Override
public TypeReference getRootType() {
return TypeReference.JavaLangObject;
}
@Override
public TypeReference getThrowableType() {
return TypeReference.JavaLangThrowable;
}
@Override
public TypeReference getConstantType(Object o) {
if (o == null) {
// TODO: do we really want null here instead of TypeReference.Null?
// lots of code seems to depend on this being null.
return null;
} else if (o instanceof Boolean) {
return TypeReference.Boolean;
} else if (o instanceof Long) {
return TypeReference.Long;
} else if (o instanceof Double) {
return TypeReference.Double;
} else if (o instanceof Float) {
return TypeReference.Float;
} else if (o instanceof Number) {
return TypeReference.Int;
} else if (o instanceof String) {
return TypeReference.JavaLangString;
} else if (o instanceof ClassToken || o instanceof TypeReference) {
return TypeReference.JavaLangClass;
} else if (o instanceof IMethod) {
IMethod m = (IMethod) o;
return m.isInit()
? TypeReference.JavaLangReflectConstructor
: TypeReference.JavaLangReflectMethod;
} else if (o instanceof MethodHandle || o instanceof ReferenceToken) {
return TypeReference.JavaLangInvokeMethodHandle;
} else if (o instanceof MethodType) {
return TypeReference.JavaLangInvokeMethodType;
} else {
assert false : "unknown constant " + o + ": " + o.getClass();
return null;
}
}
@Override
public boolean isNullType(TypeReference type) {
return type == null || type == TypeReference.Null;
}
@Override
public TypeReference[] getArrayInterfaces() {
return new TypeReference[] {TypeReference.JavaIoSerializable, TypeReference.JavaLangCloneable};
}
@Override
public TypeName lookupPrimitiveType(String name) {
throw new UnsupportedOperationException();
}
/**
* @return {@link Collection}<{@link TypeReference}>, set of exception types a call to a
* declared target might throw.
* @throws IllegalArgumentException if target is null
* @throws IllegalArgumentException if cha is null
*/
@Override
public Collection<TypeReference> inferInvokeExceptions(
MethodReference target, IClassHierarchy cha) throws InvalidClassFileException {
if (cha == null) {
throw new IllegalArgumentException("cha is null");
}
if (target == null) {
throw new IllegalArgumentException("target is null");
}
ArrayList<TypeReference> set = new ArrayList<>(cha.getJavaLangRuntimeExceptionTypes());
set.addAll(cha.getJavaLangErrorTypes());
IClass klass = cha.lookupClass(target.getDeclaringClass());
if (klass == null) {
Warnings.add(MethodResolutionFailure.moderate(target));
}
if (klass != null) {
IMethod M = klass.getMethod(target.getSelector());
if (M == null) {
Warnings.add(MethodResolutionFailure.severe(target));
} else {
TypeReference[] exceptionTypes = M.getDeclaredExceptions();
if (exceptionTypes != null) {
set.addAll(Arrays.asList(exceptionTypes));
}
}
}
return set;
}
/**
* @param pei a potentially-excepting instruction
* @return the exception types that pei may throw, independent of the class hierarchy. null if
* none.
* <p>Notes
* <ul>
* <li>this method will <em>NOT</em> return the exception type explicitly thrown by an
* athrow
* <li>this method will <em>NOT</em> return the exception types that a called method may
* throw
* <li>this method ignores OutOfMemoryError
* <li>this method ignores linkage errors
* <li>this method ignores IllegalMonitorState exceptions
* </ul>
*
* @throws IllegalArgumentException if pei is null
*/
@Override
public Collection<TypeReference> getImplicitExceptionTypes(IInstruction pei) {
if (pei == null) {
throw new IllegalArgumentException("pei is null");
}
switch (((Instruction) pei).getOpcode()) {
case OP_iaload:
case OP_laload:
case OP_faload:
case OP_daload:
case OP_aaload:
case OP_baload:
case OP_caload:
case OP_saload:
case OP_iastore:
case OP_lastore:
case OP_fastore:
case OP_dastore:
case OP_bastore:
case OP_castore:
case OP_sastore:
return getArrayAccessExceptions();
case OP_aastore:
return getAaStoreExceptions();
case OP_getfield:
case OP_putfield:
case OP_invokevirtual:
case OP_invokespecial:
case OP_invokeinterface:
case OP_monitorenter:
case OP_monitorexit:
// we're currently ignoring MonitorStateExceptions, since J2EE stuff
// should be
// logically single-threaded
case OP_athrow:
// N.B: the caller must handle the explicitly-thrown exception
case OP_arraylength:
return getNullPointerException();
case OP_idiv:
case OP_irem:
case OP_ldiv:
case OP_lrem:
return getArithmeticException();
case OP_new:
return newScalarExceptions;
case OP_newarray:
case OP_anewarray:
case OP_multianewarray:
return newArrayExceptions;
case OP_checkcast:
return getClassCastException();
case OP_ldc_w:
if (((ConstantInstruction) pei).getType().equals(TYPE_Class))
return getClassNotFoundException();
else return null;
case OP_getstatic:
case OP_putstatic:
return getExceptionInInitializerError();
default:
return Collections.emptySet();
}
}
@Override
public SSAInstructionFactory instructionFactory() {
return javaShrikeFactory;
}
private static final SSAInstructionFactory javaShrikeFactory = new JavaInstructionFactory();
@Override
public boolean isDoubleType(TypeReference type) {
return type == TypeReference.Double;
}
@Override
public boolean isFloatType(TypeReference type) {
return type == TypeReference.Float;
}
@Override
public boolean isIntType(TypeReference type) {
return type == TypeReference.Int;
}
@Override
public boolean isLongType(TypeReference type) {
return type == TypeReference.Long;
}
@Override
public boolean isVoidType(TypeReference type) {
return type == TypeReference.Void;
}
@Override
public boolean isMetadataType(TypeReference type) {
return type == TypeReference.JavaLangClass
|| type == TypeReference.JavaLangInvokeMethodHandle
|| type == TypeReference.JavaLangInvokeMethodType;
}
@Override
public boolean isStringType(TypeReference type) {
return type == TypeReference.JavaLangString;
}
@Override
public boolean isBooleanType(TypeReference type) {
return type == TypeReference.Boolean;
}
@Override
public boolean isCharType(TypeReference type) {
return type == TypeReference.Char;
}
@Override
public Object getMetadataToken(Object value) {
if (value instanceof ClassToken) {
return ShrikeUtil.makeTypeReference(
ClassLoaderReference.Application, ((ClassToken) value).getTypeName());
} else if (value instanceof ReferenceToken) {
ReferenceToken tok = (ReferenceToken) value;
TypeReference cls =
ShrikeUtil.makeTypeReference(ClassLoaderReference.Application, 'L' + tok.getClassName());
return MethodReference.findOrCreate(
cls,
new Selector(
Atom.findOrCreateUnicodeAtom(tok.getElementName()),
Descriptor.findOrCreateUTF8(tok.getDescriptor())));
} else if (value instanceof MethodHandle || value instanceof MethodType) {
return value;
} else {
assert value instanceof TypeReference;
return value;
}
}
@Override
public TypeReference getPointerType(TypeReference pointee) throws UnsupportedOperationException {
throw new UnsupportedOperationException("Java does not permit explicit pointers");
}
@Override
public TypeReference getStringType() {
return TypeReference.JavaLangString;
}
static {
JavaPrimitiveType.init();
}
@Override
@SuppressWarnings("static-access")
public PrimitiveType getPrimitive(TypeReference reference) {
return JavaPrimitiveType.getPrimitive(reference);
}
@Override
public MethodReference getInvokeMethodReference(
ClassLoaderReference loader, IInvokeInstruction instruction) {
return MethodReference.findOrCreate(
this,
loader,
instruction.getClassType(),
instruction.getMethodName(),
instruction.getMethodSignature());
}
@Override
public boolean methodsHaveDeclaredParameterTypes() {
return true;
}
@Override
public AbstractRootMethod getFakeRootMethod(
IClassHierarchy cha, AnalysisOptions options, IAnalysisCacheView cache) {
return new FakeRootMethod(
new FakeRootClass(ClassLoaderReference.Primordial, cha), options, cache);
}
@Override
public <T extends InstanceKey> RefVisitor<T, ? extends ExtendedHeapModel> makeRefVisitor(
CGNode n, Collection<PointerKey> result, PointerAnalysis<T> pa, ExtendedHeapModel h) {
return new RefVisitor<>(n, result, pa, h);
}
@Override
public <T extends InstanceKey> ModVisitor<T, ? extends ExtendedHeapModel> makeModVisitor(
CGNode n,
Collection<PointerKey> result,
PointerAnalysis<T> pa,
ExtendedHeapModel h,
boolean ignoreAllocHeapDefs) {
return new ModVisitor<>(n, result, h, pa, ignoreAllocHeapDefs);
}
}
| 29,930
| 33.363949
| 100
|
java
|
WALA
|
WALA-master/core/src/main/java/com/ibm/wala/classLoader/Language.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.classLoader;
import com.ibm.wala.analysis.typeInference.PrimitiveType;
import com.ibm.wala.analysis.typeInference.TypeInference;
import com.ibm.wala.cfg.InducedCFG;
import com.ibm.wala.core.util.strings.Atom;
import com.ibm.wala.ipa.callgraph.AnalysisOptions;
import com.ibm.wala.ipa.callgraph.CGNode;
import com.ibm.wala.ipa.callgraph.Context;
import com.ibm.wala.ipa.callgraph.IAnalysisCacheView;
import com.ibm.wala.ipa.callgraph.impl.AbstractRootMethod;
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.ExtendedHeapModel;
import com.ibm.wala.ipa.modref.ModRef;
import com.ibm.wala.ipa.modref.ModRef.RefVisitor;
import com.ibm.wala.shrike.shrikeCT.InvalidClassFileException;
import com.ibm.wala.ssa.SSAInstruction;
import com.ibm.wala.ssa.SSAInstructionFactory;
import com.ibm.wala.ssa.SSALoadMetadataInstruction;
import com.ibm.wala.types.MethodReference;
import com.ibm.wala.types.TypeName;
import com.ibm.wala.types.TypeReference;
import java.util.Collection;
import java.util.Set;
/**
* Main interface for language-specific information. This interface helps build analyses which can
* operate over multiple languages.
*/
public interface Language {
/** The canonical {@link Language} implementation for Java */
JavaLanguage JAVA = new JavaLanguage();
/** What is the name of the language? */
Atom getName();
/** If this language is "derived" from some other langauge, which one? */
Language getBaseLanguage();
/** Yuck? Languages are mutable? */
void registerDerivedLanguage(Language l);
Set<Language> getDerivedLanguages();
/** What is the root type in a type hierarchy for this language? e.g. java.lang.Object in Java. */
TypeReference getRootType();
/** What is the root type of exceptions in this language? e.g. java.lang.Throwable in Java */
TypeReference getThrowableType();
/**
* Given a Java constant o, return the appropriate language type to associate with the constant.
* Possible types for o can be language dependent, but typically include Boolean, String, Integer,
* Float, etc.
*/
TypeReference getConstantType(Object o);
/** Is t the type of the language's null value? Should return true if {@code t == null} (?). */
boolean isNullType(TypeReference t);
boolean isIntType(TypeReference t);
boolean isLongType(TypeReference t);
boolean isVoidType(TypeReference t);
boolean isFloatType(TypeReference t);
boolean isDoubleType(TypeReference t);
boolean isStringType(TypeReference t);
/**
* Is t a "metadata" type for the language, i.e., a type describing some other type (e.g.,
* java.lang.Class for Java)?
*/
boolean isMetadataType(TypeReference t);
boolean isCharType(TypeReference t);
boolean isBooleanType(TypeReference t);
/**
* Get the representation of the meta-data corresponding to value. For example, in Java, if value
* represents some type, the returned object should be the corresponding {@link TypeReference}.
* The returned object should be appropriate for use as the token in an {@link
* SSALoadMetadataInstruction} for the language
*/
Object getMetadataToken(Object value);
/** get the interfaces implemented by all arrays in the language */
TypeReference[] getArrayInterfaces();
/**
* Given a source-level primitive type name, get the corresponding "low-level" type name, e.g.,
* the corresponding character to use in a Java method descriptor
*/
TypeName lookupPrimitiveType(String name);
SSAInstructionFactory instructionFactory();
/** determine the set of possible exception types a call to target may throw */
Collection<TypeReference> inferInvokeExceptions(MethodReference target, IClassHierarchy cha)
throws InvalidClassFileException;
TypeReference getStringType();
TypeReference getPointerType(TypeReference pointee);
/**
* get the abstraction of a primitive type to be used for type inference
*
* @see TypeInference
*/
PrimitiveType getPrimitive(TypeReference reference);
/** do MethodReference objects have declared parameter types? */
boolean methodsHaveDeclaredParameterTypes();
AbstractRootMethod getFakeRootMethod(
IClassHierarchy cha, AnalysisOptions options, IAnalysisCacheView cache);
InducedCFG makeInducedCFG(SSAInstruction[] instructions, IMethod method, Context context);
boolean modelConstant(Object o);
<T extends InstanceKey> RefVisitor<T, ? extends ExtendedHeapModel> makeRefVisitor(
CGNode n, Collection<PointerKey> result, PointerAnalysis<T> pa, ExtendedHeapModel h);
<T extends InstanceKey> ModRef.ModVisitor<T, ? extends ExtendedHeapModel> makeModVisitor(
CGNode n,
Collection<PointerKey> result,
PointerAnalysis<T> pa,
ExtendedHeapModel h,
boolean ignoreAllocHeapDefs);
}
| 5,369
| 34.562914
| 100
|
java
|
WALA
|
WALA-master/core/src/main/java/com/ibm/wala/classLoader/LanguageImpl.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.classLoader;
import com.ibm.wala.cfg.InducedCFG;
import com.ibm.wala.ipa.callgraph.Context;
import com.ibm.wala.ssa.SSAInstruction;
import com.ibm.wala.util.collections.HashSetFactory;
import java.util.Set;
/** Common functionality for most {@link Language} implementations. */
public abstract class LanguageImpl implements Language {
private Language baseLang;
private final Set<Language> derivedLangs = HashSetFactory.make();
public LanguageImpl() {}
public LanguageImpl(Language base) {
baseLang = base;
base.registerDerivedLanguage(this);
}
@Override
public Language getBaseLanguage() {
return baseLang;
}
@Override
public Set<Language> getDerivedLanguages() {
return derivedLangs;
}
@Override
public void registerDerivedLanguage(Language l) {
derivedLangs.add(l);
if (baseLang != null) baseLang.registerDerivedLanguage(l);
}
@Override
public int hashCode() {
return 1609 + 199 * getName().hashCode();
}
@Override
public boolean equals(Object o) {
if (!(o instanceof LanguageImpl)) return false;
LanguageImpl other = (LanguageImpl) o;
return getName().equals(other.getName());
}
@Override
public String toString() {
return getName().toString();
}
@Override
public InducedCFG makeInducedCFG(SSAInstruction[] instructions, IMethod method, Context context) {
return new InducedCFG(instructions, method, context);
}
@Override
public boolean modelConstant(Object o) {
return o instanceof String;
}
}
| 1,913
| 23.857143
| 100
|
java
|
WALA
|
WALA-master/core/src/main/java/com/ibm/wala/classLoader/Module.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.classLoader;
import java.util.Iterator;
/**
* A {@link Module} represents a set of files to analyze. eg., a Jar file. These are persistent
* (hung onto by {@link ClassLoaderImpl}) .. so, a Module should not hold onto a lot of data.
*/
public interface Module {
/** @return an Iterator of the ModuleEntries in this Module. */
Iterator<? extends ModuleEntry> getEntries();
}
| 780
| 30.24
| 95
|
java
|
WALA
|
WALA-master/core/src/main/java/com/ibm/wala/classLoader/ModuleEntry.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.classLoader;
import java.io.InputStream;
/** A ModuleEntry represents a wrapper around a file representation in a {@link Module}. */
public interface ModuleEntry {
/** @return a String that represents the name of the file described by this object */
String getName();
/** @return true if the file is a class file. */
boolean isClassFile();
/** @return true if the file is a source file. */
boolean isSourceFile();
/** @return an InputStream which provides the contents of this logical file. */
InputStream getInputStream();
/**
* @return true iff this module entry (file) represents a module in its own right. e.g., a jar
* file which is an entry in another jar file.
*/
boolean isModuleFile();
/**
* Precondition: isModuleFile().
*
* @return a Module view of this entry.
*/
Module asModule();
/**
* @return the name of the class represented by this entry
* @throws UnsupportedOperationException if !isClassFile() and !isSourceFile()
*/
String getClassName();
/** the containing module */
Module getContainer();
}
| 1,487
| 27.075472
| 96
|
java
|
WALA
|
WALA-master/core/src/main/java/com/ibm/wala/classLoader/NestedJarFileModule.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.classLoader;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.util.zip.ZipEntry;
public class NestedJarFileModule extends AbstractNestedJarFileModule {
private final JarFileModule parent;
private final ZipEntry entry;
public NestedJarFileModule(JarFileModule parent, ZipEntry entry) {
super(parent);
this.parent = parent;
this.entry = entry;
if (parent == null) {
throw new IllegalArgumentException("null parent");
}
if (entry == null) {
throw new IllegalArgumentException("null entry");
}
}
@Override
public InputStream getNestedContents() {
return new ByteArrayInputStream(parent.getContents(entry));
}
@Override
public String toString() {
return "Nested Jar File:" + entry.getName();
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((parent == null) ? 0 : parent.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;
NestedJarFileModule other = (NestedJarFileModule) obj;
if (parent == null) {
if (other.parent != null) return false;
} else if (!parent.equals(other.parent)) return false;
return true;
}
}
| 1,748
| 25.907692
| 73
|
java
|
WALA
|
WALA-master/core/src/main/java/com/ibm/wala/classLoader/NewSiteReference.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.classLoader;
import com.ibm.wala.ssa.IR;
import com.ibm.wala.types.TypeReference;
/**
* Represents a textual allocation site
*
* <p>Note that the identity of a {@link NewSiteReference} depends on two things: the program
* counter, and the containing {@link IR}. Thus, it suffices to defines equals() and hashCode() from
* ProgramCounter, since this class does not maintain a pointer to the containing IR (or CGNode)
* anyway. If using a hashtable of NewSiteReference from different IRs, you probably want to use a
* wrapper which also holds a pointer to the governing CGNode.
*/
public class NewSiteReference extends ProgramCounter {
/** The type allocated */
private final TypeReference declaredType;
/**
* @param programCounter bytecode index of the allocation site
* @param declaredType declared type that is allocated
*/
public NewSiteReference(int programCounter, TypeReference declaredType) {
super(programCounter);
this.declaredType = declaredType;
}
public TypeReference getDeclaredType() {
return declaredType;
}
public static NewSiteReference make(int programCounter, TypeReference declaredType) {
return new NewSiteReference(programCounter, declaredType);
}
@Override
public String toString() {
return "NEW " + declaredType + '@' + getProgramCounter();
}
}
| 1,733
| 31.716981
| 100
|
java
|
WALA
|
WALA-master/core/src/main/java/com/ibm/wala/classLoader/NoSuperclassFoundException.java
|
package com.ibm.wala.classLoader;
/**
* Indicates the superclass for a class was not found in the {@link
* com.ibm.wala.ipa.callgraph.AnalysisScope}
*/
public class NoSuperclassFoundException extends RuntimeException {
static final long serialVersionUID = 333L;
public NoSuperclassFoundException(String message) {
super(message);
}
}
| 350
| 22.4
| 67
|
java
|
WALA
|
WALA-master/core/src/main/java/com/ibm/wala/classLoader/PhantomClass.java
|
package com.ibm.wala.classLoader;
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.TypeReference;
import java.util.Collection;
import java.util.Collections;
/** dummy class representing a missing superclass */
public class PhantomClass extends SyntheticClass {
/** @param T type reference describing this class */
public PhantomClass(TypeReference T, IClassHierarchy cha) {
super(T, cha);
}
@Override
public boolean isPublic() {
return false;
}
@Override
public boolean isPrivate() {
return false;
}
@Override
public int getModifiers() throws UnsupportedOperationException {
throw new UnsupportedOperationException();
}
@Override
public IClass getSuperclass() {
return getClassHierarchy().getRootClass();
}
@Override
public Collection<? extends IClass> getDirectInterfaces() {
return Collections.emptySet();
}
@Override
public Collection<IClass> getAllImplementedInterfaces() {
return Collections.emptySet();
}
@Override
public IMethod getMethod(Selector selector) {
throw new UnsupportedOperationException();
}
@Override
public IField getField(Atom name) {
throw new UnsupportedOperationException();
}
@Override
public IMethod getClassInitializer() {
throw new UnsupportedOperationException();
}
@Override
public Collection<? extends IMethod> getDeclaredMethods() {
throw new UnsupportedOperationException();
}
@Override
public Collection<IField> getAllInstanceFields() {
throw new UnsupportedOperationException();
}
@Override
public Collection<IField> getAllStaticFields() {
throw new UnsupportedOperationException();
}
@Override
public Collection<IField> getAllFields() {
throw new UnsupportedOperationException();
}
@Override
public Collection<? extends IMethod> getAllMethods() {
throw new UnsupportedOperationException();
}
@Override
public Collection<IField> getDeclaredInstanceFields() {
throw new UnsupportedOperationException();
}
@Override
public Collection<IField> getDeclaredStaticFields() {
throw new UnsupportedOperationException();
}
@Override
public boolean isReferenceType() {
return true;
}
}
| 2,314
| 21.475728
| 66
|
java
|
WALA
|
WALA-master/core/src/main/java/com/ibm/wala/classLoader/ProgramCounter.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.classLoader;
/** Simple object that represents a program counter value (i.e., an instruction in the bytecode) */
public class ProgramCounter {
/** A constant indicating no source line number information is available. */
public static final int NO_SOURCE_LINE_NUMBER = -1;
/** Index into bytecode describing this instruction */
private final int programCounter;
/** @param programCounter Index into bytecode describing this instruction */
public ProgramCounter(final int programCounter) {
if (programCounter < 0) {
throw new IllegalArgumentException("illegal programCounter: " + programCounter);
}
this.programCounter = programCounter;
}
/**
* Return the program counter (index into the method's bytecode) for this call site.
*
* @return the program counter (index into the method's bytecode) for this call site.
*/
public int getProgramCounter() {
return programCounter;
}
/**
* A Program Counter value is enough to uniquely identify a call site reference within a method.
*
* <p>Note: must use these objects with extreme care; this only works if you never mix
* ProgramLocations from different methods in the same collection.
*/
@Override
public boolean equals(Object obj) {
return (obj instanceof ProgramCounter)
&& ((ProgramCounter) obj).programCounter == programCounter;
}
@Override
public int hashCode() {
return programCounter + 77;
}
@Override
public String toString() {
return "PC@" + programCounter;
}
}
| 1,926
| 30.590164
| 99
|
java
|
WALA
|
WALA-master/core/src/main/java/com/ibm/wala/classLoader/ResourceJarFileModule.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.classLoader;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
public class ResourceJarFileModule extends AbstractNestedJarFileModule {
private final URL resourceURL;
public ResourceJarFileModule(URL resourceURL) {
super(new SourceURLModule(resourceURL));
this.resourceURL = resourceURL;
}
@Override
protected InputStream getNestedContents() throws IOException {
return resourceURL.openConnection().getInputStream();
}
}
| 866
| 26.967742
| 72
|
java
|
WALA
|
WALA-master/core/src/main/java/com/ibm/wala/classLoader/ShrikeBTMethod.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.classLoader;
import com.ibm.wala.core.util.bytecode.BytecodeStream;
import com.ibm.wala.core.util.shrike.ShrikeUtil;
import com.ibm.wala.core.util.strings.Atom;
import com.ibm.wala.core.util.strings.ImmutableByteArray;
import com.ibm.wala.shrike.shrikeBT.BytecodeConstants;
import com.ibm.wala.shrike.shrikeBT.Constants;
import com.ibm.wala.shrike.shrikeBT.Decoder;
import com.ibm.wala.shrike.shrikeBT.ExceptionHandler;
import com.ibm.wala.shrike.shrikeBT.IArrayLoadInstruction;
import com.ibm.wala.shrike.shrikeBT.IArrayStoreInstruction;
import com.ibm.wala.shrike.shrikeBT.IGetInstruction;
import com.ibm.wala.shrike.shrikeBT.IInstruction;
import com.ibm.wala.shrike.shrikeBT.IInvokeInstruction;
import com.ibm.wala.shrike.shrikeBT.IPutInstruction;
import com.ibm.wala.shrike.shrikeBT.ITypeTestInstruction;
import com.ibm.wala.shrike.shrikeBT.MonitorInstruction;
import com.ibm.wala.shrike.shrikeBT.NewInstruction;
import com.ibm.wala.shrike.shrikeCT.InvalidClassFileException;
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.TypeName;
import com.ibm.wala.types.TypeReference;
import com.ibm.wala.util.collections.EmptyIterator;
import com.ibm.wala.util.collections.HashSetFactory;
import com.ibm.wala.util.debug.Assertions;
import java.lang.ref.SoftReference;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
/** A wrapper around a Shrike object that represents a method */
public abstract class ShrikeBTMethod implements IMethod, BytecodeConstants {
/** Some verbose progress output? */
private static final boolean verbose = false;
private static int methodsParsed = 0;
/** A wrapper around the declaring class. */
protected final IClass declaringClass;
/** Canonical reference for this method */
private MethodReference methodReference;
// break these out to save some space; they're computed lazily.
protected static class BytecodeInfo {
Decoder decoder;
CallSiteReference[] callSites;
FieldReference[] fieldsWritten;
FieldReference[] fieldsRead;
NewSiteReference[] newSites;
TypeReference[] arraysRead;
TypeReference[] arraysWritten;
TypeReference[] implicitExceptions;
TypeReference[] castTypes;
boolean hasMonitorOp;
/** Mapping from instruction index to program counter. */
private int[] pcMap;
/* BEGIN Custom change: precise positions */
/** Cached map representing position information for bytecode instruction at given index */
protected SourcePosition[] positionMap;
/** Sourcecode positions for method parameters */
protected SourcePosition[] paramPositionMap;
/* END Custom change: precise positions */
/**
* Cached map representing line number information in ShrikeCT format TODO: do more careful
* caching than just soft references
*/
protected int[] lineNumberMap;
/**
* an array mapping bytecode offsets to arrays representing the local variable maps for each
* offset; a local variable map is represented as an array of localVars*2 elements, containing a
* pair (nameIndex, typeIndex) for each local variable; a pair (0,0) indicates there is no
* information for that local variable at that offset
*/
protected int[][] localVariableMap;
/** Exception types this method might throw. Computed on demand. */
private TypeReference[] exceptionTypes;
}
/** Cache the information about the method statements. */
private SoftReference<BytecodeInfo> bcInfo;
public ShrikeBTMethod(IClass klass) {
this.declaringClass = klass;
}
protected synchronized BytecodeInfo getBCInfo() throws InvalidClassFileException {
BytecodeInfo result = null;
if (bcInfo != null) {
result = bcInfo.get();
}
if (result == null) {
result = computeBCInfo();
bcInfo = new SoftReference<>(result);
}
return result;
}
/** Return the program counter (bytecode index) for a particular Shrike instruction index. */
public int getBytecodeIndex(int instructionIndex) throws InvalidClassFileException {
return getBCInfo().pcMap[instructionIndex];
}
/**
* Return the Shrike instruction index for a particular valid program counter (bytecode index), or
* -1 if the Shrike instriction index could not be determined.
*
* <p>This ShrikeBTMethod must not be native.
*/
public int getInstructionIndex(int bcIndex) throws InvalidClassFileException {
if (isNative()) {
throw new UnsupportedOperationException(
"getInstructionIndex(int bcIndex) is only supported for non-native bytecode");
}
final BytecodeInfo info = getBCInfo();
if (info.decoder.containsSubroutines()) return -1;
final int[] pcMap = info.pcMap;
assert isSorted(pcMap);
int iindex = Arrays.binarySearch(pcMap, bcIndex);
if (iindex < 0) return -1;
// Unfortunately, pcMap is not always *strictly* sorted: given bcIndex, there may be multiple
// adjacent indices
// i,j such that pcMap[i] == bcIndex == pcMap[j]. We pick the least such index.
while (iindex > 0 && pcMap[iindex - 1] == bcIndex) iindex--;
return iindex;
}
private static boolean isSorted(int[] a) {
for (int i = 0; i < a.length - 1; i++) {
if (a[i + 1] < a[i]) return false;
}
return true;
}
/** Return the number of Shrike instructions for this method. */
public int getNumShrikeInstructions() throws InvalidClassFileException {
return getBCInfo().pcMap.length;
}
public Collection<CallSiteReference> getCallSites() throws InvalidClassFileException {
return isNative() || getBCInfo().callSites == null
? Collections.emptySet()
: Collections.unmodifiableCollection(Arrays.asList(getBCInfo().callSites));
}
public Collection<NewSiteReference> getNewSites() throws InvalidClassFileException {
return (isNative() || getBCInfo().newSites == null)
? Collections.emptySet()
: Collections.unmodifiableCollection(Arrays.asList(getBCInfo().newSites));
}
/**
* @return {@link Set}<{@link TypeReference}>, the exceptions that statements in this method
* may throw,
*/
public Collection<TypeReference> getImplicitExceptionTypes() throws InvalidClassFileException {
if (isNative()) {
return Collections.emptySet();
}
return (getBCInfo().implicitExceptions == null)
? Collections.emptyList()
: Arrays.asList(getBCInfo().implicitExceptions);
}
/**
* Do a cheap pass over the bytecodes to collect some mapping information. Some methods require
* this as a pre-req to accessing ShrikeCT information.
*/
private BytecodeInfo computeBCInfo() throws InvalidClassFileException {
BytecodeInfo result = new BytecodeInfo();
result.exceptionTypes = computeDeclaredExceptions();
if (isNative()) {
return result;
}
if (verbose) {
methodsParsed += 1;
if (methodsParsed % 100 == 0) {
System.out.println(methodsParsed + " methods processed...");
}
}
processBytecodesWithShrikeBT(result);
return result;
}
/** @return true iff this method has a monitorenter or monitorexit */
public boolean hasMonitorOp() throws InvalidClassFileException {
if (isNative()) {
return false;
}
return getBCInfo().hasMonitorOp;
}
/** @return Set of FieldReference */
public Iterator<FieldReference> getFieldsWritten() throws InvalidClassFileException {
if (isNative()) {
return EmptyIterator.instance();
}
if (getBCInfo().fieldsWritten == null) {
return EmptyIterator.instance();
} else {
List<FieldReference> l = Arrays.asList(getBCInfo().fieldsWritten);
return l.iterator();
}
}
/** @return Iterator of FieldReference */
public Iterator<FieldReference> getFieldsRead() throws InvalidClassFileException {
if (isNative()) {
return EmptyIterator.instance();
}
if (getBCInfo().fieldsRead == null) {
return EmptyIterator.instance();
} else {
List<FieldReference> l = Arrays.asList(getBCInfo().fieldsRead);
return l.iterator();
}
}
/** @return Iterator of TypeReference */
public Iterator<TypeReference> getArraysRead() throws InvalidClassFileException {
if (isNative()) {
return EmptyIterator.instance();
}
return (getBCInfo().arraysRead == null)
? EmptyIterator.instance()
: Arrays.asList(getBCInfo().arraysRead).iterator();
}
/** @return Iterator of TypeReference */
public Iterator<TypeReference> getArraysWritten() throws InvalidClassFileException {
if (isNative()) {
return EmptyIterator.instance();
}
if (getBCInfo().fieldsRead == null) {
return EmptyIterator.instance();
} else {
List<TypeReference> list = Arrays.asList(getBCInfo().arraysWritten);
return list.iterator();
}
}
/** @return Iterator of TypeReference */
public Iterator<TypeReference> getCastTypes() throws InvalidClassFileException {
if (isNative()) {
return EmptyIterator.instance();
}
return (getBCInfo().castTypes == null)
? EmptyIterator.instance()
: Arrays.asList(getBCInfo().castTypes).iterator();
}
protected abstract byte[] getBytecodes();
/**
* Method getBytecodeStream.
*
* @return the bytecode stream for this method, or null if no bytecodes.
*/
public BytecodeStream getBytecodeStream() {
byte[] bytecodes = getBytecodes();
if (bytecodes == null) {
return null;
} else {
return new BytecodeStream(this, bytecodes);
}
}
protected abstract String getMethodName() throws InvalidClassFileException;
protected abstract String getMethodSignature() throws InvalidClassFileException;
private MethodReference computeMethodReference() {
try {
Atom name = Atom.findOrCreateUnicodeAtom(getMethodName());
ImmutableByteArray desc = ImmutableByteArray.make(getMethodSignature());
Descriptor D = Descriptor.findOrCreate(declaringClass.getClassLoader().getLanguage(), desc);
return MethodReference.findOrCreate(declaringClass.getReference(), name, D);
} catch (InvalidClassFileException e) {
Assertions.UNREACHABLE();
return null;
}
}
@Override
public MethodReference getReference() {
if (methodReference == null) {
methodReference = computeMethodReference();
}
return methodReference;
}
@Override
public boolean isClinit() {
return getReference().getSelector().equals(MethodReference.clinitSelector);
}
@Override
public boolean isInit() {
return getReference().getName().equals(MethodReference.initAtom);
}
protected abstract int getModifiers();
@Override
public boolean isNative() {
return ((getModifiers() & Constants.ACC_NATIVE) != 0);
}
@Override
public boolean isAbstract() {
return ((getModifiers() & Constants.ACC_ABSTRACT) != 0);
}
@Override
public boolean isPrivate() {
return ((getModifiers() & Constants.ACC_PRIVATE) != 0);
}
@Override
public boolean isProtected() {
return ((getModifiers() & Constants.ACC_PROTECTED) != 0);
}
@Override
public boolean isPublic() {
return ((getModifiers() & Constants.ACC_PUBLIC) != 0);
}
@Override
public boolean isFinal() {
return ((getModifiers() & Constants.ACC_FINAL) != 0);
}
@Override
public boolean isBridge() {
return ((getModifiers() & Constants.ACC_VOLATILE) != 0);
}
@Override
public boolean isSynchronized() {
return ((getModifiers() & Constants.ACC_SYNCHRONIZED) != 0);
}
@Override
public boolean isStatic() {
return ((getModifiers() & Constants.ACC_STATIC) != 0);
}
@Override
public boolean isSynthetic() {
return ((getModifiers() & Constants.ACC_SYNTHETIC) != 0);
}
@Override
public boolean isAnnotation() {
return ((getModifiers() & Constants.ACC_ANNOTATION) != 0);
}
@Override
public boolean isEnum() {
return ((getModifiers() & Constants.ACC_ENUM) != 0);
}
@Override
public boolean isModule() {
return ((getModifiers() & Constants.ACC_MODULE) != 0);
}
@Override
public boolean isWalaSynthetic() {
return false;
}
@Override
public IClass getDeclaringClass() {
return declaringClass;
}
/**
* Find the decoder object for this method, or create one if necessary.
*
* @return null if the method has no code.
*/
protected abstract Decoder makeDecoder();
/** Walk through the bytecodes and collect trivial information. */
protected abstract void processDebugInfo(BytecodeInfo bcInfo) throws InvalidClassFileException;
private void processBytecodesWithShrikeBT(BytecodeInfo info) throws InvalidClassFileException {
info.decoder = makeDecoder();
if (!isAbstract() && info.decoder == null) {
throw new InvalidClassFileException(
-1, "non-abstract method " + getReference() + " has no bytecodes");
}
if (info.decoder == null) {
return;
}
info.pcMap = info.decoder.getInstructionsToBytecodes();
processDebugInfo(info);
SimpleVisitor simpleVisitor = new SimpleVisitor(info);
BytecodeLanguage lang = (BytecodeLanguage) getDeclaringClass().getClassLoader().getLanguage();
IInstruction[] instructions = info.decoder.getInstructions();
for (int i = 0; i < instructions.length; i++) {
simpleVisitor.setInstructionIndex(i);
instructions[i].visit(simpleVisitor);
if (instructions[i].isPEI()) {
Collection<TypeReference> t = lang.getImplicitExceptionTypes(instructions[i]);
if (t != null) {
simpleVisitor.implicitExceptions.addAll(t);
}
}
}
// copy the Set results into arrays; will use less
// storage
copyVisitorSetsToArrays(simpleVisitor, info);
}
private static void copyVisitorSetsToArrays(SimpleVisitor simpleVisitor, BytecodeInfo info) {
info.newSites = new NewSiteReference[simpleVisitor.newSites.size()];
int i = 0;
for (NewSiteReference newSiteReference : simpleVisitor.newSites) {
info.newSites[i++] = newSiteReference;
}
info.fieldsRead = new FieldReference[simpleVisitor.fieldsRead.size()];
i = 0;
for (FieldReference fieldReference : simpleVisitor.fieldsRead) {
info.fieldsRead[i++] = fieldReference;
}
info.fieldsRead = new FieldReference[simpleVisitor.fieldsRead.size()];
i = 0;
for (FieldReference fieldReference : simpleVisitor.fieldsRead) {
info.fieldsRead[i++] = fieldReference;
}
info.fieldsWritten = new FieldReference[simpleVisitor.fieldsWritten.size()];
i = 0;
for (FieldReference fieldReference : simpleVisitor.fieldsWritten) {
info.fieldsWritten[i++] = fieldReference;
}
info.callSites = new CallSiteReference[simpleVisitor.callSites.size()];
i = 0;
for (CallSiteReference callSiteReference : simpleVisitor.callSites) {
info.callSites[i++] = callSiteReference;
}
info.arraysRead = new TypeReference[simpleVisitor.arraysRead.size()];
i = 0;
for (TypeReference typeReference : simpleVisitor.arraysRead) {
info.arraysRead[i++] = typeReference;
}
info.arraysWritten = new TypeReference[simpleVisitor.arraysWritten.size()];
i = 0;
for (TypeReference typeReference : simpleVisitor.arraysWritten) {
info.arraysWritten[i++] = typeReference;
}
info.implicitExceptions = new TypeReference[simpleVisitor.implicitExceptions.size()];
i = 0;
for (TypeReference typeReference : simpleVisitor.implicitExceptions) {
info.implicitExceptions[i++] = typeReference;
}
info.castTypes = new TypeReference[simpleVisitor.castTypes.size()];
i = 0;
for (TypeReference typeReference : simpleVisitor.castTypes) {
info.castTypes[i++] = typeReference;
}
info.hasMonitorOp = simpleVisitor.hasMonitorOp;
}
@Override
public String toString() {
return getReference().toString();
}
@Override
public boolean equals(Object obj) {
// instanceof is OK because this class is final.
// if (this.getClass().equals(obj.getClass())) {
if (obj instanceof ShrikeBTMethod) {
ShrikeBTMethod that = (ShrikeBTMethod) obj;
return (getDeclaringClass().equals(that.getDeclaringClass())
&& getReference().equals(that.getReference()));
} else {
return false;
}
}
@Override
public int hashCode() {
return 9661 * getReference().hashCode();
}
/** @see com.ibm.wala.classLoader.SyntheticMethod#getMaxLocals() */
public abstract int getMaxLocals();
// TODO: ShrikeBT should have a getMaxStack method on Decoder, I think.
public abstract int getMaxStackHeight();
@Override
public Atom getName() {
return getReference().getName();
}
@Override
public Descriptor getDescriptor() {
return getReference().getDescriptor();
}
/** A visitor used to process bytecodes */
private class SimpleVisitor extends IInstruction.Visitor {
private final BytecodeInfo info;
public SimpleVisitor(BytecodeInfo info) {
this.info = info;
}
// TODO: make a better Set implementation for these.
final Set<CallSiteReference> callSites = HashSetFactory.make(5);
final Set<FieldReference> fieldsWritten = HashSetFactory.make(5);
final Set<FieldReference> fieldsRead = HashSetFactory.make(5);
final Set<NewSiteReference> newSites = HashSetFactory.make(5);
final Set<TypeReference> arraysRead = HashSetFactory.make(5);
final Set<TypeReference> arraysWritten = HashSetFactory.make(5);
final Set<TypeReference> implicitExceptions = HashSetFactory.make(5);
final Set<TypeReference> castTypes = HashSetFactory.make(5);
boolean hasMonitorOp;
private int instructionIndex;
public void setInstructionIndex(int i) {
instructionIndex = i;
}
public int getProgramCounter() {
return info.pcMap[instructionIndex];
}
@Override
public void visitMonitor(MonitorInstruction instruction) {
hasMonitorOp = true;
}
@Override
public void visitNew(NewInstruction instruction) {
ClassLoaderReference loader = getReference().getDeclaringClass().getClassLoader();
TypeReference t = ShrikeUtil.makeTypeReference(loader, instruction.getType());
newSites.add(NewSiteReference.make(getProgramCounter(), t));
}
@Override
public void visitGet(IGetInstruction instruction) {
ClassLoaderReference loader = getReference().getDeclaringClass().getClassLoader();
FieldReference f =
FieldReference.findOrCreate(
loader,
instruction.getClassType(),
instruction.getFieldName(),
instruction.getFieldType());
fieldsRead.add(f);
}
@Override
public void visitPut(IPutInstruction instruction) {
ClassLoaderReference loader = getReference().getDeclaringClass().getClassLoader();
FieldReference f =
FieldReference.findOrCreate(
loader,
instruction.getClassType(),
instruction.getFieldName(),
instruction.getFieldType());
fieldsWritten.add(f);
}
@Override
public void visitInvoke(IInvokeInstruction instruction) {
IClassLoader loader = getDeclaringClass().getClassLoader();
MethodReference m =
MethodReference.findOrCreate(
loader.getLanguage(),
loader.getReference(),
instruction.getClassType(),
instruction.getMethodName(),
instruction.getMethodSignature());
int programCounter = getProgramCounter();
CallSiteReference site =
CallSiteReference.make(programCounter, m, instruction.getInvocationCode());
callSites.add(site);
}
@Override
public void visitArrayLoad(IArrayLoadInstruction instruction) {
arraysRead.add(
ShrikeUtil.makeTypeReference(
getDeclaringClass().getClassLoader().getReference(), instruction.getType()));
}
@Override
public void visitArrayStore(IArrayStoreInstruction instruction) {
arraysWritten.add(
ShrikeUtil.makeTypeReference(
getDeclaringClass().getClassLoader().getReference(), instruction.getType()));
}
@Override
public void visitCheckCast(ITypeTestInstruction instruction) {
for (String t : instruction.getTypes()) {
castTypes.add(
ShrikeUtil.makeTypeReference(getDeclaringClass().getClassLoader().getReference(), t));
}
}
}
/** */
public IInstruction[] getInstructions() throws InvalidClassFileException {
if (getBCInfo().decoder == null) {
return null;
} else {
return getBCInfo().decoder.getInstructions();
}
}
public ExceptionHandler[][] getHandlers() throws InvalidClassFileException {
if (getBCInfo().decoder == null) {
return null;
} else {
return getBCInfo().decoder.getHandlers();
}
}
/** By convention, for a non-static method, getParameterType(0) is the this pointer */
@Override
public TypeReference getParameterType(int i) {
if (!isStatic()) {
if (i == 0) {
return declaringClass.getReference();
} else {
return getReference().getParameterType(i - 1);
}
} else {
return getReference().getParameterType(i);
}
}
/**
* Method getNumberOfParameters. This result includes the "this" pointer if applicable
*
* @return int
*/
@Override
public int getNumberOfParameters() {
if (isStatic() || isClinit()) {
return getReference().getNumberOfParameters();
} else {
return getReference().getNumberOfParameters() + 1;
}
}
@Override
public abstract boolean hasExceptionHandler();
/** Clients should not modify the returned array. TODO: clone to avoid the problem? */
@Override
public TypeReference[] getDeclaredExceptions() throws InvalidClassFileException {
return (getBCInfo().exceptionTypes == null) ? new TypeReference[0] : getBCInfo().exceptionTypes;
}
protected abstract String[] getDeclaredExceptionTypeNames() throws InvalidClassFileException;
/** @see com.ibm.wala.classLoader.IMethod#getDeclaredExceptions() */
private TypeReference[] computeDeclaredExceptions() {
try {
String[] strings = getDeclaredExceptionTypeNames();
if (strings == null) return null;
ClassLoaderReference loader = getDeclaringClass().getClassLoader().getReference();
TypeReference[] result = new TypeReference[strings.length];
Arrays.setAll(
result,
i ->
TypeReference.findOrCreate(
loader, TypeName.findOrCreate(ImmutableByteArray.make('L' + strings[i]))));
return result;
} catch (InvalidClassFileException e) {
Assertions.UNREACHABLE();
return null;
}
}
/* BEGIN Custom change: precise bytecode positions */
@Override
public SourcePosition getSourcePosition(int bcIndex) throws InvalidClassFileException {
return (getBCInfo().positionMap == null) ? null : getBCInfo().positionMap[bcIndex];
}
@Override
public SourcePosition getParameterSourcePosition(int paramNum) throws InvalidClassFileException {
return (getBCInfo().paramPositionMap == null) ? null : getBCInfo().paramPositionMap[paramNum];
}
/* END Custom change: precise bytecode positions */
@Override
public int getLineNumber(int bcIndex) {
try {
return (getBCInfo().lineNumberMap == null) ? -1 : getBCInfo().lineNumberMap[bcIndex];
} catch (InvalidClassFileException e) {
return -1;
}
}
/** @return {@link Set}<{@link TypeReference}> */
public Set<TypeReference> getCaughtExceptionTypes() throws InvalidClassFileException {
ExceptionHandler[][] handlers = getHandlers();
if (handlers == null) {
return Collections.emptySet();
}
HashSet<TypeReference> result = HashSetFactory.make(10);
ClassLoaderReference loader = getReference().getDeclaringClass().getClassLoader();
for (ExceptionHandler[] handler : handlers) {
for (ExceptionHandler element : handler) {
TypeReference t = ShrikeUtil.makeTypeReference(loader, element.getCatchClass());
if (t == null) {
t = TypeReference.JavaLangThrowable;
}
result.add(t);
}
}
return result;
}
@Override
public String getSignature() {
return getReference().getSignature();
}
@Override
public Selector getSelector() {
return getReference().getSelector();
}
@Override
public abstract String getLocalVariableName(int bcIndex, int localNumber);
/*
* TODO: cache for efficiency?
*
* @see com.ibm.wala.classLoader.IMethod#hasLocalVariableTable()
*/
@Override
public abstract boolean hasLocalVariableTable();
/** Clear all optional cached data associated with this class. */
public void clearCaches() {
bcInfo = null;
}
}
| 25,582
| 30.16078
| 100
|
java
|
WALA
|
WALA-master/core/src/main/java/com/ibm/wala/classLoader/ShrikeCTMethod.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.classLoader;
import com.ibm.wala.classLoader.ShrikeClass.GetReader;
import com.ibm.wala.ipa.cha.IClassHierarchy;
import com.ibm.wala.shrike.shrikeBT.Decoder;
import com.ibm.wala.shrike.shrikeBT.IInstruction;
import com.ibm.wala.shrike.shrikeBT.IndirectionData;
import com.ibm.wala.shrike.shrikeBT.shrikeCT.CTDecoder;
import com.ibm.wala.shrike.shrikeCT.AnnotationsReader;
import com.ibm.wala.shrike.shrikeCT.AnnotationsReader.AnnotationType;
import com.ibm.wala.shrike.shrikeCT.ClassReader;
import com.ibm.wala.shrike.shrikeCT.ClassReader.AttrIterator;
import com.ibm.wala.shrike.shrikeCT.CodeReader;
import com.ibm.wala.shrike.shrikeCT.ExceptionsReader;
import com.ibm.wala.shrike.shrikeCT.InvalidClassFileException;
import com.ibm.wala.shrike.shrikeCT.LineNumberTableReader;
import com.ibm.wala.shrike.shrikeCT.LocalVariableTableReader;
import com.ibm.wala.shrike.shrikeCT.SignatureReader;
import com.ibm.wala.shrike.shrikeCT.SourceFileReader;
import com.ibm.wala.shrike.shrikeCT.SourcePositionTableReader;
import com.ibm.wala.shrike.shrikeCT.SourcePositionTableReader.Position;
import com.ibm.wala.shrike.shrikeCT.TypeAnnotationsReader;
import com.ibm.wala.types.ClassLoaderReference;
import com.ibm.wala.types.TypeReference;
import com.ibm.wala.types.annotations.Annotation;
import com.ibm.wala.types.annotations.TypeAnnotation;
import com.ibm.wala.types.generics.MethodTypeSignature;
import com.ibm.wala.util.collections.HashSetFactory;
import com.ibm.wala.util.debug.Assertions;
import java.io.IOException;
import java.util.Arrays;
import java.util.Collection;
/** A wrapper around a Shrike object that represents a method */
public final class ShrikeCTMethod extends ShrikeBTMethod implements IBytecodeMethod<IInstruction> {
/** The index of this method in the declaring class's method list according to Shrike CT. */
private final int shrikeMethodIndex;
/** JVM-level modifiers for this method a value of -1 means "uninitialized" */
private int modifiers = -1;
private final IClassHierarchy cha;
public ShrikeCTMethod(IClass klass, int index) {
super(klass);
if (klass == null) {
throw new IllegalArgumentException("klass is null");
}
this.shrikeMethodIndex = index;
this.cha = klass.getClassHierarchy();
}
@Override
public byte[] getBytecodes() {
CodeReader code = getCodeReader();
if (code == null) {
return null;
} else {
return code.getBytecode();
}
}
@Override
protected String getMethodName() throws InvalidClassFileException {
ClassReader reader = getClassReader();
return reader.getMethodName(shrikeMethodIndex);
}
@Override
protected String getMethodSignature() throws InvalidClassFileException {
ClassReader reader = getClassReader();
return reader.getMethodType(shrikeMethodIndex);
}
@Override
protected int getModifiers() {
if (modifiers == -1) {
modifiers = getClassReader().getMethodAccessFlags(shrikeMethodIndex);
}
return modifiers;
}
@Override
protected Decoder makeDecoder() {
CodeReader reader = getCodeReader();
if (reader == null) {
return null;
}
final Decoder d = new CTDecoder(reader);
try {
d.decode();
} catch (Decoder.InvalidBytecodeException ex) {
Assertions.UNREACHABLE();
}
return d;
}
@Override
public int getMaxLocals() {
CodeReader reader = getCodeReader();
return reader.getMaxLocals();
}
@Override
public int getMaxStackHeight() {
CodeReader reader = getCodeReader();
// note that Shrike returns the maximum index in the zero-indexed stack
// array.
// Instead, we want the max number of entries on the stack.
// So we add 1.
// Additionally, ShrikeBT may add additional stack entries with
// Constant instructions. We add an additional 1 to account for this,
// which seems to handle all ShrikeBT code generation patterns.
// TODO: ShrikeBT should have a getMaxStack method on Decoder, I think.
return reader.getMaxStack() + 2;
}
@Override
public boolean hasExceptionHandler() {
CodeReader reader = getCodeReader();
if (reader == null) return false;
int[] handlers = reader.getRawHandlers();
return handlers != null && handlers.length > 0;
}
@Override
protected String[] getDeclaredExceptionTypeNames() throws InvalidClassFileException {
ExceptionsReader reader = getExceptionReader();
if (reader == null) {
return null;
} else {
return reader.getClasses();
}
}
/* BEGIN Custom change: precise positions */
private static final class SPos implements SourcePosition {
String fileName;
final int firstLine;
final int lastLine;
final int firstCol;
final int lastCol;
private SPos(String fileName, int firstLine, int lastLine, int firstCol, int lastCol) {
this.firstLine = firstLine;
this.lastLine = lastLine;
this.firstCol = firstCol;
this.lastCol = lastCol;
this.fileName = fileName;
}
@Override
public int getFirstCol() {
return firstCol;
}
@Override
public int getFirstLine() {
return firstLine;
}
@Override
public int getFirstOffset() {
return 0;
}
@Override
public int getLastCol() {
return lastCol;
}
@Override
public int getLastLine() {
return lastLine;
}
@Override
public int getLastOffset() {
return 0;
}
@Override
public int compareTo(SourcePosition p) {
if (p != null) {
if (firstLine != p.getFirstLine()) {
return firstLine - p.getFirstLine();
} else if (firstCol != p.getFirstCol()) {
return firstCol - p.getFirstCol();
} else if (lastLine != p.getLastLine()) {
return lastLine - p.getLastLine();
} else if (lastCol != p.getLastCol()) {
return lastCol - p.getLastCol();
} else {
return 0;
}
} else {
return -1;
}
}
@Override
public String toString() {
return fileName + '(' + firstLine + ',' + firstCol + '-' + lastLine + ',' + lastCol + ')';
}
}
/* END Custom change: precise positions */
@Override
protected void processDebugInfo(BytecodeInfo bcInfo) throws InvalidClassFileException {
CodeReader cr = getCodeReader();
bcInfo.lineNumberMap = LineNumberTableReader.makeBytecodeToSourceMap(cr);
bcInfo.localVariableMap = LocalVariableTableReader.makeVarMap(cr);
/* BEGIN Custom change: precise bytecode positions */
Position param = null;
try {
param = SourcePositionTableReader.findParameterPosition(shrikeMethodIndex, cr);
} catch (IOException e) {
e.printStackTrace();
}
bcInfo.paramPositionMap = new SPos[getNumberOfParameters()];
if (param != null) {
String fileName = ((ShrikeClass) getDeclaringClass()).getSourceFileReader().getSourceFile();
SPos paramPos =
new SPos(fileName, param.firstLine, param.lastLine, param.firstCol, param.lastCol);
for (int i = 0; i < getNumberOfParameters(); i++) {
bcInfo.paramPositionMap[i] = paramPos;
}
}
Position pos[] = null;
try {
pos = SourcePositionTableReader.makeBytecodeToPositionMap(cr);
} catch (IOException e) {
e.printStackTrace();
}
if (pos == null && bcInfo.lineNumberMap != null) {
pos = SourcePositionTableReader.makeLineNumberToPositionMap(bcInfo.lineNumberMap);
}
if (pos != null) {
String sourceFile = null;
SourceFileReader reader = ((ShrikeClass) getDeclaringClass()).getSourceFileReader();
if (reader != null) {
sourceFile = reader.getSourceFile();
}
bcInfo.positionMap = new SPos[pos.length];
for (int i = 0; i < pos.length; i++) {
Position p = pos[i];
bcInfo.positionMap[i] =
new SPos(sourceFile, p.firstLine, p.lastLine, p.firstCol, p.lastCol);
}
}
/* END Custom change: : precise bytecode positions */
}
@Override
public String getLocalVariableName(int bcIndex, int localNumber) {
int[][] map = null;
try {
map = getBCInfo().localVariableMap;
} catch (InvalidClassFileException e1) {
return null;
}
if (localNumber > getMaxLocals()) {
throw new IllegalArgumentException(
"illegal local number: "
+ localNumber
+ ", method "
+ getDeclaringClass().getName()
+ '.'
+ getName()
+ " uses at most "
+ getMaxLocals());
}
if (map == null) {
return null;
} else {
int[] localPairs = map[bcIndex];
int localIndex = localNumber * 2;
if (localPairs == null || localIndex >= localPairs.length) {
// no information about the specified local at this program point
return null;
}
int nameIndex = localPairs[localIndex];
if (nameIndex == 0) {
return null;
} else {
try {
return getClassReader().getCP().getCPUtf8(nameIndex);
} catch (InvalidClassFileException e) {
e.printStackTrace();
Assertions.UNREACHABLE();
return null;
}
}
}
}
/*
* TODO: cache for efficiency?
*
* @see com.ibm.wala.classLoader.IMethod#hasLocalVariableTable()
*/
@Override
public boolean hasLocalVariableTable() {
try {
ClassReader.AttrIterator iter = new ClassReader.AttrIterator();
getCodeReader().initAttributeIterator(iter);
for (; iter.isValid(); iter.advance()) {
if (iter.getName().equals("LocalVariableTable")) {
return true;
}
}
return false;
} catch (InvalidClassFileException e) {
e.printStackTrace();
Assertions.UNREACHABLE();
return false;
}
}
private ClassReader getClassReader() {
return ((ShrikeClass) getDeclaringClass()).getReader();
}
private <T> T getReader(String attrName, GetReader<T> reader) {
ClassReader.AttrIterator iter = new AttrIterator();
getClassReader().initMethodAttributeIterator(shrikeMethodIndex, iter);
return ShrikeClass.getReader(iter, attrName, reader);
}
private CodeReader getCodeReader() {
return getReader("Code", CodeReader::new);
}
private ExceptionsReader getExceptionReader() {
return getReader("Exceptions", ExceptionsReader::new);
}
private SignatureReader getSignatureReader() {
return getReader("Signature", SignatureReader::new);
}
private AnnotationsReader getAnnotationsReader(AnnotationType type) {
ClassReader.AttrIterator iter = new AttrIterator();
getClassReader().initMethodAttributeIterator(shrikeMethodIndex, iter);
return AnnotationsReader.getReaderForAnnotation(type, iter);
}
private TypeAnnotationsReader getTypeAnnotationsReaderAtMethodInfo(
TypeAnnotationsReader.AnnotationType type) {
ClassReader.AttrIterator iter = new AttrIterator();
getClassReader().initMethodAttributeIterator(shrikeMethodIndex, iter);
return TypeAnnotationsReader.getReaderForAnnotationAtMethodInfo(
type, iter, getExceptionReader(), getSignatureReader());
}
private TypeAnnotationsReader getTypeAnnotationsReaderAtCode(
TypeAnnotationsReader.AnnotationType type) {
final CodeReader codeReader = getCodeReader();
if (codeReader == null) return null;
ClassReader.AttrIterator iter = new ClassReader.AttrIterator();
codeReader.initAttributeIterator(iter);
return TypeAnnotationsReader.getReaderForAnnotationAtCode(type, iter, getCodeReader());
}
private String computeGenericsSignature() throws InvalidClassFileException {
SignatureReader reader = getSignatureReader();
if (reader == null) {
return null;
} else {
return reader.getSignature();
}
}
@Override
public TypeReference getReturnType() {
return getReference().getReturnType();
}
@Override
public IClassHierarchy getClassHierarchy() {
return cha;
}
/**
* TODO: cache?
*
* @return raw "Signature" attribute from the bytecode
*/
private String getGenericsSignature() throws InvalidClassFileException {
return computeGenericsSignature();
}
/** UNDER CONSTRUCTION */
public MethodTypeSignature getMethodTypeSignature() throws InvalidClassFileException {
String sig = getGenericsSignature();
return sig == null ? null : MethodTypeSignature.make(sig);
}
/** read the runtime-invisible annotations from the class file */
public Collection<Annotation> getRuntimeInvisibleAnnotations() throws InvalidClassFileException {
return getAnnotations(true);
}
/** read the runtime-visible annotations from the class file */
public Collection<Annotation> getRuntimeVisibleAnnotations() throws InvalidClassFileException {
return getAnnotations(false);
}
@Override
public Collection<Annotation> getAnnotations(boolean runtimeInvisible)
throws InvalidClassFileException {
AnnotationsReader r =
getAnnotationsReader(
runtimeInvisible
? AnnotationType.RuntimeInvisibleAnnotations
: AnnotationType.RuntimeVisibleAnnotations);
return Annotation.getAnnotationsFromReader(
r, getDeclaringClass().getClassLoader().getReference());
}
public Collection<TypeAnnotation> getTypeAnnotationsAtMethodInfo(boolean runtimeInvisible)
throws InvalidClassFileException {
TypeAnnotationsReader r =
getTypeAnnotationsReaderAtMethodInfo(
runtimeInvisible
? TypeAnnotationsReader.AnnotationType.RuntimeInvisibleTypeAnnotations
: TypeAnnotationsReader.AnnotationType.RuntimeVisibleTypeAnnotations);
final ClassLoaderReference clRef = getDeclaringClass().getClassLoader().getReference();
return TypeAnnotation.getTypeAnnotationsFromReader(
r, TypeAnnotation.targetConverterAtMethodInfo(clRef), clRef);
}
public Collection<TypeAnnotation> getTypeAnnotationsAtCode(boolean runtimeInvisible)
throws InvalidClassFileException {
TypeAnnotationsReader r =
getTypeAnnotationsReaderAtCode(
runtimeInvisible
? TypeAnnotationsReader.AnnotationType.RuntimeInvisibleTypeAnnotations
: TypeAnnotationsReader.AnnotationType.RuntimeVisibleTypeAnnotations);
final ClassLoaderReference clRef = getDeclaringClass().getClassLoader().getReference();
return TypeAnnotation.getTypeAnnotationsFromReader(
r, TypeAnnotation.targetConverterAtCode(clRef, this), clRef);
}
@Override
public Collection<Annotation> getAnnotations() {
Collection<Annotation> result = HashSetFactory.make();
try {
result.addAll(getAnnotations(true));
result.addAll(getAnnotations(false));
} catch (InvalidClassFileException e) {
}
return result;
}
/**
* get annotations on parameters as an array of Collections, where each array element gives the
* annotations on the corresponding parameter. Note that the 'this' parameter for an instance
* method cannot have annotations.
*/
@Override
public Collection<Annotation>[] getParameterAnnotations() {
int numAnnotatedParams = isStatic() ? getNumberOfParameters() : getNumberOfParameters() - 1;
@SuppressWarnings("unchecked")
Collection<Annotation>[] result = new Collection[numAnnotatedParams];
Arrays.setAll(result, i -> HashSetFactory.make());
try {
ClassLoaderReference reference = getDeclaringClass().getClassLoader().getReference();
AnnotationsReader r =
getAnnotationsReader(AnnotationType.RuntimeInvisibleParameterAnnotations);
Collection<Annotation>[] paramAnnots =
Annotation.getParameterAnnotationsFromReader(r, reference);
if (paramAnnots != null) {
assert paramAnnots.length == result.length : paramAnnots.length + " != " + result.length;
for (int i = 0; i < result.length; i++) {
result[i].addAll(paramAnnots[i]);
}
}
r = getAnnotationsReader(AnnotationType.RuntimeVisibleParameterAnnotations);
paramAnnots = Annotation.getParameterAnnotationsFromReader(r, reference);
if (paramAnnots != null) {
assert paramAnnots.length == result.length;
for (int i = 0; i < result.length; i++) {
result[i].addAll(paramAnnots[i]);
}
}
} catch (InvalidClassFileException e) {
e.printStackTrace();
}
return result;
}
private static final IndirectionData NO_INDIRECTIONS =
new IndirectionData() {
private final int[] NOTHING = new int[0];
@Override
public int[] indirectlyReadLocals(int instructionIndex) {
return NOTHING;
}
@Override
public int[] indirectlyWrittenLocals(int instructionIndex) {
return NOTHING;
}
};
@Override
public IndirectionData getIndirectionData() {
return NO_INDIRECTIONS;
}
}
| 17,371
| 31.471028
| 99
|
java
|
WALA
|
WALA-master/core/src/main/java/com/ibm/wala/classLoader/ShrikeClass.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.classLoader;
import com.ibm.wala.core.util.shrike.ShrikeClassReaderHandle;
import com.ibm.wala.core.util.strings.Atom;
import com.ibm.wala.core.util.strings.ImmutableByteArray;
import com.ibm.wala.ipa.cha.IClassHierarchy;
import com.ibm.wala.shrike.shrikeBT.Constants;
import com.ibm.wala.shrike.shrikeCT.AnnotationsReader;
import com.ibm.wala.shrike.shrikeCT.AnnotationsReader.AnnotationType;
import com.ibm.wala.shrike.shrikeCT.ClassConstants;
import com.ibm.wala.shrike.shrikeCT.ClassReader;
import com.ibm.wala.shrike.shrikeCT.ClassReader.AttrIterator;
import com.ibm.wala.shrike.shrikeCT.InnerClassesReader;
import com.ibm.wala.shrike.shrikeCT.InvalidClassFileException;
import com.ibm.wala.shrike.shrikeCT.SignatureReader;
import com.ibm.wala.shrike.shrikeCT.SourceFileReader;
import com.ibm.wala.shrike.shrikeCT.TypeAnnotationsReader;
import com.ibm.wala.types.ClassLoaderReference;
import com.ibm.wala.types.TypeName;
import com.ibm.wala.types.TypeReference;
import com.ibm.wala.types.annotations.Annotation;
import com.ibm.wala.types.annotations.TypeAnnotation;
import com.ibm.wala.types.generics.ClassSignature;
import com.ibm.wala.types.generics.TypeSignature;
import com.ibm.wala.util.collections.HashSetFactory;
import com.ibm.wala.util.debug.Assertions;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
/** A class read from Shrike */
public final class ShrikeClass extends JVMClass<IClassLoader> {
static final boolean DEBUG = false;
/** The Shrike object that knows how to read the class file */
private final ShrikeClassReaderHandle reader;
/** @throws IllegalArgumentException if reader is null */
public ShrikeClass(ShrikeClassReaderHandle reader, IClassLoader loader, IClassHierarchy cha)
throws InvalidClassFileException {
super(loader, cha);
if (reader == null) {
throw new IllegalArgumentException("reader is null");
}
this.reader = reader;
computeTypeReference();
this.hashCode = 2161 * getReference().hashCode();
// as long as the reader is around, pull more data out
// of it before the soft reference to it disappears
computeSuperName();
computeModifiers();
computeInterfaceNames();
computeFields();
}
/**
* Compute the fields declared by this class
*
* @throws InvalidClassFileException iff Shrike fails to read the class file correctly
*/
private void computeFields() throws InvalidClassFileException {
ClassReader cr = reader.get();
int fieldCount = cr.getFieldCount();
List<FieldImpl> instanceList = new ArrayList<>(fieldCount);
List<FieldImpl> staticList = new ArrayList<>(fieldCount);
try {
for (int i = 0; i < fieldCount; i++) {
int accessFlags = cr.getFieldAccessFlags(i);
Atom name = Atom.findOrCreateUnicodeAtom(cr.getFieldName(i));
ImmutableByteArray b = ImmutableByteArray.make(cr.getFieldType(i));
Collection<Annotation> annotations = HashSetFactory.make();
annotations.addAll(getRuntimeInvisibleAnnotations(i));
annotations.addAll(getRuntimeVisibleAnnotations(i));
annotations = annotations.isEmpty() ? null : annotations;
Collection<TypeAnnotation> typeAnnotations = HashSetFactory.make();
typeAnnotations.addAll(getRuntimeInvisibleTypeAnnotations(i));
typeAnnotations.addAll(getRuntimeVisibleTypeAnnotations(i));
typeAnnotations = typeAnnotations.isEmpty() ? null : typeAnnotations;
TypeSignature sig = null;
SignatureReader signatureReader = getSignatureReader(i);
if (signatureReader != null) {
String signature = signatureReader.getSignature();
if (signature != null) {
sig = TypeSignature.make(signature);
}
}
if ((accessFlags & ClassConstants.ACC_STATIC) == 0) {
addFieldToList(instanceList, name, b, accessFlags, annotations, typeAnnotations, sig);
} else {
addFieldToList(staticList, name, b, accessFlags, annotations, typeAnnotations, sig);
}
}
instanceFields = instanceList.toArray(new IField[0]);
staticFields = staticList.toArray(new IField[0]);
} catch (InvalidClassFileException e) {
e.printStackTrace();
Assertions.UNREACHABLE();
}
}
private void computeModifiers() throws InvalidClassFileException {
modifiers = reader.get().getAccessFlags();
}
/**
* Note that this is called from the constructor, at which point this class is not yet ready to
* actually load the superclass. Instead, we pull out the name of the superclass and cache it
* here, to avoid hitting the reader later.
*/
private void computeSuperName() {
try {
String s = reader.get().getSuperName();
if (s != null) {
superName = ImmutableByteArray.make('L' + s);
}
} catch (InvalidClassFileException e) {
Assertions.UNREACHABLE();
}
}
/**
* Note that this is called from the constructor, at which point this class is not yet ready to
* actually load the interfaces. Instead, we pull out the name of the interfaces and cache it
* here, to avoid hitting the reader later.
*/
private void computeInterfaceNames() {
try {
String[] s = reader.get().getInterfaceNames();
interfaceNames = new ImmutableByteArray[s.length];
Arrays.setAll(interfaceNames, i -> ImmutableByteArray.make('L' + s[i]));
} catch (InvalidClassFileException e) {
Assertions.UNREACHABLE();
}
}
/** initialize the declared methods array */
@Override
protected ShrikeCTMethod[] computeDeclaredMethods() throws InvalidClassFileException {
int methodCount = reader.get().getMethodCount();
ShrikeCTMethod[] result = new ShrikeCTMethod[methodCount];
for (int i = 0; i < methodCount; i++) {
ShrikeCTMethod m = new ShrikeCTMethod(this, i);
if (DEBUG) {
System.err.println(("Register method " + m + " for class " + this));
}
result[i] = m;
}
return result;
}
/**
* initialize the TypeReference field for this instance
*
* @throws InvalidClassFileException iff Shrike can't read this class
*/
private void computeTypeReference() throws InvalidClassFileException {
String className = 'L' + reader.get().getName();
ImmutableByteArray name = ImmutableByteArray.make(className);
typeReference =
TypeReference.findOrCreate(getClassLoader().getReference(), TypeName.findOrCreate(name));
}
/** @see java.lang.Object#equals(Object) */
@Override
public boolean equals(Object obj) {
// it's ok to use instanceof since this class is final
// if (this.getClass().equals(obj.getClass())) {
if (obj instanceof ShrikeClass) {
return getReference().equals(((ShrikeClass) obj).getReference());
} else {
return false;
}
}
public ClassReader getReader() {
try {
return reader.get();
} catch (InvalidClassFileException e) {
e.printStackTrace();
Assertions.UNREACHABLE();
return null;
}
}
/** Clear all optional cached data associated with this class */
public void clearSoftCaches() {
// toss optional information from each method.
if (methodMap != null) {
for (IMethod iMethod : getDeclaredMethods()) {
ShrikeCTMethod m = (ShrikeCTMethod) iMethod;
m.clearCaches();
}
}
// clear the methodMap cache
// SJF: don't do this!!! makes it hard to clear caches on methods.
// methodMap = null;
inheritCache = null;
// clear the cached interfaces
allInterfaces = null;
// toss away the Shrike reader
reader.clear();
}
public Collection<Annotation> getRuntimeInvisibleAnnotations() throws InvalidClassFileException {
return getAnnotations(true);
}
public Collection<Annotation> getRuntimeVisibleAnnotations() throws InvalidClassFileException {
return getAnnotations(false);
}
@Override
public Collection<Annotation> getAnnotations() {
Collection<Annotation> result = HashSetFactory.make();
try {
result.addAll(getAnnotations(true));
result.addAll(getAnnotations(false));
} catch (InvalidClassFileException e) {
}
return result;
}
@Override
public Collection<Annotation> getAnnotations(boolean runtimeInvisible)
throws InvalidClassFileException {
AnnotationsReader r = getAnnotationsReader(runtimeInvisible);
return Annotation.getAnnotationsFromReader(r, getClassLoader().getReference());
}
private AnnotationsReader getAnnotationsReader(boolean runtimeInvisable)
throws InvalidClassFileException {
ClassReader r = reader.get();
ClassReader.AttrIterator attrs = new ClassReader.AttrIterator();
r.initClassAttributeIterator(attrs);
return AnnotationsReader.getReaderForAnnotation(
runtimeInvisable
? AnnotationType.RuntimeInvisibleAnnotations
: AnnotationType.RuntimeVisibleAnnotations,
attrs);
}
public Collection<TypeAnnotation> getTypeAnnotations(boolean runtimeInvisible)
throws InvalidClassFileException {
TypeAnnotationsReader r = getTypeAnnotationsReader(runtimeInvisible);
final ClassLoaderReference clRef = getClassLoader().getReference();
return TypeAnnotation.getTypeAnnotationsFromReader(
r, TypeAnnotation.targetConverterAtClassFile(clRef), clRef);
}
private TypeAnnotationsReader getTypeAnnotationsReader(boolean runtimeInvisible)
throws InvalidClassFileException {
ClassReader r = reader.get();
ClassReader.AttrIterator attrs = new ClassReader.AttrIterator();
r.initClassAttributeIterator(attrs);
return TypeAnnotationsReader.getReaderForAnnotationAtClassfile(
runtimeInvisible
? TypeAnnotationsReader.AnnotationType.RuntimeInvisibleTypeAnnotations
: TypeAnnotationsReader.AnnotationType.RuntimeVisibleTypeAnnotations,
attrs,
getSignatureReader(-1));
}
interface GetReader<T> {
T getReader(ClassReader.AttrIterator iter) throws InvalidClassFileException;
}
static <T> T getReader(ClassReader.AttrIterator iter, String attrName, GetReader<T> reader) {
// search for the attribute
try {
for (; iter.isValid(); iter.advance()) {
if (iter.getName().equals(attrName)) {
return reader.getReader(iter);
}
}
} catch (InvalidClassFileException e) {
Assertions.UNREACHABLE();
}
return null;
}
private InnerClassesReader getInnerClassesReader() throws InvalidClassFileException {
ClassReader r = reader.get();
ClassReader.AttrIterator attrs = new ClassReader.AttrIterator();
r.initClassAttributeIterator(attrs);
// search for the desired attribute
InnerClassesReader result = null;
try {
for (; attrs.isValid(); attrs.advance()) {
if (attrs.getName().equals("InnerClasses")) {
result = new InnerClassesReader(attrs);
break;
}
}
} catch (InvalidClassFileException e) {
Assertions.UNREACHABLE();
}
return result;
}
SourceFileReader getSourceFileReader() {
ClassReader.AttrIterator attrs = new ClassReader.AttrIterator();
getReader().initClassAttributeIterator(attrs);
return getReader(attrs, "SourceFile", SourceFileReader::new);
}
private AnnotationsReader getFieldAnnotationsReader(boolean runtimeInvisible, int fieldIndex)
throws InvalidClassFileException {
ClassReader.AttrIterator iter = new AttrIterator();
reader.get().initFieldAttributeIterator(fieldIndex, iter);
return AnnotationsReader.getReaderForAnnotation(
runtimeInvisible
? AnnotationType.RuntimeInvisibleAnnotations
: AnnotationType.RuntimeVisibleAnnotations,
iter);
}
/** read the runtime-invisible annotations from the class file */
public Collection<Annotation> getRuntimeInvisibleAnnotations(int fieldIndex)
throws InvalidClassFileException {
return getFieldAnnotations(fieldIndex, true);
}
/** read the runtime-invisible annotations from the class file */
public Collection<Annotation> getRuntimeVisibleAnnotations(int fieldIndex)
throws InvalidClassFileException {
return getFieldAnnotations(fieldIndex, false);
}
private Collection<Annotation> getFieldAnnotations(int fieldIndex, boolean runtimeInvisible)
throws InvalidClassFileException {
AnnotationsReader r = getFieldAnnotationsReader(runtimeInvisible, fieldIndex);
return Annotation.getAnnotationsFromReader(r, getClassLoader().getReference());
}
private TypeAnnotationsReader getFieldTypeAnnotationsReader(
boolean runtimeInvisible, int fieldIndex) throws InvalidClassFileException {
ClassReader.AttrIterator iter = new AttrIterator();
reader.get().initFieldAttributeIterator(fieldIndex, iter);
return TypeAnnotationsReader.getReaderForAnnotationAtFieldInfo(
runtimeInvisible
? TypeAnnotationsReader.AnnotationType.RuntimeInvisibleTypeAnnotations
: TypeAnnotationsReader.AnnotationType.RuntimeVisibleTypeAnnotations,
iter);
}
/** read the runtime-invisible type annotations from the class file */
public Collection<TypeAnnotation> getRuntimeInvisibleTypeAnnotations(int fieldIndex)
throws InvalidClassFileException {
return getFieldTypeAnnotations(fieldIndex, true);
}
/** read the runtime-visible type annotations from the class file */
public Collection<TypeAnnotation> getRuntimeVisibleTypeAnnotations(int fieldIndex)
throws InvalidClassFileException {
return getFieldTypeAnnotations(fieldIndex, false);
}
private Collection<TypeAnnotation> getFieldTypeAnnotations(
int fieldIndex, boolean runtimeInvisible) throws InvalidClassFileException {
TypeAnnotationsReader r = getFieldTypeAnnotationsReader(runtimeInvisible, fieldIndex);
final ClassLoaderReference clRef = getClassLoader().getReference();
return TypeAnnotation.getTypeAnnotationsFromReader(
r, TypeAnnotation.targetConverterAtFieldInfo(), clRef);
}
private SignatureReader getSignatureReader(int index) throws InvalidClassFileException {
ClassReader r = reader.get();
ClassReader.AttrIterator attrs = new ClassReader.AttrIterator();
if (index == -1) {
r.initClassAttributeIterator(attrs);
} else {
r.initFieldAttributeIterator(index, attrs);
}
// search for the desired attribute
SignatureReader result = null;
try {
for (; attrs.isValid(); attrs.advance()) {
if (attrs.getName().equals("Signature")) {
result = new SignatureReader(attrs);
break;
}
}
} catch (InvalidClassFileException e) {
Assertions.UNREACHABLE();
}
return result;
}
public ClassSignature getClassSignature() throws InvalidClassFileException {
// TODO: cache this later?
SignatureReader r = getSignatureReader(-1);
if (r == null) {
return null;
} else {
return ClassSignature.make(r.getSignature());
}
}
public ModuleEntry getModuleEntry() {
return reader.getModuleEntry();
}
/** Does the class file indicate that this class is a member of some other class? */
public boolean isInnerClass() throws InvalidClassFileException {
InnerClassesReader r = getInnerClassesReader();
if (r != null) {
for (String s : r.getInnerClasses()) {
if (s.equals(getName().toString().substring(1))) {
String outer = r.getOuterClass(s);
return outer != null;
}
}
}
return false;
}
/** Does the class file indicate that this class is a static inner class? */
public boolean isStaticInnerClass() throws InvalidClassFileException {
InnerClassesReader r = getInnerClassesReader();
if (r != null) {
for (String s : r.getInnerClasses()) {
if (s.equals(getName().toString().substring(1))) {
String outer = r.getOuterClass(s);
if (outer != null) {
int modifiers = r.getAccessFlags(s);
boolean result = ((modifiers & Constants.ACC_STATIC) != 0);
return result;
}
}
}
}
return false;
}
/** If this is an inner class, return the outer class. Else return null. */
public TypeReference getOuterClass() throws InvalidClassFileException {
if (!isInnerClass()) {
return null;
}
InnerClassesReader r = getInnerClassesReader();
for (String s : r.getInnerClasses()) {
if (s.equals(getName().toString().substring(1))) {
String outer = r.getOuterClass(s);
if (outer != null) {
return TypeReference.findOrCreate(getClassLoader().getReference(), 'L' + outer);
}
}
}
return null;
}
@Override
public Module getContainer() {
return reader.getModuleEntry().getContainer();
}
}
| 17,282
| 35.00625
| 99
|
java
|
WALA
|
WALA-master/core/src/main/java/com/ibm/wala/classLoader/ShrikeIRFactory.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.classLoader;
import com.ibm.wala.cfg.ShrikeCFG;
import com.ibm.wala.ipa.callgraph.Context;
import com.ibm.wala.shrike.shrikeBT.IInstruction;
import com.ibm.wala.shrike.shrikeCT.InvalidClassFileException;
import com.ibm.wala.ssa.DefUse;
import com.ibm.wala.ssa.IR;
import com.ibm.wala.ssa.IRFactory;
import com.ibm.wala.ssa.SSAArrayLengthInstruction;
import com.ibm.wala.ssa.SSABuilder;
import com.ibm.wala.ssa.SSACFG;
import com.ibm.wala.ssa.SSAInstruction;
import com.ibm.wala.ssa.SSANewInstruction;
import com.ibm.wala.ssa.SSAOptions;
import com.ibm.wala.ssa.ShrikeIndirectionData;
import com.ibm.wala.ssa.SymbolTable;
import com.ibm.wala.ssa.analysis.DeadAssignmentElimination;
import com.ibm.wala.types.TypeReference;
import com.ibm.wala.util.WalaRuntimeException;
import java.util.Collection;
/** An {@link IRFactory} that for methods that originate from Shrike. */
public class ShrikeIRFactory implements IRFactory<IBytecodeMethod<IInstruction>> {
public static final boolean buildLocalMap = true;
public ShrikeCFG makeCFG(final IBytecodeMethod<IInstruction> method) {
return ShrikeCFG.make(method);
}
@Override
public IR makeIR(final IBytecodeMethod<IInstruction> method, Context C, final SSAOptions options)
throws IllegalArgumentException {
if (method == null) {
throw new IllegalArgumentException("null method");
}
com.ibm.wala.shrike.shrikeBT.IInstruction[] shrikeInstructions = null;
try {
shrikeInstructions = method.getInstructions();
} catch (InvalidClassFileException e) {
throw new WalaRuntimeException("bad method bytecodes", e);
}
final ShrikeCFG shrikeCFG = makeCFG(method);
final SymbolTable symbolTable = new SymbolTable(method.getNumberOfParameters());
final SSAInstruction[] newInstrs = new SSAInstruction[shrikeInstructions.length];
final SSACFG newCfg = new SSACFG(method, shrikeCFG, newInstrs);
return new IR(method, newInstrs, symbolTable, newCfg, options) {
private final SSA2LocalMap localMap;
private final ShrikeIndirectionData indirectionData;
/**
* Remove any phis that are dead assignments.
*
* <p>TODO: move this elsewhere?
*/
private void eliminateDeadPhis() {
DeadAssignmentElimination.perform(this);
}
private void pruneExceptionsForSafeArrayCreations() {
DefUse du = new DefUse(this);
for (int i = 0; i < newInstrs.length; i++) {
SSAInstruction instr = newInstrs[i];
if (instr instanceof SSANewInstruction) {
SSANewInstruction newInstr = (SSANewInstruction) instr;
if (newInstr.getConcreteType().isArrayType()) {
boolean isSafe = true;
final int[] params = new int[newInstr.getNumberOfUses()];
for (int u = 0; u < newInstr.getNumberOfUses(); u++) {
int vLength = newInstr.getUse(u);
params[u] = vLength;
isSafe &= (isNonNegativeConstant(vLength) || isDefdByArrayLength(vLength, du));
}
if (isSafe) {
// newInstr is either obtained from
// JavaLanguage.JavaInstructionFactory#NewInstruction(int iindex, int result,
// NewSiteReference site, int[] params)
// or
// JavaLanguage.JavaInstructionFactory#NewInstruction(int iindex, int result,
// NewSiteReference site)
// , both provide anonymous subclasses of SSANewInstruction which differ
// from SSANewInstruction only in the implementation of getExceptionTypes().
// Hence, it is OK to just defining a new anonymous subclasses of SSANewInstruction,
// overriding getExceptionTypes().
newInstrs[i] =
new SSANewInstruction(
newInstr.iIndex(), newInstr.getDef(), newInstr.getNewSite(), params) {
@Override
public Collection<TypeReference> getExceptionTypes() {
return JavaLanguage.getNewSafeArrayExceptions();
}
};
}
}
}
}
}
private boolean isNonNegativeConstant(int vLength) {
return symbolTable.isIntegerConstant(vLength) && symbolTable.getIntValue(vLength) >= 0;
}
private boolean isDefdByArrayLength(int vLength, DefUse du) {
return du.getDef(vLength) instanceof SSAArrayLengthInstruction;
}
@Override
protected String instructionPosition(int instructionIndex) {
try {
int bcIndex = method.getBytecodeIndex(instructionIndex);
int lineNumber = method.getLineNumber(bcIndex);
if (lineNumber == -1) {
return "";
} else {
return "(line " + lineNumber + ')';
}
} catch (InvalidClassFileException e) {
return "";
}
}
@Override
public SSA2LocalMap getLocalMap() {
return localMap;
}
{
SSABuilder builder =
SSABuilder.make(
method,
newCfg,
shrikeCFG,
newInstrs,
symbolTable,
buildLocalMap,
options.getPiNodePolicy());
builder.build();
if (buildLocalMap) localMap = builder.getLocalMap();
else localMap = null;
indirectionData = builder.getIndirectionData();
eliminateDeadPhis();
pruneExceptionsForSafeArrayCreations();
setupLocationMap();
}
@SuppressWarnings("unchecked")
@Override
protected ShrikeIndirectionData getIndirectionData() {
return indirectionData;
}
};
}
@Override
public boolean contextIsIrrelevant(IBytecodeMethod<IInstruction> method) {
// this factory always returns the same IR for a method
return true;
}
}
| 6,388
| 34.494444
| 100
|
java
|
WALA
|
WALA-master/core/src/main/java/com/ibm/wala/classLoader/SourceDirectoryTreeModule.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.classLoader;
import java.io.File;
/** a module representing a directory tree of source files. */
public class SourceDirectoryTreeModule extends DirectoryTreeModule {
/** file extension of source files in directory tree (defaults to "java" for Java source files) */
String fileExt = "java";
public SourceDirectoryTreeModule(File root) {
super(root);
}
public SourceDirectoryTreeModule(File root, String fileExt) {
super(root);
if (fileExt != null) this.fileExt = fileExt;
}
@Override
protected boolean includeFile(File file) {
return file.getName().endsWith(fileExt);
}
@Override
protected FileModule makeFile(File file) {
String rootPath = root.getAbsolutePath();
if (!rootPath.endsWith(File.separator)) {
rootPath += File.separator;
}
String filePath = file.getAbsolutePath();
assert filePath.startsWith(rootPath);
return new SourceFileModule(file, filePath.substring(rootPath.length()), this);
}
@Override
public String toString() {
return "SourceDirectoryTreeModule:" + getPath();
}
}
| 1,475
| 26.333333
| 100
|
java
|
WALA
|
WALA-master/core/src/main/java/com/ibm/wala/classLoader/SourceFileModule.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.classLoader;
import com.ibm.wala.core.util.io.FileSuffixes;
import java.io.File;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.MalformedURLException;
import java.net.URL;
/** A {@link Module} which is a wrapper around a source file */
public class SourceFileModule extends FileModule implements Module, ModuleEntry, SourceModule {
private final String fileName;
/** cache result of {@link #getURL()}, for performance */
private URL url;
public SourceFileModule(File f, String fileName, Module container) {
super(f, container);
this.fileName = fileName;
}
public SourceFileModule(File f, SourceFileModule clonedFrom) {
super(f, clonedFrom.getContainer());
this.fileName = clonedFrom.fileName;
}
@Override
public String toString() {
return "SourceFileModule:" + getFile().toString();
}
@Override
public boolean isClassFile() {
return false;
}
@Override
public String getClassName() {
return FileSuffixes.stripSuffix(fileName).replace(File.separator.charAt(0), '/');
}
@Override
public boolean isSourceFile() {
return true;
}
@Override
public Reader getInputReader() {
return new InputStreamReader(getInputStream());
}
@Override
public URL getURL() {
if (url == null) {
try {
url = getFile().toURI().toURL();
} catch (MalformedURLException e) {
throw new Error("error making URL for " + getFile(), e);
}
}
return url;
}
}
| 1,885
| 24.486486
| 95
|
java
|
WALA
|
WALA-master/core/src/main/java/com/ibm/wala/classLoader/SourceModule.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.classLoader;
import java.io.Reader;
import java.net.URL;
public interface SourceModule extends Module, ModuleEntry {
Reader getInputReader();
URL getURL();
}
| 555
| 24.272727
| 72
|
java
|
WALA
|
WALA-master/core/src/main/java/com/ibm/wala/classLoader/SourceURLModule.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.classLoader;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.URL;
public class SourceURLModule extends AbstractURLModule implements SourceModule {
public SourceURLModule(URL url) {
super(url);
}
@Override
public boolean isClassFile() {
return false;
}
@Override
public boolean isSourceFile() {
return true;
}
@Override
public Reader getInputReader() {
return new InputStreamReader(getInputStream());
}
}
| 869
| 21.894737
| 80
|
java
|
WALA
|
WALA-master/core/src/main/java/com/ibm/wala/classLoader/SyntheticClass.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.classLoader;
import com.ibm.wala.core.util.strings.Atom;
import com.ibm.wala.ipa.cha.IClassHierarchy;
import com.ibm.wala.types.TypeName;
import com.ibm.wala.types.TypeReference;
import com.ibm.wala.types.annotations.Annotation;
import java.io.Reader;
import java.util.Collection;
import java.util.Collections;
/** An {@link IClass} that exists nowhere in bytecode. */
public abstract class SyntheticClass implements IClass {
private final TypeReference T;
private final IClassHierarchy cha;
/** @param T type reference describing this class */
public SyntheticClass(TypeReference T, IClassHierarchy cha) {
super();
this.T = T;
this.cha = cha;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((T == null) ? 0 : T.hashCode());
result = prime * result + ((cha == null) ? 0 : cha.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (obj == null) return false;
if (!(obj instanceof SyntheticClass)) return false;
final SyntheticClass other = (SyntheticClass) obj;
if (T == null) {
if (other.T != null) return false;
} else if (!T.equals(other.T)) return false;
if (cha == null) {
if (other.cha != null) return false;
} else if (!cha.equals(other.cha)) return false;
return true;
}
/**
* By default, a synthetic class is "loaded" by the primordial loader. Subclasses may override as
* necessary.
*/
@Override
public IClassLoader getClassLoader() {
return cha.getLoader(T.getClassLoader());
}
@Override
public boolean isInterface() {
return false;
}
@Override
public boolean isAbstract() {
return false;
}
/*
* These classes are generated by WALA, not by any
* compiler, therefore it always returns false
* @see com.ibm.wala.classLoader.IClass#isSynthetic()
*/
@Override
public boolean isSynthetic() {
return false;
}
@Override
public TypeReference getReference() {
return T;
}
@Override
public String getSourceFileName() {
return null;
}
@Override
public Reader getSource() {
return null;
}
@Override
public boolean isArrayClass() {
return false;
}
@Override
public IClassHierarchy getClassHierarchy() {
return cha;
}
@Override
public TypeName getName() {
return getReference().getName();
}
/** we assume synthetic classes do not need to have multiple fields with the same name. */
@Override
public IField getField(Atom name, TypeName typeName) {
return getField(name);
}
@Override
public Collection<Annotation> getAnnotations() {
return Collections.emptySet();
}
}
| 3,134
| 23.115385
| 99
|
java
|
WALA
|
WALA-master/core/src/main/java/com/ibm/wala/classLoader/SyntheticMethod.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.classLoader;
import com.ibm.wala.cfg.InducedCFG;
import com.ibm.wala.core.util.bytecode.BytecodeStream;
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.ipa.cha.IClassHierarchy;
import com.ibm.wala.shrike.shrikeCT.InvalidClassFileException;
import com.ibm.wala.ssa.IR;
import com.ibm.wala.ssa.SSAInstruction;
import com.ibm.wala.ssa.SSAOptions;
import com.ibm.wala.types.Descriptor;
import com.ibm.wala.types.MethodReference;
import com.ibm.wala.types.Selector;
import com.ibm.wala.types.TypeReference;
import com.ibm.wala.types.annotations.Annotation;
import com.ibm.wala.util.debug.UnimplementedError;
import java.util.Collection;
import java.util.Collections;
/**
* An implementation of {@link IMethod}, usually for a synthesized method that is not read directly
* from any source {@link Module}.
*/
public class SyntheticMethod implements IMethod {
public static final SSAInstruction[] NO_STATEMENTS = new SSAInstruction[0];
private final MethodReference method;
protected final IMethod resolvedMethod;
public final IClass declaringClass;
private final boolean isStatic;
private final boolean isFactory;
public SyntheticMethod(
MethodReference method, IClass declaringClass, boolean isStatic, boolean isFactory) {
super();
if (method == null) {
throw new IllegalArgumentException("null method");
}
this.method = method;
this.resolvedMethod = null;
this.declaringClass = declaringClass;
this.isStatic = isStatic;
this.isFactory = isFactory;
}
public SyntheticMethod(
IMethod method, IClass declaringClass, boolean isStatic, boolean isFactory) {
super();
if (method == null) {
throw new IllegalArgumentException("null method");
}
this.resolvedMethod = method;
this.method = resolvedMethod.getReference();
this.declaringClass = declaringClass;
this.isStatic = isStatic;
this.isFactory = isFactory;
}
@Override
public boolean isClinit() {
return method.getSelector().equals(MethodReference.clinitSelector);
}
@Override
public boolean isInit() {
return method.getSelector().equals(MethodReference.initSelector);
}
/** @see com.ibm.wala.classLoader.IMethod#isStatic() */
@Override
public boolean isStatic() {
return isStatic;
}
@Override
public boolean isNative() {
return false;
}
@Override
public boolean isAbstract() {
return false;
}
@Override
public boolean isPrivate() {
return false;
}
@Override
public boolean isProtected() {
return false;
}
@Override
public boolean isPublic() {
return false;
}
@Override
public boolean isFinal() {
return false;
}
@Override
public boolean isBridge() {
return false;
}
/** @see com.ibm.wala.classLoader.IMethod#isAbstract() */
@Override
public boolean isSynchronized() {
return false;
}
@Override
public boolean isAnnotation() {
return false;
}
@Override
public boolean isEnum() {
return false;
}
@Override
public boolean isModule() {
return false;
}
@Override
public boolean isWalaSynthetic() {
return true;
}
@Override
public boolean isSynthetic() {
return false;
}
@Override
public MethodReference getReference() {
return method;
}
/**
* Create an {@link InducedCFG} from an instruction array.
*
* <p>NOTE: SIDE EFFECT!!! ... nulls out phi instructions in the instruction array!
*/
public InducedCFG makeControlFlowGraph(SSAInstruction[] instructions) {
return this.getDeclaringClass()
.getClassLoader()
.getLanguage()
.makeInducedCFG(instructions, this, Everywhere.EVERYWHERE);
}
public BytecodeStream getBytecodeStream() throws UnsupportedOperationException {
throw new UnsupportedOperationException();
}
/*
* TODO: why isn't this abstract?
*
* @see com.ibm.wala.classLoader.IMethod#getMaxLocals()
*
* @throws UnsupportedOperationException unconditionally
*/
public int getMaxLocals() throws UnsupportedOperationException {
throw new UnsupportedOperationException();
}
/*
* TODO: why isn't this abstract?
*
* @see com.ibm.wala.classLoader.IMethod#getMaxStackHeight()
*/
public int getMaxStackHeight() throws UnsupportedOperationException {
throw new UnsupportedOperationException();
}
@Override
public IClass getDeclaringClass() {
return declaringClass;
}
@Override
public String toString() {
StringBuilder s = new StringBuilder("synthetic ");
if (isFactoryMethod()) {
s.append(" factory ");
}
s.append(method.toString());
return s.toString();
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((declaringClass == null) ? 0 : declaringClass.hashCode());
result = prime * result + ((method == null) ? 0 : method.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 SyntheticMethod other = (SyntheticMethod) obj;
if (declaringClass == null) {
if (other.declaringClass != null) return false;
} else if (!declaringClass.equals(other.declaringClass)) return false;
if (method == null) {
if (other.method != null) return false;
} else if (!method.equals(other.method)) return false;
return true;
}
@Override
public boolean hasExceptionHandler() {
return false;
}
public boolean hasPoison() {
return false;
}
public String getPoison() {
return null;
}
public byte getPoisonLevel() {
return -1;
}
/*
* TODO: why isn't this abstract?
*
* @param options options governing SSA construction
*/
@Deprecated
public SSAInstruction[] getStatements(@SuppressWarnings("unused") SSAOptions options) {
return NO_STATEMENTS;
}
/**
* Most subclasses should override this.
*
* @param context TODO
* @param options options governing IR conversion
*/
public IR makeIR(Context context, SSAOptions options) throws UnimplementedError {
throw new UnimplementedError(
"haven't implemented IR yet for class " + getClass() + ", method " + method);
}
@Override
public TypeReference getParameterType(int i) {
if (isStatic()) {
return method.getParameterType(i);
} else {
if (i == 0) {
return method.getDeclaringClass();
} else {
return method.getParameterType(i - 1);
}
}
}
@Override
public int getNumberOfParameters() {
int n = method.getNumberOfParameters();
return isStatic() ? n : n + 1;
}
@Override
public TypeReference[] getDeclaredExceptions() throws InvalidClassFileException {
if (resolvedMethod == null) {
return null;
} else {
return resolvedMethod.getDeclaredExceptions();
}
}
@Override
public Atom getName() {
return method.getSelector().getName();
}
@Override
public Descriptor getDescriptor() {
return method.getSelector().getDescriptor();
}
/* BEGIN Custom change: : precise bytecode positions */
@Override
public SourcePosition getSourcePosition(int bcIndex) throws InvalidClassFileException {
return null;
}
@Override
public SourcePosition getParameterSourcePosition(int paramNum) throws InvalidClassFileException {
return null;
}
/* END Custom change: precise bytecode positions */
@Override
public int getLineNumber(int bcIndex) {
return -1;
}
public boolean isFactoryMethod() {
return isFactory;
}
@Override
public String getSignature() {
return getReference().getSignature();
}
@Override
public Selector getSelector() {
return getReference().getSelector();
}
@Override
public String getLocalVariableName(int bcIndex, int localNumber) {
// no information is available
return null;
}
@Override
public boolean hasLocalVariableTable() {
return false;
}
public SSAInstruction[] getStatements() {
return getStatements(SSAOptions.defaultOptions());
}
@Override
public TypeReference getReturnType() {
return getReference().getReturnType();
}
@Override
public IClassHierarchy getClassHierarchy() {
return getDeclaringClass().getClassHierarchy();
}
@Override
public Collection<Annotation> getAnnotations() {
return Collections.emptySet();
}
}
| 8,965
| 22.909333
| 99
|
java
|
WALA
|
WALA-master/core/src/main/java/com/ibm/wala/client/AbstractAnalysisEngine.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.client;
import com.ibm.wala.analysis.pointers.BasicHeapGraph;
import com.ibm.wala.analysis.pointers.HeapGraph;
import com.ibm.wala.classLoader.ClassLoaderFactory;
import com.ibm.wala.classLoader.ClassLoaderFactoryImpl;
import com.ibm.wala.classLoader.JarFileModule;
import com.ibm.wala.classLoader.Module;
import com.ibm.wala.core.util.config.AnalysisScopeReader;
import com.ibm.wala.core.util.io.FileProvider;
import com.ibm.wala.ipa.callgraph.AnalysisCacheImpl;
import com.ibm.wala.ipa.callgraph.AnalysisOptions;
import com.ibm.wala.ipa.callgraph.AnalysisScope;
import com.ibm.wala.ipa.callgraph.CallGraph;
import com.ibm.wala.ipa.callgraph.CallGraphBuilder;
import com.ibm.wala.ipa.callgraph.Entrypoint;
import com.ibm.wala.ipa.callgraph.IAnalysisCacheView;
import com.ibm.wala.ipa.callgraph.impl.Util;
import com.ibm.wala.ipa.callgraph.propagation.InstanceKey;
import com.ibm.wala.ipa.callgraph.propagation.PointerAnalysis;
import com.ibm.wala.ipa.callgraph.propagation.PropagationCallGraphBuilder;
import com.ibm.wala.ipa.cha.ClassHierarchyException;
import com.ibm.wala.ipa.cha.ClassHierarchyFactory;
import com.ibm.wala.ipa.cha.IClassHierarchy;
import com.ibm.wala.ipa.slicer.SDG;
import com.ibm.wala.ipa.slicer.Slicer.ControlDependenceOptions;
import com.ibm.wala.ipa.slicer.Slicer.DataDependenceOptions;
import com.ibm.wala.ssa.DefaultIRFactory;
import com.ibm.wala.types.ClassLoaderReference;
import com.ibm.wala.util.CancelException;
import com.ibm.wala.util.MonitorUtil.IProgressMonitor;
import com.ibm.wala.util.config.SetOfClasses;
import com.ibm.wala.util.debug.Assertions;
import java.io.IOException;
import java.util.Collection;
import java.util.jar.JarFile;
/**
* Abstract base class for analysis engine implementations
*
* <p>Some clients choose to build on this, but many don't. I usually don't in new code; I usually
* don't find the re-use enabled by this class compelling. I would probably nuke this except for
* some legacy code that uses it.
*/
public abstract class AbstractAnalysisEngine<
I extends InstanceKey, X extends CallGraphBuilder<I>, Y>
implements AnalysisEngine {
public interface EntrypointBuilder {
Iterable<Entrypoint> createEntrypoints(IClassHierarchy cha);
}
public static final String SYNTHETIC_J2SE_MODEL = "SyntheticJ2SEModel.txt";
/**
* DEBUG_LEVEL:
*
* <ul>
* <li>0 No output
* <li>1 Print some simple stats and warning information
* <li>2 Detailed debugging
* </ul>
*/
protected static final int DEBUG_LEVEL = 1;
/** Name of the file which holds the class hierarchy exclusions directives for this analysis. */
private String exclusionsFile = "J2SEClassHierarchyExclusions.txt";
/** The modules to analyze */
protected Collection<? extends Module> moduleFiles;
/** A representation of the analysis scope */
protected AnalysisScope scope;
/** A representation of the analysis options */
private AnalysisOptions options;
/** A cache of IRs and stuff */
private IAnalysisCacheView cache = null;
/** The standard J2SE libraries to analyze */
protected Module[] j2seLibs;
/** Whether to perform closed-world analysis of an application */
private boolean closedWorld = false;
/** Governing class hierarchy */
private IClassHierarchy cha;
/** Governing call graph */
protected CallGraph cg;
/** Results of pointer analysis */
protected PointerAnalysis<I> pointerAnalysis;
/** Graph view of flow of pointers between heap abstractions */
private HeapGraph<?> heapGraph;
private EntrypointBuilder entrypointBuilder = this::makeDefaultEntrypoints;
protected abstract X getCallGraphBuilder(
IClassHierarchy cha, AnalysisOptions options, IAnalysisCacheView cache2);
protected X buildCallGraph(
IClassHierarchy cha,
AnalysisOptions options,
boolean savePointerAnalysis,
IProgressMonitor monitor)
throws IllegalArgumentException, CancelException {
X builder = getCallGraphBuilder(cha, options, cache);
cg = builder.makeCallGraph(options, monitor);
if (savePointerAnalysis) {
pointerAnalysis = builder.getPointerAnalysis();
}
return builder;
}
@Override
public void setModuleFiles(Collection<? extends Module> moduleFiles) {
this.moduleFiles = moduleFiles;
}
/** Set up the AnalysisScope object */
public void buildAnalysisScope() throws IOException {
if (j2seLibs == null) {
Assertions.UNREACHABLE(
"no j2selibs specified. You probably did not call AppAnalysisEngine.setJ2SELibrary.");
}
scope =
AnalysisScopeReader.instance.readJavaScope(
SYNTHETIC_J2SE_MODEL,
new FileProvider().getFile(getExclusionsFile()),
getClass().getClassLoader());
// add standard libraries
for (Module j2seLib : j2seLibs) {
scope.addToScope(scope.getPrimordialLoader(), j2seLib);
}
// add user stuff
addApplicationModulesToScope();
}
/** @return a IClassHierarchy object for this analysis scope */
public IClassHierarchy buildClassHierarchy() {
IClassHierarchy cha = null;
ClassLoaderFactory factory = makeClassLoaderFactory(getScope().getExclusions());
try {
cha = ClassHierarchyFactory.make(getScope(), factory);
} catch (ClassHierarchyException e) {
System.err.println("Class Hierarchy construction failed");
System.err.println(e);
e.printStackTrace();
}
return cha;
}
protected ClassLoaderFactory makeClassLoaderFactory(SetOfClasses exclusions) {
return new ClassLoaderFactoryImpl(exclusions);
}
public IClassHierarchy getClassHierarchy() {
return cha;
}
protected IClassHierarchy setClassHierarchy(IClassHierarchy cha) {
return this.cha = cha;
}
/** @return Returns the call graph */
protected CallGraph getCallGraph() {
return cg;
}
/** Add the application modules to the analysis scope. */
protected void addApplicationModulesToScope() {
ClassLoaderReference app = scope.getApplicationLoader();
for (Object o : moduleFiles) {
if (!(o instanceof Module)) {
Assertions.UNREACHABLE("Unexpected type: " + o.getClass());
}
Module M = (Module) o;
scope.addToScope(app, M);
}
}
@Override
public void setJ2SELibraries(JarFile[] libs) {
if (libs == null) {
throw new IllegalArgumentException("libs is null");
}
this.j2seLibs = new Module[libs.length];
for (int i = 0; i < libs.length; i++) {
j2seLibs[i] = new JarFileModule(libs[i]);
}
}
@Override
public void setJ2SELibraries(Module[] libs) {
if (libs == null) {
throw new IllegalArgumentException("libs is null");
}
this.j2seLibs = libs.clone();
}
@Override
public void setClosedWorld(boolean b) {
this.closedWorld = b;
}
public boolean isClosedWorld() {
return closedWorld;
}
protected AnalysisScope getScope() {
return scope;
}
public PointerAnalysis<? super I> getPointerAnalysis() {
return pointerAnalysis;
}
public HeapGraph<?> getHeapGraph() {
if (heapGraph == null) {
heapGraph = new BasicHeapGraph<>(getPointerAnalysis(), cg);
}
return heapGraph;
}
public SDG<? super I> getSDG(DataDependenceOptions data, ControlDependenceOptions ctrl) {
return new SDG<>(getCallGraph(), getPointerAnalysis(), data, ctrl);
}
public String getExclusionsFile() {
return exclusionsFile;
}
public void setExclusionsFile(String exclusionsFile) {
this.exclusionsFile = exclusionsFile;
}
@Override
public AnalysisOptions getDefaultOptions(Iterable<Entrypoint> entrypoints) {
return new AnalysisOptions(getScope(), entrypoints);
}
public IAnalysisCacheView makeDefaultCache() {
return new AnalysisCacheImpl(new DefaultIRFactory());
}
protected Iterable<Entrypoint> makeDefaultEntrypoints(IClassHierarchy cha) {
return Util.makeMainEntrypoints(cha);
}
public void setEntrypointBuilder(EntrypointBuilder builder) {
entrypointBuilder = builder;
}
/**
* Builds the call graph for the analysis scope in effect, using all of the given entry points.
*/
public X defaultCallGraphBuilder() throws IllegalArgumentException, IOException {
buildAnalysisScope();
IClassHierarchy cha = buildClassHierarchy();
setClassHierarchy(cha);
Iterable<Entrypoint> eps = entrypointBuilder.createEntrypoints(cha);
options = getDefaultOptions(eps);
cache = makeDefaultCache();
return getCallGraphBuilder(cha, options, cache);
}
public CallGraph buildDefaultCallGraph()
throws IllegalArgumentException, CancelException, IOException {
return defaultCallGraphBuilder().makeCallGraph(options, null);
}
public IAnalysisCacheView getCache() {
if (cache == null) {
cache = makeDefaultCache();
}
return cache;
}
public AnalysisOptions getOptions() {
return options;
}
@SuppressWarnings("unused")
public Y performAnalysis(PropagationCallGraphBuilder builder) throws CancelException {
return null;
}
}
| 9,454
| 29.798046
| 98
|
java
|
WALA
|
WALA-master/core/src/main/java/com/ibm/wala/client/AbstractEngineStopwatch.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.client;
import com.ibm.wala.util.perf.StopwatchGC;
/** An object to track performance of an analysis engine */
public abstract class AbstractEngineStopwatch implements EngineStopwatch {
/** @return the number of distinct categories timed by this object */
protected abstract int getNumberOfCategories();
/** @return an array of Strings that represent names of the categories tracked */
protected abstract String[] getCategoryNames();
protected final StopwatchGC[] stopwatch;
protected AbstractEngineStopwatch() {
stopwatch = new StopwatchGC[getNumberOfCategories()];
for (int i = 0; i < getNumberOfCategories(); i++) {
stopwatch[i] = new StopwatchGC(getCategoryNames()[i]);
}
}
@Override
public final String report() {
StringBuilder result = new StringBuilder();
long total = 0;
for (int i = 0; i < getNumberOfCategories(); i++) {
total += stopwatch[i].getElapsedMillis();
result
.append(getCategoryNames()[i])
.append(": ")
.append(stopwatch[i].getElapsedMillis())
.append('\n');
}
result.append("Total : ").append(total).append('\n');
return result.toString();
}
/** */
@Override
public void start(byte category) {
stopwatch[category].start();
}
/** */
@Override
public void stop(byte category) {
stopwatch[category].stop();
}
@Override
public StopwatchGC getTimer(byte category) {
return stopwatch[category];
}
}
| 1,876
| 27.439394
| 83
|
java
|
WALA
|
WALA-master/core/src/main/java/com/ibm/wala/client/AnalysisEngine.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.client;
import com.ibm.wala.classLoader.Module;
import com.ibm.wala.ipa.callgraph.AnalysisOptions;
import com.ibm.wala.ipa.callgraph.Entrypoint;
import java.util.Collection;
import java.util.jar.JarFile;
public interface AnalysisEngine {
/**
* Specify the list of modules that should be analyzed. If an EARFile is included in the list, all
* of its contained modules should be examined. Multiple ear files can be specified for cross-app
* invocations, which will become increasingly common in the 5.1 release.
*
* @param moduleFiles A non-null Collection of module files: (EARFile, WARFile,
* ApplicationClientFile, EJBJarFile).
*/
void setModuleFiles(Collection<? extends Module> moduleFiles);
/**
* Specify the jar files that represent the standard J2SE libraries
*
* @param libs an array of jar files; usually rt.jar for vanilla JDK core.jar, server.jar, and
* xml.jar for some WAS runtimes
*/
void setJ2SELibraries(JarFile[] libs);
/**
* Specify the mdoules that represent the standard J2SE libraries
*
* @param libs an array of Modules; usually rt.jar for vanilla JDK core.jar, server.jar, and
* xml.jar for some WAS runtimes
*/
void setJ2SELibraries(Module[] libs);
/**
* Specify whether the engine should or should not employ "closed-world" analysis.
*
* <p>In a closed-world analysis, the engine considers only application client main methods and
* servlet entrypoints to the application.
*
* <p>In an open-world analysis, the engine additionally considers all EJB local and remote
* interface methods as entrypoints.
*
* <p>By default, this property is false; the default analysis is open-world
*
* @param b whether to use closed-world analysis
*/
void setClosedWorld(boolean b);
/** Get the default analysis options appropriate for this engine */
AnalysisOptions getDefaultOptions(Iterable<Entrypoint> entrypoints);
}
| 2,350
| 35.169231
| 100
|
java
|
WALA
|
WALA-master/core/src/main/java/com/ibm/wala/client/EngineStopwatch.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.client;
import com.ibm.wala.util.perf.StopwatchGC;
/** An object to track performance of analysis engine */
public interface EngineStopwatch {
/** @return a String representation of the information in this object */
String report();
/** start timing for some category */
void start(byte category);
/** stop timing for some category */
void stop(byte category);
/** Returns access to class encapsulating time events results, related to the given category. */
StopwatchGC getTimer(byte category);
}
| 915
| 29.533333
| 98
|
java
|
WALA
|
WALA-master/core/src/main/java/com/ibm/wala/core/java11/Java9AnalysisScopeReader.java
|
package com.ibm.wala.core.java11;
import com.ibm.wala.core.util.config.AnalysisScopeReader;
import com.ibm.wala.ipa.callgraph.AnalysisScope;
import com.ibm.wala.types.ClassLoaderReference;
import java.io.IOException;
public class Java9AnalysisScopeReader extends AnalysisScopeReader {
public static final Java9AnalysisScopeReader instance = new Java9AnalysisScopeReader();
static {
setScopeReader(instance);
}
@Override
protected boolean handleInSubclass(
AnalysisScope scope,
ClassLoaderReference walaLoader,
String language,
String entryType,
String entryPathname) {
if ("jrt".equals(entryType)) {
try {
scope.addToScope(walaLoader, new JrtModule(entryPathname));
return true;
} catch (IOException e) {
return false;
}
} else {
return false;
}
}
}
| 861
| 23.628571
| 89
|
java
|
WALA
|
WALA-master/core/src/main/java/com/ibm/wala/core/java11/JrtModule.java
|
package com.ibm.wala.core.java11;
import com.ibm.wala.classLoader.Module;
import com.ibm.wala.classLoader.ModuleEntry;
import com.ibm.wala.core.util.shrike.ShrikeClassReaderHandle;
import com.ibm.wala.core.util.strings.ImmutableByteArray;
import com.ibm.wala.shrike.shrikeCT.InvalidClassFileException;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Iterator;
import java.util.stream.Stream;
public class JrtModule implements Module {
final Path root;
public JrtModule(String module) throws IOException {
root =
java.nio.file.FileSystems.newFileSystem(
java.net.URI.create("jrt:/"), java.util.Collections.emptyMap())
.getPath("modules", module);
}
@Override
public String toString() {
return "[module " + root.toString() + "]";
}
private Stream<? extends ModuleEntry> rec(Path pp) {
Module me = this;
try (var list = Files.list(pp)) {
return list.flatMap(
s -> {
if (Files.isDirectory(s)) {
return rec(s);
} else {
return Stream.of(
new ModuleEntry() {
@Override
public String toString() {
StringBuilder sb = new StringBuilder("[");
if (isClassFile()) {
sb.append("class");
} else if (isSourceFile()) {
sb.append("source");
} else {
sb.append("file");
}
sb.append(" ").append(getName());
return sb.toString();
}
@Override
public String getName() {
return s.toString().substring(root.toString().length() + 1);
}
@Override
public boolean isClassFile() {
return getName().endsWith(".class");
}
@Override
public boolean isSourceFile() {
return getName().endsWith(".java");
}
@Override
public InputStream getInputStream() {
try {
return new ByteArrayInputStream(Files.readAllBytes(s));
} catch (IOException e) {
assert false : e;
return null;
}
}
@Override
public boolean isModuleFile() {
return false;
}
@Override
public Module asModule() {
assert false;
return null;
}
private String className = null;
@Override
public String getClassName() {
assert isClassFile();
if (className == null) {
ShrikeClassReaderHandle reader = new ShrikeClassReaderHandle(this);
try {
ImmutableByteArray name = ImmutableByteArray.make(reader.get().getName());
className = name.toString();
} catch (InvalidClassFileException e) {
e.printStackTrace();
assert false;
}
}
return className;
}
@Override
public Module getContainer() {
return me;
}
});
}
});
} catch (IOException e) {
assert false;
return null;
}
}
@Override
public Iterator<? extends ModuleEntry> getEntries() {
return rec(root).iterator();
}
}
| 4,105
| 31.078125
| 100
|
java
|
WALA
|
WALA-master/core/src/main/java/com/ibm/wala/core/java11/LibraryStuff.java
|
package com.ibm.wala.core.java11;
import com.ibm.wala.classLoader.ClassLoaderFactory;
import com.ibm.wala.classLoader.ClassLoaderFactoryImpl;
import com.ibm.wala.classLoader.Language;
import com.ibm.wala.core.util.config.AnalysisScopeReader;
import com.ibm.wala.ipa.callgraph.AnalysisCacheImpl;
import com.ibm.wala.ipa.callgraph.AnalysisOptions;
import com.ibm.wala.ipa.callgraph.AnalysisOptions.ReflectionOptions;
import com.ibm.wala.ipa.callgraph.AnalysisScope;
import com.ibm.wala.ipa.callgraph.CallGraph;
import com.ibm.wala.ipa.callgraph.Entrypoint;
import com.ibm.wala.ipa.callgraph.IAnalysisCacheView;
import com.ibm.wala.ipa.callgraph.impl.Util;
import com.ibm.wala.ipa.callgraph.propagation.InstanceKey;
import com.ibm.wala.ipa.callgraph.propagation.SSAPropagationCallGraphBuilder;
import com.ibm.wala.ipa.cha.ClassHierarchyFactory;
import com.ibm.wala.ipa.cha.IClassHierarchy;
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.util.NullProgressMonitor;
public class LibraryStuff {
public static void main(String[] args) throws Exception {
try {
AnalysisScopeReader r = new Java9AnalysisScopeReader();
AnalysisScope scope =
r.readJavaScope(
(args.length > 0 ? args[0] : "wala.testdata.txt"),
null,
LibraryStuff.class.getClassLoader());
System.err.println(scope);
ClassLoaderFactory factory = new ClassLoaderFactoryImpl(null);
IClassHierarchy cha = ClassHierarchyFactory.make(scope, factory);
System.err.println(cha);
Iterable<Entrypoint> entrypoints =
com.ibm.wala.ipa.callgraph.impl.Util.makeMainEntrypoints(cha);
AnalysisOptions options = new AnalysisOptions(scope, entrypoints);
options.setReflectionOptions(ReflectionOptions.NONE);
IAnalysisCacheView cache = new AnalysisCacheImpl();
SSAPropagationCallGraphBuilder builder =
Util.makeZeroCFABuilder(Language.JAVA, options, cache, cha);
CallGraph cg = builder.makeCallGraph(options, new NullProgressMonitor());
System.err.println(cg);
SDG<InstanceKey> G =
new SDG<>(
cg,
builder.getPointerAnalysis(),
DataDependenceOptions.FULL,
ControlDependenceOptions.FULL);
System.err.println(G);
} catch (Exception e) {
e.printStackTrace();
throw e;
}
}
}
| 2,505
| 35.318841
| 79
|
java
|
WALA
|
WALA-master/core/src/main/java/com/ibm/wala/core/tests/callGraph/CallGraphTestUtil.java
|
/*
* Copyright (c) 2002 - 2006 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.core.tests.callGraph;
import com.ibm.wala.classLoader.Language;
import com.ibm.wala.core.util.config.AnalysisScopeReader;
import com.ibm.wala.core.util.io.FileProvider;
import com.ibm.wala.ipa.callgraph.AnalysisOptions;
import com.ibm.wala.ipa.callgraph.AnalysisScope;
import com.ibm.wala.ipa.callgraph.CallGraph;
import com.ibm.wala.ipa.callgraph.CallGraphBuilder;
import com.ibm.wala.ipa.callgraph.Entrypoint;
import com.ibm.wala.ipa.callgraph.IAnalysisCacheView;
import com.ibm.wala.ipa.callgraph.impl.Util;
import com.ibm.wala.ipa.callgraph.propagation.InstanceKey;
import com.ibm.wala.ipa.callgraph.propagation.PointerAnalysis;
import com.ibm.wala.ipa.callgraph.propagation.SSAPropagationCallGraphBuilder;
import com.ibm.wala.ipa.cha.IClassHierarchy;
import com.ibm.wala.util.CancelException;
import com.ibm.wala.util.collections.Pair;
import com.ibm.wala.util.perf.StopwatchGC;
import java.io.IOException;
/** Utilities for call graph tests */
public class CallGraphTestUtil {
private static final ClassLoader MY_CLASSLOADER = CallGraphTestUtil.class.getClassLoader();
public static AnalysisOptions makeAnalysisOptions(
AnalysisScope scope, Iterable<Entrypoint> entrypoints) {
AnalysisOptions options = new AnalysisOptions(scope, entrypoints);
return options;
}
public static String REGRESSION_EXCLUSIONS = "Java60RegressionExclusions.txt";
public static String REGRESSION_EXCLUSIONS_FOR_GUI = "Java60RegressionExclusionsForGUI.txt";
/** should we check the heap footprint before and after CG construction? */
private static final boolean CHECK_FOOTPRINT = false;
public static AnalysisScope makeJ2SEAnalysisScope(String scopeFile, String exclusionsFile)
throws IOException {
return makeJ2SEAnalysisScope(scopeFile, exclusionsFile, MY_CLASSLOADER);
}
public static AnalysisScope makeJ2SEAnalysisScope(
String scopeFile, String exclusionsFile, ClassLoader myClassLoader) throws IOException {
AnalysisScope scope =
AnalysisScopeReader.instance.readJavaScope(
scopeFile, new FileProvider().getFile(exclusionsFile), myClassLoader);
return scope;
}
public static CallGraph buildRTA(
AnalysisOptions options, IAnalysisCacheView cache, IClassHierarchy cha)
throws IllegalArgumentException, CancelException {
StopwatchGC S = null;
if (CHECK_FOOTPRINT) {
S = new StopwatchGC("build RTA graph");
S.start();
}
CallGraphBuilder<InstanceKey> builder = Util.makeRTABuilder(options, cache, cha);
CallGraph cg = builder.makeCallGraph(options, null);
if (CHECK_FOOTPRINT) {
S.stop();
System.err.println(S.report());
}
return cg;
}
public static CallGraph buildZeroCFA(
AnalysisOptions options,
IAnalysisCacheView cache,
IClassHierarchy cha,
boolean testPAtoString)
throws IllegalArgumentException, CancelException {
StopwatchGC S = null;
if (CHECK_FOOTPRINT) {
S = new StopwatchGC("build RTA graph");
S.start();
}
SSAPropagationCallGraphBuilder builder =
Util.makeZeroCFABuilder(Language.JAVA, options, cache, cha);
CallGraph cg = builder.makeCallGraph(options, null);
if (testPAtoString) {
String ignored = builder.getPointerAnalysis().toString();
}
if (CHECK_FOOTPRINT) {
S.stop();
System.err.println(S.report());
}
return cg;
}
public static CallGraph buildVanillaZeroOneCFA(
AnalysisOptions options, IAnalysisCacheView cache, IClassHierarchy cha)
throws IllegalArgumentException, CancelException {
StopwatchGC S = null;
if (CHECK_FOOTPRINT) {
S = new StopwatchGC("build RTA graph");
S.start();
}
CallGraphBuilder<InstanceKey> builder =
Util.makeVanillaZeroOneCFABuilder(Language.JAVA, options, cache, cha);
CallGraph cg = builder.makeCallGraph(options, null);
if (CHECK_FOOTPRINT) {
S.stop();
System.err.println(S.report());
}
return cg;
}
public static CallGraph buildZeroOneCFA(
AnalysisOptions options,
IAnalysisCacheView cache,
IClassHierarchy cha,
boolean testPAtoString)
throws IllegalArgumentException, CancelException {
StopwatchGC S = null;
if (CHECK_FOOTPRINT) {
S = new StopwatchGC("build RTA graph");
S.start();
}
CallGraphBuilder<InstanceKey> builder =
Util.makeZeroOneCFABuilder(Language.JAVA, options, cache, cha);
CallGraph cg = builder.makeCallGraph(options, null);
if (testPAtoString) {
String ignored = builder.getPointerAnalysis().toString();
}
if (CHECK_FOOTPRINT) {
S.stop();
System.err.println(S.report());
}
return cg;
}
public static CallGraph buildZeroContainerCFA(
AnalysisOptions options, IAnalysisCacheView cache, IClassHierarchy cha)
throws IllegalArgumentException, CancelException {
StopwatchGC S = null;
if (CHECK_FOOTPRINT) {
S = new StopwatchGC("build RTA graph");
S.start();
}
CallGraphBuilder<InstanceKey> builder = Util.makeZeroContainerCFABuilder(options, cache, cha);
CallGraph cg = builder.makeCallGraph(options, null);
if (CHECK_FOOTPRINT) {
S.stop();
System.err.println(S.report());
}
return cg;
}
public static CallGraph buildZeroOneContainerCFA(
AnalysisOptions options, IAnalysisCacheView cache, IClassHierarchy cha)
throws IllegalArgumentException, CancelException {
StopwatchGC S = null;
if (CHECK_FOOTPRINT) {
S = new StopwatchGC("build RTA graph");
S.start();
}
CallGraphBuilder<InstanceKey> builder =
Util.makeZeroOneContainerCFABuilder(options, cache, cha);
CallGraph cg = builder.makeCallGraph(options, null);
if (CHECK_FOOTPRINT) {
S.stop();
System.err.println(S.report());
}
return cg;
}
public static Pair<CallGraph, PointerAnalysis<InstanceKey>> buildNCFA(
int n, AnalysisOptions options, IAnalysisCacheView cache, IClassHierarchy cha)
throws IllegalArgumentException, CancelException {
StopwatchGC S = null;
if (CHECK_FOOTPRINT) {
S = new StopwatchGC("build N-CFA graph");
S.start();
}
CallGraphBuilder<InstanceKey> builder = Util.makeNCFABuilder(n, options, cache, cha);
CallGraph cg = builder.makeCallGraph(options, null);
if (CHECK_FOOTPRINT) {
S.stop();
System.err.println(S.report());
}
return Pair.make(cg, builder.getPointerAnalysis());
}
}
| 6,905
| 31.575472
| 98
|
java
|
WALA
|
WALA-master/core/src/main/java/com/ibm/wala/core/tests/util/TestConstants.java
|
/*
* Copyright (c) 2006 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.core.tests.util;
public interface TestConstants {
String WALA_TESTDATA = "wala.testdata.txt";
String CLASSCONSTANT_MAIN = "LclassConstant/ClassConstant";
String PI_TEST_MAIN = "Lpi/PiNodeCallGraphTestCase";
String RECURSE_MAIN = "Lrecurse/NList";
String HELLO = "hello.txt";
String HELLO_MAIN = "Lhello/Hello";
String BCEL = "bcel.txt";
String BCEL_VERIFIER_MAIN = "Lorg/apache/bcel/verifier/Verifier";
String JLEX = "JLex.txt";
String JLEX_MAIN = "LJLex/Main";
String JAVA_CUP = "java_cup.txt";
String JAVA_CUP_MAIN = "Ljava_cup/Main";
String MULTI_DIM_MAIN = "LmultiDim/TestMultiDim";
String ARRAY_ALIAS_MAIN = "LarrayAlias/TestArrayAlias";
String ZERO_LENGTH_ARRAY_MAIN = "LarrayAlias/TestZeroLengthArray";
String REFLECT1_MAIN = "Lreflection/Reflect1";
String REFLECT2_MAIN = "Lreflection/Reflect2";
String REFLECT3_MAIN = "Lreflection/Reflect3";
String REFLECT4_MAIN = "Lreflection/Reflect4";
String REFLECT5_MAIN = "Lreflection/Reflect5";
String REFLECT6_MAIN = "Lreflection/Reflect6";
String REFLECT7_MAIN = "Lreflection/Reflect7";
String REFLECT8_MAIN = "Lreflection/Reflect8";
String REFLECT9_MAIN = "Lreflection/Reflect9";
String REFLECT10_MAIN = "Lreflection/Reflect10";
String REFLECT11_MAIN = "Lreflection/Reflect11";
String REFLECT12_MAIN = "Lreflection/Reflect12";
String REFLECT13_MAIN = "Lreflection/Reflect13";
String REFLECT14_MAIN = "Lreflection/Reflect14";
String REFLECT15_MAIN = "Lreflection/Reflect15";
String REFLECT16_MAIN = "Lreflection/Reflect16";
String REFLECT17_MAIN = "Lreflection/Reflect17";
String REFLECT18_MAIN = "Lreflection/Reflect18";
String REFLECT19_MAIN = "Lreflection/Reflect19";
String REFLECT20_MAIN = "Lreflection/Reflect20";
String REFLECT21_MAIN = "Lreflection/Reflect21";
String REFLECT22_MAIN = "Lreflection/Reflect22";
String REFLECT23_MAIN = "Lreflection/Reflect23";
String REFLECT24_MAIN = "Lreflection/Reflect24";
String REFLECTGETMETHODCONTEXT_MAIN = "Lreflection/GetMethodContext";
String SLICE1_MAIN = "Lslice/Slice1";
String SLICE2_MAIN = "Lslice/Slice2";
String SLICE3_MAIN = "Lslice/Slice3";
String SLICE4_MAIN = "Lslice/Slice4";
String SLICE5_MAIN = "Lslice/Slice5";
String SLICE7_MAIN = "Lslice/Slice7";
String SLICE8_MAIN = "Lslice/Slice8";
String SLICE9_MAIN = "Lslice/Slice9";
String SLICE_TESTCD1 = "Lslice/TestCD1";
String SLICE_TESTCD2 = "Lslice/TestCD2";
String SLICE_TESTCD3 = "Lslice/TestCD3";
String SLICE_TESTCD4 = "Lslice/TestCD4";
String SLICE_TESTCD5 = "Lslice/TestCD5";
String SLICE_TESTCD6 = "Lslice/TestCD6";
String SLICE_TESTID = "Lslice/TestId";
String SLICE_TESTARRAYS = "Lslice/TestArrays";
String SLICE_TESTFIELDS = "Lslice/TestFields";
String SLICE_TESTGLOBAL = "Lslice/TestGlobal";
String SLICE_TESTMULTITARGET = "Lslice/TestMultiTarget";
String SLICE_TESTRECURSION = "Lslice/TestRecursion";
String SLICE_TEST_PRIM_GETTER_SETTER = "Lslice/TestPrimGetterSetter";
String SLICE_TEST_PRIM_GETTER_SETTER2 = "Lslice/TestPrimGetterSetter2";
String SLICE_TESTTHIN1 = "Lslice/TestThin1";
String SLICE_TESTTHROWCATCH = "Lslice/TestThrowCatch";
String SLICE_TESTMESSAGEFORMAT = "Lslice/TestMessageFormat";
String SLICE_TESTINETADDR = "Lslice/TestInetAddr";
String SLICE_JUSTTHROW = "Lslice/JustThrow";
String OBJECT_SENSITIVE_TEST1 = "LobjSensitive/TestObjSensitive1";
String OBJECT_SENSITIVE_TEST2 = "LobjSensitive/TestObjSensitive2";
}
| 3,910
| 24.562092
| 73
|
java
|
WALA
|
WALA-master/core/src/main/java/com/ibm/wala/core/util/CancelRuntimeException.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.core.util;
import com.ibm.wala.util.CancelException;
/**
* An exception for when work is canceled in eclipse. This is identical to {@link CancelException},
* but this one extends {@link RuntimeException}, so it need not be threaded through every API that
* uses it.
*/
public class CancelRuntimeException extends RuntimeException {
private static final long serialVersionUID = 5859062345002606705L;
protected CancelRuntimeException(String msg) {
super(msg);
}
public CancelRuntimeException(Exception cause) {
super(cause);
}
public static CancelRuntimeException make(String msg) {
return new CancelRuntimeException(msg);
}
}
| 1,050
| 28.194444
| 99
|
java
|
WALA
|
WALA-master/core/src/main/java/com/ibm/wala/core/util/PrimitiveAssignability.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.core.util;
import com.ibm.wala.types.TypeName;
import com.ibm.wala.types.TypeReference;
import java.util.EnumMap;
import java.util.HashMap;
import java.util.Map;
/**
* Offers checks like ClassHierarchy.isAssignable but for primitives.
*
* <p>This Class does not consider Boxing / Unboxing
*
* @author Tobias Blaschke <code@tobiasblaschke.de>
* @since 2013-11-21
*/
public class PrimitiveAssignability {
public enum AssignabilityKind {
IDENTITY,
WIDENING,
NARROWING,
WIDENING_NARROWING,
UNASSIGNABLE
}
private enum Primitive {
BOOLEAN,
CHAR,
BYTE,
SHORT,
INT,
LONG,
FLOAT,
DOUBLE
}
private static final Map<Primitive, Map<Primitive, AssignabilityKind>> assignability =
new EnumMap<>(Primitive.class);
static {
// fill assignability
for (final Primitive t : Primitive.values()) {
final Map<Primitive, AssignabilityKind> addendum = new EnumMap<>(Primitive.class);
addendum.put(t, AssignabilityKind.IDENTITY);
assignability.put(t, addendum);
}
putWidening(Primitive.BYTE, Primitive.SHORT);
putWidening(Primitive.BYTE, Primitive.INT);
putWidening(Primitive.BYTE, Primitive.LONG);
putWidening(Primitive.BYTE, Primitive.FLOAT);
putWidening(Primitive.BYTE, Primitive.DOUBLE);
putWidening(Primitive.SHORT, Primitive.INT);
putWidening(Primitive.SHORT, Primitive.LONG);
putWidening(Primitive.SHORT, Primitive.FLOAT);
putWidening(Primitive.SHORT, Primitive.DOUBLE);
putWidening(Primitive.CHAR, Primitive.INT);
putWidening(Primitive.CHAR, Primitive.LONG);
putWidening(Primitive.CHAR, Primitive.FLOAT);
putWidening(Primitive.CHAR, Primitive.DOUBLE);
putWidening(Primitive.INT, Primitive.LONG);
putWidening(Primitive.INT, Primitive.FLOAT);
putWidening(Primitive.INT, Primitive.DOUBLE);
putWidening(Primitive.LONG, Primitive.FLOAT);
putWidening(Primitive.LONG, Primitive.DOUBLE);
putWidening(Primitive.FLOAT, Primitive.DOUBLE);
putNarrowing(Primitive.SHORT, Primitive.BYTE);
putNarrowing(Primitive.SHORT, Primitive.CHAR);
putNarrowing(Primitive.CHAR, Primitive.BYTE);
putNarrowing(Primitive.CHAR, Primitive.SHORT);
putNarrowing(Primitive.INT, Primitive.BYTE);
putNarrowing(Primitive.INT, Primitive.SHORT);
putNarrowing(Primitive.INT, Primitive.CHAR);
putNarrowing(Primitive.LONG, Primitive.BYTE);
putNarrowing(Primitive.LONG, Primitive.SHORT);
putNarrowing(Primitive.LONG, Primitive.CHAR);
putNarrowing(Primitive.LONG, Primitive.INT);
putNarrowing(Primitive.FLOAT, Primitive.BYTE);
putNarrowing(Primitive.FLOAT, Primitive.SHORT);
putNarrowing(Primitive.FLOAT, Primitive.CHAR);
putNarrowing(Primitive.FLOAT, Primitive.INT);
putNarrowing(Primitive.FLOAT, Primitive.LONG);
putNarrowing(Primitive.DOUBLE, Primitive.BYTE);
putNarrowing(Primitive.DOUBLE, Primitive.SHORT);
putNarrowing(Primitive.DOUBLE, Primitive.CHAR);
putNarrowing(Primitive.DOUBLE, Primitive.INT);
putNarrowing(Primitive.DOUBLE, Primitive.LONG);
putNarrowing(Primitive.DOUBLE, Primitive.FLOAT);
assignability.get(Primitive.BYTE).put(Primitive.CHAR, AssignabilityKind.WIDENING_NARROWING);
}
private static void putNarrowing(final Primitive from, final Primitive to) {
assert !assignability.get(from).containsKey(to);
assignability.get(from).put(to, AssignabilityKind.NARROWING);
}
private static void putWidening(final Primitive from, final Primitive to) {
assert !assignability.get(from).containsKey(to);
assignability.get(from).put(to, AssignabilityKind.WIDENING);
}
private static final Map<TypeName, Primitive> namePrimitiveMap = new HashMap<>();
static {
// fill namePrimitiveMap
namePrimitiveMap.put(TypeReference.BooleanName, Primitive.BOOLEAN);
namePrimitiveMap.put(TypeReference.ByteName, Primitive.BYTE);
namePrimitiveMap.put(TypeReference.CharName, Primitive.CHAR);
namePrimitiveMap.put(TypeReference.DoubleName, Primitive.DOUBLE);
namePrimitiveMap.put(TypeReference.FloatName, Primitive.FLOAT);
namePrimitiveMap.put(TypeReference.IntName, Primitive.INT);
namePrimitiveMap.put(TypeReference.LongName, Primitive.LONG);
namePrimitiveMap.put(TypeReference.ShortName, Primitive.SHORT);
}
/** Is information lost on c1 x := c2 y? */
public static AssignabilityKind getAssignableFrom(TypeName from, TypeName to) {
final Primitive f = namePrimitiveMap.get(from);
final Primitive t = namePrimitiveMap.get(to);
return assignability.get(f).getOrDefault(t, AssignabilityKind.UNASSIGNABLE);
}
/** Does an expression c1 x := c2 y typecheck? */
public static boolean isAssignableFrom(TypeName from, TypeName to) {
return getAssignableFrom(from, to) != AssignabilityKind.UNASSIGNABLE;
}
}
| 6,792
| 38.04023
| 96
|
java
|
WALA
|
WALA-master/core/src/main/java/com/ibm/wala/core/util/ProgressMaster.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.core.util;
import com.ibm.wala.util.MonitorUtil.IProgressMonitor;
/**
* A class to control execution through the {@link IProgressMonitor} interface.
*
* <p>This class bounds each work item with a time in milliseconds. If there is no apparent progress
* within the specified bound, this class cancels itself.
*/
public class ProgressMaster {
public static IProgressMonitor make(
IProgressMonitor monitor, int msPerWorkItem, boolean checkMemory) {
if (monitor == null) {
throw new IllegalArgumentException("null monitor");
}
return new ProgressMasterImpl(monitor, msPerWorkItem, checkMemory);
}
}
| 1,020
| 31.935484
| 100
|
java
|
WALA
|
WALA-master/core/src/main/java/com/ibm/wala/core/util/ProgressMasterImpl.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.core.util;
import com.ibm.wala.util.MonitorUtil.IProgressMonitor;
import java.lang.management.ManagementFactory;
import java.lang.management.MemoryMXBean;
import java.lang.management.MemoryNotificationInfo;
import java.lang.management.MemoryPoolMXBean;
import java.lang.management.MemoryType;
import javax.management.InstanceNotFoundException;
import javax.management.ListenerNotFoundException;
import javax.management.NotificationListener;
import javax.management.openmbean.CompositeData;
/**
* A class to control execution through the {@link IProgressMonitor} interface.
*
* <p>This class bounds each work item with a time in milliseconds. If there is no apparent progress
* within the specified bound, this class cancels itself.
*/
class ProgressMasterImpl implements IProgressMonitor {
private final IProgressMonitor delegate;
private volatile boolean timedOut = false;
private volatile boolean tooMuchMemory = false;
/** If -1, work items can run forever. */
private final int msPerWorkItem;
private final boolean checkMemory;
private Timeout currentNanny;
ProgressMasterImpl(IProgressMonitor monitor, int msPerWorkItem, boolean checkMemory) {
this.delegate = monitor;
this.msPerWorkItem = msPerWorkItem;
this.checkMemory = checkMemory;
}
@Override
public synchronized void beginTask(String name, int totalWork) {
delegate.beginTask(name, totalWork);
startNanny();
}
private synchronized void startNanny() {
killNanny();
if (msPerWorkItem >= 1 || checkMemory) {
currentNanny = new Timeout();
// don't let nanny thread prevent JVM exit
currentNanny.setDaemon(true);
currentNanny.start();
}
}
public synchronized void reset() {
killNanny();
setCanceled();
timedOut = false;
tooMuchMemory = false;
}
/** Was the last cancel state due to a timeout? */
public boolean lastItemTimedOut() {
return timedOut;
}
public boolean lastItemTooMuchMemory() {
return tooMuchMemory;
}
@Override
public synchronized void done() {
killNanny();
delegate.done();
}
private synchronized void killNanny() {
if (currentNanny != null) {
currentNanny.interrupt();
try {
currentNanny.join();
} catch (InterruptedException e) {
}
currentNanny = null;
}
}
@Override
public boolean isCanceled() {
return delegate.isCanceled() || timedOut || tooMuchMemory;
}
public void setCanceled() {
killNanny();
}
/* BEGIN Custom change: subtasks and canceling */
@Override
public void subTask(String subTask) {
delegate.subTask(subTask);
}
@Override
public void cancel() {
setCanceled();
}
/* END Custom change: subtasks and canceling */
@Override
public synchronized void worked(int work) {
killNanny();
delegate.worked(work);
startNanny();
}
public int getMillisPerWorkItem() {
return msPerWorkItem;
}
public static class TooMuchMemoryUsed extends Exception {
private static final long serialVersionUID = -7174940833610292692L;
}
private class Timeout extends Thread {
@Override
public void run() {
try {
MemoryMXBean gcbean = null;
NotificationListener listener = null;
if (checkMemory) {
for (MemoryPoolMXBean pool : ManagementFactory.getMemoryPoolMXBeans()) {
if (pool.getType().equals(MemoryType.HEAP)) {
pool.setCollectionUsageThreshold(
(long) (pool.getUsage().getMax() * MAX_USED_MEM_BEFORE_BACKING_OUT));
}
}
final Thread nannyThread = this;
gcbean = ManagementFactory.getMemoryMXBean();
listener =
(notification, arg1) -> {
MemoryNotificationInfo info =
MemoryNotificationInfo.from((CompositeData) notification.getUserData());
long used = info.getUsage().getUsed();
long max = Runtime.getRuntime().maxMemory();
if (((double) used / (double) max) > MAX_USED_MEM_BEFORE_BACKING_OUT) {
System.err.println("used " + used + " of " + max);
tooMuchMemory = true;
nannyThread.interrupt();
}
};
try {
ManagementFactory.getPlatformMBeanServer()
.addNotificationListener(gcbean.getObjectName(), listener, null, null);
} catch (InstanceNotFoundException e) {
throw new Error("cannot find existing bean", e);
}
}
Thread.sleep(msPerWorkItem);
if (checkMemory) {
try {
ManagementFactory.getPlatformMBeanServer()
.removeNotificationListener(gcbean.getObjectName(), listener);
} catch (InstanceNotFoundException | ListenerNotFoundException e) {
throw new Error("cannot find existing bean", e);
}
}
if (isInterrupted()) {
return;
}
timedOut = true;
} catch (InterruptedException e) {
return;
}
}
private static final double MAX_USED_MEM_BEFORE_BACKING_OUT = .7;
}
@Override
public String getCancelMessage() {
return tooMuchMemory ? "too much memory" : timedOut ? "timed out" : "unknown";
}
}
| 5,713
| 26.873171
| 100
|
java
|
WALA
|
WALA-master/core/src/main/java/com/ibm/wala/core/util/bytecode/BytecodeStream.java
|
/*
* Copyright (c) 2002 - 2006 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.core.util.bytecode;
import com.ibm.wala.classLoader.IClass;
import com.ibm.wala.classLoader.IMethod;
import com.ibm.wala.shrike.shrikeBT.BytecodeConstants;
/**
* Provides minimal abstraction layer to a stream of bytecodes from the code attribute of a method.
*/
public class BytecodeStream implements BytecodeConstants {
private final IMethod method;
private final IClass declaringClass;
private final int bcLength;
private final byte[] bcodes;
private int bcIndex;
private int opcode;
private boolean wide;
/**
* @param m the method containing the bytecodes
* @param bc the array of bytecodes
* @throws IllegalArgumentException if bc is null
* @throws IllegalArgumentException if m is null
*/
public BytecodeStream(IMethod m, byte[] bc) {
if (m == null) {
throw new IllegalArgumentException("m is null");
}
if (bc == null) {
throw new IllegalArgumentException("bc is null");
}
method = m;
declaringClass = m.getDeclaringClass();
bcodes = bc;
bcLength = bc.length;
bcIndex = 0;
}
/** Returns the method that this bytecode stream is from */
public final IMethod method() {
return method;
}
/** Returns the declaring class that this bytecode stream is from */
public final IClass declaringClass() {
return declaringClass;
}
/**
* Returns the length of the bytecode stream Returns 0 if the method doesn't have any bytecodes
* (i.e. is abstract or native)
*/
public final int length() {
return bcLength;
}
/** Returns the current bytecode index */
public final int index() {
return bcIndex;
}
/** Resets the stream to the beginning */
public final void reset() {
reset(0);
}
/**
* Resets the stream to a given position Use with caution
*
* @param index the position to reset the stream to
*/
public final void reset(int index) {
bcIndex = index;
}
/** Does the stream have more bytecodes in it? */
public final boolean hasMoreBytecodes() {
return bcIndex < bcLength;
}
/**
* Returns the opcode of the next instruction in the sequence without advancing to it
*
* @return the opcode of the next instruction
* @see #nextInstruction()
*/
public final int peekNextOpcode() {
return getUnsignedByte(bcIndex);
}
/**
* Sets up the next instruction in the sequence
*
* @return the opcode of the next instruction
* @see #peekNextOpcode()
*/
public final int nextInstruction() {
opcode = readUnsignedByte();
wide = (opcode == JBC_wide);
return opcode;
}
/**
* Returns the opcode of the current instruction in the sequence Note: if skipInstruction has been
* called, but nextInstruction has not, this method will return the opcode of the skipped
* instruction!
*
* @return the opcode of the current instruction
* @see #nextInstruction()
* @see #isWide()
*/
public final int getOpcode() {
return opcode;
}
/**
* Are we currently processing a wide instruction?
*
* @return true if current instruction is wide
* @see #nextInstruction()
* @see #getOpcode()
*/
public final boolean isWide() {
return wide;
}
/**
* Skips the current instruction
*
* @see #skipInstruction(int,boolean)
*/
public final void skipInstruction() {
int len = JBC_length[opcode] - 1;
if (wide) len += len;
if (len >= 0) {
bcIndex += len;
} else {
skipSpecialInstruction(opcode);
}
}
/**
* Skips the current instruction (without using the opcode field) A slightly optimized version of
* skipInstruction()
*
* @param opc current opcode
* @param w whether current instruction follows wide
* @see #skipInstruction()
*/
public final void skipInstruction(int opc, boolean w) {
int len = JBC_length[opc] - 1;
if (w) len += len;
if (len >= 0) bcIndex += len;
else skipSpecialInstruction(opc);
}
/**
* Returns a signed byte value Used for bipush
*
* @return signed byte value
*/
public final int getByteValue() {
return readSignedByte();
}
/**
* Returns a signed short value Used for sipush
*
* @return signed short value
*/
public final int getShortValue() {
return readSignedShort();
}
/**
* Returns the number of the local (as an unsigned byte) Used for iload, lload, fload, dload,
* aload, istore, lstore, fstore, dstore, astore, iinc, ret
*
* @return local number
* @see #getWideLocalNumber()
*/
public final int getLocalNumber() {
return readUnsignedByte();
}
/**
* Returns the wide number of the local (as an unsigned short) Used for iload, lload, fload,
* dload, aload, istore, lstore, fstore, dstore, astore, iinc prefixed by wide
*
* @return wide local number
* @see #getLocalNumber()
*/
public final int getWideLocalNumber() {
return readUnsignedShort();
}
/**
* Returns an increment value (as a signed byte) Used for iinc
*
* @return increment
* @see #getWideIncrement()
*/
public final int getIncrement() {
return readSignedByte();
}
/**
* Returns an increment value (as a signed short) Used for iinc prefixed by wide
*
* @return wide increment
* @see #getIncrement()
*/
public final int getWideIncrement() {
return readSignedShort();
}
/**
* Returns the offset of the branch (as a signed short) Used for if<cond>,
* ificmp<cond>, ifacmp<cond>, goto, jsr
*
* @return branch offset
* @see #getWideBranchOffset()
*/
public final int getBranchOffset() {
return readSignedShort();
}
/**
* Returns the wide offset of the branch (as a signed int) Used for goto_w, jsr_w
*
* @return wide branch offset
* @see #getBranchOffset()
*/
public final int getWideBranchOffset() {
return readSignedInt();
}
/** Skips the padding of a switch instruction Used for tableswitch, lookupswitch */
public final void alignSwitch() {
int align = bcIndex & 3;
if (align != 0) bcIndex += 4 - align; // eat padding
}
/**
* Returns the default offset of the switch (as a signed int) Used for tableswitch, lookupswitch
*
* @return default switch offset
*/
public final int getDefaultSwitchOffset() {
return readSignedInt();
}
/**
* Returns the lowest value of the tableswitch (as a signed int) Used for tableswitch
*
* @return lowest switch value
* @see #getHighSwitchValue()
*/
public final int getLowSwitchValue() {
return readSignedInt();
}
/**
* Returns the highest value of the tableswitch (as a signed int) Used for tableswitch
*
* @return highest switch value
* @see #getLowSwitchValue()
*/
public final int getHighSwitchValue() {
return readSignedInt();
}
/**
* Skips the offsets of a tableswitch instruction Used for tableswitch
*
* @param num the number of offsets to skip
* @see #getTableSwitchOffset(int)
*/
public final void skipTableSwitchOffsets(int num) {
bcIndex += (num << 2);
}
/**
* Returns the numbered offset of the tableswitch (as a signed int) Used for tableswitch The
* "cursor" has to be positioned at the start of the offset table NOTE: Will NOT advance cursor
*
* @param num the number of the offset to retrieve
* @return switch offset
*/
public final int getTableSwitchOffset(int num) {
return getSignedInt(bcIndex + (num << 2));
}
/**
* Returns the offset for a given value of the tableswitch (as a signed int) or 0 if the value is
* out of range. Used for tableswitch The "cursor" has to be positioned at the start of the offset
* table NOTE: Will NOT advance cursor
*
* @param value the value to retrieve offset for
* @param low the lowest value of the tableswitch
* @param high the highest value of the tableswitch
* @return switch offset
*/
public final int computeTableSwitchOffset(int value, int low, int high) {
if (value < low || value > high) return 0;
return getSignedInt(bcIndex + ((value - low) << 2));
}
/**
* Returns the number of match-offset pairs in the lookupswitch (as a signed int) Used for
* lookupswitch
*
* @return number of switch pairs
*/
public final int getSwitchLength() {
return readSignedInt();
}
/**
* Skips the match-offset pairs of a lookupswitch instruction Used for lookupswitch
*
* @param num the number of match-offset pairs to skip
* @see #getLookupSwitchValue(int)
* @see #getLookupSwitchOffset(int)
*/
public final void skipLookupSwitchPairs(int num) {
bcIndex += (num << 3);
}
/**
* Returns the numbered offset of the lookupswitch (as a signed int) Used for lookupswitch The
* "cursor" has to be positioned at the start of the pair table NOTE: Will NOT advance cursor
*
* @param num the number of the offset to retrieve
* @return switch offset
* @see #getLookupSwitchValue(int)
*/
public final int getLookupSwitchOffset(int num) {
return getSignedInt(bcIndex + (num << 3) + 4);
}
/**
* Returns the numbered value of the lookupswitch (as a signed int) Used for lookupswitch The
* "cursor" has to be positioned at the start of the pair table NOTE: Will NOT advance cursor
*
* @param num the number of the value to retrieve
* @return switch value
* @see #getLookupSwitchOffset(int)
*/
public final int getLookupSwitchValue(int num) {
return getSignedInt(bcIndex + (num << 3));
}
/**
* Returns the offset for a given value of the lookupswitch (as a signed int) or 0 if the value is
* not in the table. Used for lookupswitch The "cursor" has to be positioned at the start of the
* offset table NOTE: Will NOT advance cursor WARNING: Uses LINEAR search. Whoever has time on
* their hands can re-implement this as a binary search.
*
* @param value the value to retrieve offset for
* @param num the number of match-offset pairs in the lookupswitch
* @return switch offset
*/
public final int computeLookupSwitchOffset(int value, int num) {
for (int i = 0; i < num; i++)
if (getSignedInt(bcIndex + (i << 3)) == value) return getSignedInt(bcIndex + (i << 3) + 4);
return 0;
}
/** Skips the extra stuff after an invokeinterface instruction Used for invokeinterface */
public final void alignInvokeInterface() {
bcIndex += 2; // eat superfluous stuff
}
/**
* Returns the element type (primitive) of the array (as an unsigned byte) Used for newarray
*
* @return array element type
*/
public final int getArrayElementType() {
return readUnsignedByte();
}
/**
* Returns the dimension of the array (as an unsigned byte) Used for multianewarray
*
* @return array dimension
*/
public final int getArrayDimension() {
return readUnsignedByte();
}
/**
* Returns the opcode of the wide instruction Used for wide Can be one of iload, lload, fload,
* dload, aload, istore, lstore, fstore, dstore, astore, iinc
*
* @return the opcode of the wide instruction
*/
public final int getWideOpcode() {
opcode = readUnsignedByte();
return opcode;
}
/**
* Returns the constant pool index of a constant (as an unsigned byte) Used for ldc
*
* @return constant index
* @see #getWideConstantIndex()
*/
public final int getConstantIndex() {
return readUnsignedByte();
}
/**
* Returns the wide constant pool index of a constant (as an unsigned short) Used for ldc_w,
* ldc2_w
*
* @return wide constant index
* @see #getConstantIndex()
*/
public final int getWideConstantIndex() {
return readUnsignedShort();
}
// // HELPER FUNCTIONS
// Skip a tableswitch or a lookupswitch instruction
private void skipSpecialInstruction(int opcode) {
switch (opcode) {
case JBC_tableswitch:
{
alignSwitch();
getDefaultSwitchOffset();
int l = getLowSwitchValue();
int h = getHighSwitchValue();
skipTableSwitchOffsets(h - l + 1); // jump offsets
}
break;
case JBC_lookupswitch:
{
alignSwitch();
getDefaultSwitchOffset();
int n = getSwitchLength();
skipLookupSwitchPairs(n); // match-offset pairs
}
break;
case JBC_wide:
{
int oc = getWideOpcode();
int len = JBC_length[oc] - 1;
bcIndex += len + len;
}
break;
default:
throw new NullPointerException();
}
}
// // READ BYTECODES
private final byte readSignedByte() {
return bcodes[bcIndex++];
}
private final int readUnsignedByte() {
return (bcodes[bcIndex++] & 0xFF);
}
private final int getUnsignedByte(int index) {
return (bcodes[index] & 0xFF);
}
private final int readSignedShort() {
int i = bcodes[bcIndex++] << 8;
i |= (bcodes[bcIndex++] & 0xFF);
return i;
}
private final int readUnsignedShort() {
int i = (bcodes[bcIndex++] & 0xFF) << 8;
i |= (bcodes[bcIndex++] & 0xFF);
return i;
}
private final int readSignedInt() {
int i = bcodes[bcIndex++] << 24;
i |= (bcodes[bcIndex++] & 0xFF) << 16;
i |= (bcodes[bcIndex++] & 0xFF) << 8;
i |= (bcodes[bcIndex++] & 0xFF);
return i;
}
private final int getSignedInt(int index) {
int i = bcodes[index++] << 24;
i |= (bcodes[index++] & 0xFF) << 16;
i |= (bcodes[index++] & 0xFF) << 8;
i |= (bcodes[index] & 0xFF);
return i;
}
}
| 13,951
| 25.98646
| 100
|
java
|
WALA
|
WALA-master/core/src/main/java/com/ibm/wala/core/util/config/AnalysisScopeReader.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.core.util.config;
import com.ibm.wala.classLoader.BinaryDirectoryTreeModule;
import com.ibm.wala.classLoader.ClassFileURLModule;
import com.ibm.wala.classLoader.Module;
import com.ibm.wala.classLoader.SourceDirectoryTreeModule;
import com.ibm.wala.core.util.io.FileProvider;
import com.ibm.wala.core.util.strings.Atom;
import com.ibm.wala.ipa.callgraph.AnalysisScope;
import com.ibm.wala.properties.WalaProperties;
import com.ibm.wala.shrike.shrikeCT.InvalidClassFileException;
import com.ibm.wala.types.ClassLoaderReference;
import com.ibm.wala.util.config.FileOfClasses;
import com.ibm.wala.util.debug.Assertions;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URI;
import java.net.URL;
import java.util.StringTokenizer;
import java.util.jar.JarFile;
/** Reads {@link AnalysisScope} from a text file. */
public class AnalysisScopeReader {
public static AnalysisScopeReader instance = new AnalysisScopeReader();
protected static void setScopeReader(AnalysisScopeReader reader) {
instance = reader;
}
protected final ClassLoader MY_CLASSLOADER;
protected final String BASIC_FILE;
protected AnalysisScopeReader() {
this(AnalysisScopeReader.class.getClassLoader(), "primordial.txt");
}
protected AnalysisScopeReader(ClassLoader myLoader, String basicFile) {
this.MY_CLASSLOADER = myLoader;
this.BASIC_FILE = basicFile;
}
/**
* read in an analysis scope for a Java application from a text file
*
* @param scopeFileName the text file specifying the scope
* @param exclusionsFile a file specifying code to be excluded from the scope; can be {@code null}
* @param javaLoader the class loader used to read in files referenced in the scope file, via
* {@link ClassLoader#getResource(String)}
* @return the analysis scope
*/
public AnalysisScope readJavaScope(
String scopeFileName, File exclusionsFile, ClassLoader javaLoader) throws IOException {
AnalysisScope scope = AnalysisScope.createJavaAnalysisScope();
return read(scope, scopeFileName, exclusionsFile, javaLoader);
}
public AnalysisScope read(
AnalysisScope scope, String scopeFileName, File exclusionsFile, ClassLoader javaLoader)
throws IOException {
BufferedReader r = null;
try {
// Now reading from jar is included in WALA, but we can't use their version, because they load
// from
// jar by default and use filesystem as fallback. We want it the other way round. E.g. to
// deliver default
// configuration files with the jar, but use userprovided ones if present in the working
// directory.
// InputStream scopeFileInputStream = fp.getInputStreamFromClassLoader(scopeFileName,
// javaLoader);
File scopeFile = new File(scopeFileName);
String line;
// assume the scope file is UTF-8 encoded; ASCII files will also be handled properly
// TODO allow specifying encoding as a parameter?
if (scopeFile.exists()) {
r = new BufferedReader(new InputStreamReader(new FileInputStream(scopeFile), "UTF-8"));
} else {
// try to read from jar
InputStream inFromJar = javaLoader.getResourceAsStream(scopeFileName);
if (inFromJar == null) {
throw new IllegalArgumentException(
"Unable to retreive " + scopeFileName + " from the jar using " + javaLoader);
}
r = new BufferedReader(new InputStreamReader(inFromJar));
}
while ((line = r.readLine()) != null) {
processScopeDefLine(scope, javaLoader, line);
}
if (exclusionsFile != null) {
try (InputStream fs =
exclusionsFile.exists()
? new FileInputStream(exclusionsFile)
: FileProvider.class
.getClassLoader()
.getResourceAsStream(exclusionsFile.getName())) {
scope.setExclusions(new FileOfClasses(fs));
}
}
} finally {
if (r != null) {
try {
r.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return scope;
}
protected AnalysisScope read(
AnalysisScope scope,
final URI scopeFileURI,
final File exclusionsFile,
ClassLoader javaLoader)
throws IOException {
BufferedReader r = null;
try {
String line;
final InputStream inStream = scopeFileURI.toURL().openStream();
if (inStream == null) {
throw new IllegalArgumentException("Unable to retrieve URI " + scopeFileURI);
}
r = new BufferedReader(new InputStreamReader(inStream, "UTF-8"));
while ((line = r.readLine()) != null) {
processScopeDefLine(scope, javaLoader, line);
}
if (exclusionsFile != null) {
try (final InputStream fs =
exclusionsFile.exists()
? new FileInputStream(exclusionsFile)
: FileProvider.class
.getClassLoader()
.getResourceAsStream(exclusionsFile.getName())) {
scope.setExclusions(new FileOfClasses(fs));
}
}
} finally {
if (r != null) {
try {
r.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return scope;
}
public void processScopeDefLine(AnalysisScope scope, ClassLoader javaLoader, String line)
throws IOException {
if (line == null) {
throw new IllegalArgumentException("null line");
}
StringTokenizer toks = new StringTokenizer(line, "\n,");
if (!toks.hasMoreTokens()) {
return;
}
Atom loaderName = Atom.findOrCreateUnicodeAtom(toks.nextToken());
ClassLoaderReference walaLoader = scope.getLoader(loaderName);
String language = toks.nextToken();
String entryType = toks.nextToken();
String entryPathname = toks.nextToken();
FileProvider fp = new FileProvider();
if ("classFile".equals(entryType)) {
File cf = fp.getFile(entryPathname, javaLoader);
try {
scope.addClassFileToScope(walaLoader, cf);
} catch (InvalidClassFileException e) {
Assertions.UNREACHABLE(e.toString());
}
} else if ("classUrl".equals(entryType)) {
URL cls = fp.getResource(entryPathname);
assert cls != null : "cannot find " + entryPathname;
try {
scope.addToScope(walaLoader, new ClassFileURLModule(cls));
} catch (InvalidClassFileException e) {
Assertions.UNREACHABLE(e.toString());
}
} else if ("sourceFile".equals(entryType)) {
File sf = fp.getFile(entryPathname, javaLoader);
scope.addSourceFileToScope(walaLoader, sf, entryPathname);
} else if ("binaryDir".equals(entryType)) {
File bd = fp.getFile(entryPathname, javaLoader);
assert bd.isDirectory();
scope.addToScope(walaLoader, new BinaryDirectoryTreeModule(bd));
} else if ("sourceDir".equals(entryType)) {
File sd = fp.getFile(entryPathname, javaLoader);
assert sd.isDirectory();
scope.addToScope(walaLoader, new SourceDirectoryTreeModule(sd));
} else if ("jarFile".equals(entryType)) {
Module M = fp.getJarFileModule(entryPathname, javaLoader);
scope.addToScope(walaLoader, M);
} else if ("loaderImpl".equals(entryType)) {
scope.setLoaderImpl(walaLoader, entryPathname);
} else if ("stdlib".equals(entryType)) {
boolean justBase = entryPathname.equals("base");
String[] stdlibs = WalaProperties.getJDKLibraryFiles(justBase);
for (String stdlib : stdlibs) {
scope.addToScope(walaLoader, new JarFile(stdlib, false));
}
} else if ("jdkModule".equals(entryType)) {
scope.addJDKModuleToScope(entryPathname);
} else if (!handleInSubclass(scope, walaLoader, language, entryType, entryPathname)) {
Assertions.UNREACHABLE();
}
}
protected boolean handleInSubclass(
@SuppressWarnings("unused") AnalysisScope scope,
@SuppressWarnings("unused") ClassLoaderReference walaLoader,
@SuppressWarnings("unused") String language,
@SuppressWarnings("unused") String entryType,
@SuppressWarnings("unused") String entryPathname) {
// hook for e.g. Java 11
return false;
}
/**
* Creates an AnalysisScope containing only the JDK standard libraries. If no explicit JDK library
* paths are given in the WALA properties file, the scope contains all library modules for the
* running JVM.
*
* @param exclusionsFile file holding class hierarchy exclusions. may be null
* @throws IllegalStateException if there are problmes reading wala properties
*/
public AnalysisScope makePrimordialScope(File exclusionsFile) throws IOException {
return readJavaScope(BASIC_FILE, exclusionsFile, MY_CLASSLOADER);
}
/**
* Creates an AnalysisScope containing only the JDK standard libraries. If no explicit JDK library
* paths are given in the WALA properties file, the scope contains only the {@code java.base}
* module for the running JVM.
*
* @param exclusionsFile file holding class hierarchy exclusions. may be null
* @throws IllegalStateException if there are problmes reading wala properties
*/
public AnalysisScope makeBasePrimordialScope(File exclusionsFile) throws IOException {
return readJavaScope("primordial-base.txt", exclusionsFile, MY_CLASSLOADER);
}
/**
* @param classPath class path to analyze, delimited by {@link File#pathSeparator}
* @param exclusionsFile file holding class hierarchy exclusions. may be null
* @throws IllegalStateException if there are problems reading wala properties
*/
public AnalysisScope makeJavaBinaryAnalysisScope(String classPath, File exclusionsFile)
throws IOException {
if (classPath == null) {
throw new IllegalArgumentException("classPath null");
}
AnalysisScope scope = makePrimordialScope(exclusionsFile);
ClassLoaderReference loader = scope.getLoader(AnalysisScope.APPLICATION);
addClassPathToScope(classPath, scope, loader);
return scope;
}
public void addClassPathToScope(
String classPath, AnalysisScope scope, ClassLoaderReference loader) {
if (classPath == null) {
throw new IllegalArgumentException("null classPath");
}
try {
StringTokenizer paths = new StringTokenizer(classPath, File.pathSeparator);
while (paths.hasMoreTokens()) {
String path = paths.nextToken();
if (path.endsWith(".jar")) {
JarFile jar = new JarFile(path, false);
scope.addToScope(loader, jar);
try {
if (jar.getManifest() != null) {
String cp = jar.getManifest().getMainAttributes().getValue("Class-Path");
if (cp != null) {
for (String cpEntry : cp.split(" ")) {
addClassPathToScope(
new File(path).getParent() + File.separator + cpEntry, scope, loader);
}
}
}
} catch (RuntimeException e) {
System.err.println("warning: trouble processing class path of " + path);
}
} else {
File f = new File(path);
if (f.isDirectory()) {
scope.addToScope(loader, new BinaryDirectoryTreeModule(f));
} else {
scope.addClassFileToScope(loader, f);
}
}
}
} catch (IOException | InvalidClassFileException e) {
Assertions.UNREACHABLE(e.toString());
}
}
}
| 12,005
| 36.055556
| 100
|
java
|
WALA
|
WALA-master/core/src/main/java/com/ibm/wala/core/util/io/FileProvider.java
|
/*
* Copyright (c) 2002 - 2006 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.core.util.io; // 5724-D15
import com.ibm.wala.classLoader.JarFileModule;
import com.ibm.wala.classLoader.JarStreamModule;
import com.ibm.wala.classLoader.Module;
import com.ibm.wala.classLoader.NestedJarFileModule;
import com.ibm.wala.classLoader.ResourceJarFileModule;
import com.ibm.wala.util.debug.Assertions;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.JarURLConnection;
import java.net.URI;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLDecoder;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import java.util.jar.JarInputStream;
import java.util.zip.ZipException;
/** This class provides files that are packaged with this plug-in */
public class FileProvider {
private static final int DEBUG_LEVEL =
Integer.parseInt(System.getProperty("wala.debug.file", "0"));
/** @return the jar file packaged with this plug-in of the given name, or null if not found. */
public Module getJarFileModule(String fileName) throws IOException {
return getJarFileModule(fileName, FileProvider.class.getClassLoader());
}
public Module getJarFileModule(String fileName, ClassLoader loader) throws IOException {
return getJarFileFromClassLoader(fileName, loader);
}
public URL getResource(String fileName) {
if (fileName == null) {
throw new IllegalArgumentException("null fileName");
}
return getResource(fileName, FileProvider.class.getClassLoader());
}
public URL getResource(String fileName, ClassLoader loader) {
if (fileName == null) {
throw new IllegalArgumentException("null fileName");
}
if (loader == null) {
throw new IllegalArgumentException("null loader");
}
return loader.getResource(fileName);
}
public File getFile(String fileName) throws IOException {
if (fileName == null) {
throw new IllegalArgumentException("null fileName");
}
return getFile(fileName, FileProvider.class.getClassLoader());
}
public File getFile(String fileName, ClassLoader loader) throws IOException {
return getFileFromClassLoader(fileName, loader);
}
public File getFileFromClassLoader(String fileName, ClassLoader loader)
throws FileNotFoundException {
if (loader == null) {
throw new IllegalArgumentException("null loader");
}
if (fileName == null) {
throw new IllegalArgumentException("null fileName");
}
URL url = null;
try {
url = loader.getResource(fileName);
} catch (Exception e) {
}
if (DEBUG_LEVEL > 0) {
System.err.println(("FileProvider got url: " + url + " for " + fileName));
}
if (url == null) {
// couldn't load it from the class loader. try again from the
// system classloader
File f = new File(fileName);
if (f.exists()) {
return f;
}
throw new FileNotFoundException(fileName);
} else {
return new File(filePathFromURL(url));
}
}
/**
* First tries to read fileName from the ClassLoader loader. If unsuccessful, attempts to read
* file from the file system. If that fails, throws a {@link FileNotFoundException}
*/
public InputStream getInputStreamFromClassLoader(String fileName, ClassLoader loader)
throws FileNotFoundException {
if (loader == null) {
throw new IllegalArgumentException("null loader");
}
if (fileName == null) {
throw new IllegalArgumentException("null fileName");
}
InputStream is = loader.getResourceAsStream(fileName);
if (is == null) {
// couldn't load it from the class loader. try again from the
// system classloader
File f = new File(fileName);
if (f.exists()) {
return new FileInputStream(f);
}
throw new FileNotFoundException(fileName);
}
return is;
}
/**
* @return the jar file packaged with this plug-in of the given name, or null if not found:
* wrapped as a JarFileModule or a NestedJarFileModule
*/
public Module getJarFileFromClassLoader(String fileName, ClassLoader loader) throws IOException {
if (fileName == null) {
throw new IllegalArgumentException("null fileName");
}
if (loader == null) {
throw new IllegalArgumentException("null loader");
}
URL url = loader.getResource(fileName);
if (DEBUG_LEVEL > 0) {
System.err.println("FileProvider got url: " + url + " for " + fileName);
}
if (url == null) {
// couldn't load it from the class loader. try again from the
// system classloader
try {
return new JarFileModule(new JarFile(fileName, false));
} catch (ZipException e) {
throw new IOException("Could not find file: " + fileName, e);
}
}
switch (url.getProtocol()) {
case "jar":
JarURLConnection jc = (JarURLConnection) url.openConnection();
JarFile f = jc.getJarFile();
JarEntry entry = jc.getJarEntry();
JarFileModule parent = new JarFileModule(f);
return new NestedJarFileModule(parent, entry);
case "rsrc":
return new ResourceJarFileModule(url);
case "file":
String filePath = filePathFromURL(url);
return new JarFileModule(new JarFile(filePath, false));
default:
final URLConnection in = url.openConnection();
final JarInputStream jarIn = new JarInputStream(in.getInputStream(), false);
return new JarStreamModule(jarIn);
}
}
/**
* Properly creates the String file name of a {@link URL}. This works around a bug in the Sun
* implementation of {@link URL#getFile()}, which doesn't properly handle file paths with spaces
* (see <a href=
* "http://sourceforge.net/tracker/index.php?func=detail&aid=1565842&group_id=176742&atid=878458"
* >bug report</a>). For now, fails with an assertion if the url is malformed.
*
* @return the path name for the url
* @throws IllegalArgumentException if url is null
*/
public String filePathFromURL(URL url) {
if (url == null) {
throw new IllegalArgumentException("url is null");
}
// Old solution does not deal well with "<" | ">" | "#" | "%" |
// <"> "{" | "}" | "|" | "\" | "^" | "[" | "]" | "`" since they may occur
// inside an URL but are prohibited for an URI. See
// http://www.faqs.org/rfcs/rfc2396.html Section 2.4.3
// This solution works. See discussion at
// http://stackoverflow.com/questions/4494063/how-to-avoid-java-net-urisyntaxexception-in-url-touri
// we assume url has been properly encoded, so we decode it
try {
URI uri = new File(URLDecoder.decode(url.getPath(), "UTF-8")).toURI();
return uri.getPath();
} catch (UnsupportedEncodingException e) {
// this really shouldn't happen
Assertions.UNREACHABLE();
return null;
}
}
}
| 7,361
| 34.737864
| 111
|
java
|
WALA
|
WALA-master/core/src/main/java/com/ibm/wala/core/util/io/FileSuffixes.java
|
/*
* Copyright (c) 2002 - 2006 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.core.util.io;
import java.net.URI;
/** Some simple utilities used to manipulate Strings */
public class FileSuffixes {
private static final String CLASS_SUFFIX = ".class";
private static final String JAR_SUFFIX = ".jar";
private static final String WAR_SUFFIX = ".war";
private static final String DEX_SUFFIX = ".dex";
private static final String APK_SUFFIX = ".apk";
/**
* Does the URI refer to a .dex file?
*
* @throws IllegalArgumentException if uri is null
*/
public static boolean isDexFile(final URI uri) {
if (uri == null) {
throw new IllegalArgumentException("uri is null");
}
if (uri.toString().startsWith("jar:")) {
try {
final String filePart = uri.toURL().getFile().toLowerCase();
return isDexFile(filePart);
} catch (java.net.MalformedURLException e) {
throw new IllegalArgumentException(e);
}
} else {
assert (uri.getPath() != null);
return isDexFile(uri.getPath());
}
}
/**
* Does the file name represent a .dex file?
*
* @param fileName name of a file
* @return boolean
* @throws IllegalArgumentException if fileName is null
*/
public static boolean isDexFile(String fileName) {
if (fileName == null) {
throw new IllegalArgumentException("fileName is null");
}
return fileName.toLowerCase().endsWith(DEX_SUFFIX);
}
/**
* Does the file name represent a .dex file?
*
* @param fileName name of a file
* @return boolean
* @throws IllegalArgumentException if fileName is null
*/
public static boolean isApkFile(String fileName) {
if (fileName == null) {
throw new IllegalArgumentException("fileName is null");
}
return fileName.toLowerCase().endsWith(APK_SUFFIX);
}
/**
* Does the file name represent a .class file?
*
* @param fileName name of a file
* @return boolean
* @throws IllegalArgumentException if fileName is null
*/
public static boolean isClassFile(String fileName) {
if (fileName == null) {
throw new IllegalArgumentException("fileName is null");
}
return fileName.endsWith(CLASS_SUFFIX);
}
/**
* Does the file name represent a .java file?
*
* @param fileName name of a file
* @return boolean
* @throws IllegalArgumentException if fileName is null
*/
public static boolean isSourceFile(String fileName) {
if (fileName == null) {
throw new IllegalArgumentException("fileName is null");
}
return fileName.endsWith(".java");
}
/**
* Does the file name represent a .jar file?
*
* @param fileName name of a file
* @return boolean
* @throws IllegalArgumentException if fileName is null
*/
public static boolean isJarFile(String fileName) {
if (fileName == null) {
throw new IllegalArgumentException("fileName is null");
}
return fileName.endsWith(JAR_SUFFIX);
}
/**
* Does the file name represent a .war file?
*
* @param fileName name of a file
* @return boolean
* @throws IllegalArgumentException if fileName is null
*/
public static boolean isWarFile(String fileName) {
if (fileName == null) {
throw new IllegalArgumentException("fileName is null");
}
return fileName.endsWith(WAR_SUFFIX);
}
/**
* Strip the ".class" or ".java" suffix from a file name
*
* <p>TODO: generalize for all suffixes
*
* @param fileName the file name
* @throws IllegalArgumentException if fileName is null
*/
public static String stripSuffix(String fileName) {
if (fileName == null) {
throw new IllegalArgumentException("fileName is null");
}
int suffixIndex = fileName.indexOf(CLASS_SUFFIX);
suffixIndex = (suffixIndex > -1) ? suffixIndex : fileName.indexOf(".java");
if (suffixIndex > -1) {
return fileName.substring(0, suffixIndex);
} else {
return fileName;
}
}
/** Does the URI point to a ressource in a jar-file */
public static boolean isRessourceFromJar(final URI uri) {
return uri.toString().startsWith("jar:"); // How Pretty
}
}
| 4,490
| 27.06875
| 79
|
java
|
WALA
|
WALA-master/core/src/main/java/com/ibm/wala/core/util/ref/CacheReference.java
|
/*
* Copyright (c) 2002 - 2006 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.core.util.ref;
import com.ibm.wala.util.debug.Assertions;
import java.lang.ref.SoftReference;
import java.lang.ref.WeakReference;
/** A factory for References ... useful for debugging. */
public final class CacheReference {
private static final byte SOFT = 0;
private static final byte WEAK = 1;
private static final byte HARD = 2;
// should be SOFT except during debugging.
private static final byte choice = SOFT;
public static Object make(final Object referent) {
switch (choice) {
case SOFT:
return new SoftReference<>(referent);
case WEAK:
return new WeakReference<>(referent);
case HARD:
return referent;
default:
Assertions.UNREACHABLE();
return null;
}
}
public static Object get(final Object reference) throws IllegalArgumentException {
if (reference == null) {
return null;
}
switch (choice) {
case SOFT:
if (!(reference instanceof java.lang.ref.SoftReference)) {
throw new IllegalArgumentException(
"not ( reference instanceof java.lang.ref.SoftReference ) ");
}
return ((SoftReference<?>) reference).get();
case WEAK:
return ((WeakReference<?>) reference).get();
case HARD:
return reference;
default:
Assertions.UNREACHABLE();
return null;
}
}
}
| 1,780
| 25.984848
| 84
|
java
|
WALA
|
WALA-master/core/src/main/java/com/ibm/wala/core/util/ref/ReferenceCleanser.java
|
/*
* Copyright (c) 2002 - 2006 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.core.util.ref;
import com.ibm.wala.classLoader.IClass;
import com.ibm.wala.classLoader.IMethod;
import com.ibm.wala.classLoader.ShrikeCTMethod;
import com.ibm.wala.classLoader.ShrikeClass;
import com.ibm.wala.ipa.callgraph.AnalysisCacheImpl;
import com.ibm.wala.ipa.callgraph.IAnalysisCacheView;
import com.ibm.wala.ipa.cha.IClassHierarchy;
import java.lang.ref.WeakReference;
/**
* For some reason (either a bug in our code that defeats soft references, or a bad policy in the
* GC), leaving soft reference caches to clear themselves out doesn't work. Help it out.
*
* <p>It's unfortunate that this class exists.
*/
public class ReferenceCleanser {
private static final float OCCUPANCY_TRIGGER = 0.5f;
private static WeakReference<IClassHierarchy> cha;
private static WeakReference<AnalysisCacheImpl> cache;
public static void registerClassHierarchy(IClassHierarchy cha) {
ReferenceCleanser.cha = new WeakReference<>(cha);
}
private static IClassHierarchy getClassHierarchy() {
IClassHierarchy result = null;
if (cha != null) {
result = cha.get();
}
return result;
}
public static void registerCache(IAnalysisCacheView cache) {
if (cache instanceof AnalysisCacheImpl) {
ReferenceCleanser.cache = new WeakReference<>((AnalysisCacheImpl) cache);
}
}
private static AnalysisCacheImpl getAnalysisCache() {
AnalysisCacheImpl result = null;
if (cache != null) {
result = cache.get();
}
return result;
}
/** A debugging aid. TODO: move this elsewhere */
public static void clearSoftCaches() {
float occupancy =
1f
- ((float) Runtime.getRuntime().freeMemory()
/ (float) Runtime.getRuntime().totalMemory());
if (occupancy < OCCUPANCY_TRIGGER) {
return;
}
AnalysisCacheImpl cache = getAnalysisCache();
if (cache != null) {
cache.getSSACache().wipe();
}
IClassHierarchy cha = getClassHierarchy();
if (cha != null) {
for (IClass klass : cha) {
if (klass instanceof ShrikeClass) {
ShrikeClass c = (ShrikeClass) klass;
c.clearSoftCaches();
} else {
if (klass.getDeclaredMethods() != null) {
for (IMethod m : klass.getDeclaredMethods()) {
if (m instanceof ShrikeCTMethod) {
((ShrikeCTMethod) m).clearCaches();
}
}
}
}
}
}
}
}
| 2,841
| 29.234043
| 97
|
java
|
WALA
|
WALA-master/core/src/main/java/com/ibm/wala/core/util/scope/JUnitEntryPoints.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.core.util.scope;
import com.ibm.wala.classLoader.IClass;
import com.ibm.wala.classLoader.IClassLoader;
import com.ibm.wala.classLoader.IMethod;
import com.ibm.wala.classLoader.ShrikeCTMethod;
import com.ibm.wala.core.util.strings.Atom;
import com.ibm.wala.core.util.strings.StringStuff;
import com.ibm.wala.ipa.callgraph.Entrypoint;
import com.ibm.wala.ipa.callgraph.impl.DefaultEntrypoint;
import com.ibm.wala.ipa.cha.IClassHierarchy;
import com.ibm.wala.types.ClassLoaderReference;
import com.ibm.wala.types.MethodReference;
import com.ibm.wala.types.TypeName;
import com.ibm.wala.types.annotations.Annotation;
import com.ibm.wala.util.collections.HashSetFactory;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;
import java.util.logging.Logger;
/**
* This class represents entry points ({@link Entrypoint})s of JUnit test methods. JUnit test
* methods are those invoked by the JUnit framework reflectively The entry points can be used to
* specify entry points of a call graph.
*/
public class JUnitEntryPoints {
private static final Logger logger = Logger.getLogger(JUnitEntryPoints.class.getName());
/** Names of annotations that denote JUnit4/5 test methods. */
private static final Set<String> TEST_ENTRY_POINT_ANNOTATION_NAMES =
new HashSet<>(
Arrays.asList(
"org.junit.After",
"org.junit.AfterClass",
"org.junit.Before",
"org.junit.BeforeClass",
"org.junit.ClassRule",
"org.junit.Rule",
"org.junit.Test",
"org.junit.runners.Parameterized.Parameters",
"org.junit.jupiter.api.AfterAll",
"org.junit.jupiter.api.AfterEach",
"org.junit.jupiter.api.BeforeAll",
"org.junit.jupiter.api.BeforeEach",
"org.junit.jupiter.api.RepeatedTest",
"org.junit.jupiter.api.Test"));
/**
* Construct JUnit entrypoints for all the JUnit test methods in the given scope.
*
* @throws IllegalArgumentException if cha is null
*/
public static Iterable<Entrypoint> make(IClassHierarchy cha) {
if (cha == null) {
throw new IllegalArgumentException("cha is null");
}
final HashSet<Entrypoint> result = HashSetFactory.make();
for (IClass klass : cha) {
IClassLoader classLoader = klass.getClassLoader();
ClassLoaderReference reference = classLoader.getReference();
if (reference.equals(ClassLoaderReference.Application)) {
// if the class is a subclass of the Junit TestCase
if (isJUnitTestCase(klass)) {
logger.fine(() -> "application class: " + klass);
// return all the tests methods
Collection<? extends IMethod> methods = klass.getAllMethods();
for (IMethod m : methods) {
if (isJUnitMethod(m)) {
result.add(new DefaultEntrypoint(m, cha));
logger.fine(() -> "- adding test method as entry point: " + m.getName().toString());
}
}
// add entry points of setUp/tearDown methods
Set<IMethod> setUpTearDowns;
try {
setUpTearDowns = getSetUpTearDownMethods(klass);
} catch (Exception e) {
throw new IllegalArgumentException(
"Can't find test method entry points using class hierarchy: " + cha, e);
}
for (IMethod m : setUpTearDowns) {
result.add(new DefaultEntrypoint(m, cha));
}
} else { // JUnit4?
boolean isTestClass = false;
// Since JUnit4 test classes are POJOs, look through each method.
for (com.ibm.wala.classLoader.IMethod method : klass.getDeclaredMethods()) {
// if method has an annotation
if (!(method instanceof ShrikeCTMethod)) continue;
for (Annotation annotation : ((ShrikeCTMethod) method).getAnnotations())
if (isTestEntryPoint(annotation.getType().getName())) {
result.add(new DefaultEntrypoint(method, cha));
isTestClass = true;
}
}
// if the class has a test method, we'll also need to add it's ctor.
if (isTestClass) {
IMethod classInitializer = klass.getClassInitializer();
if (classInitializer != null) result.add(new DefaultEntrypoint(classInitializer, cha));
IMethod ctor = klass.getMethod(MethodReference.initSelector);
if (ctor != null) result.add(new DefaultEntrypoint(ctor, cha));
}
}
}
}
return result::iterator;
}
private static boolean isTestEntryPoint(TypeName typeName) {
// WALA uses $ to refers to inner classes. We have to replace "$" by "."
// to make it a valid class name in Java source code.
String javaName =
StringStuff.jvmToReadableType(typeName.getPackage() + "." + typeName.getClassName());
return TEST_ENTRY_POINT_ANNOTATION_NAMES.contains(javaName);
}
/**
* Construct JUnit entrypoints for the specified test method in a scope.
*
* @throws IllegalArgumentException if cha is null
* @apiNote Only handles JUnit3.
*/
public static Iterable<Entrypoint> makeOne(
IClassHierarchy cha,
String targetPackageName,
String targetSimpleClassName,
String targetMethodName) {
if (cha == null) {
throw new IllegalArgumentException("cha is null");
}
// assume test methods don't have parameters
final Atom targetPackageAtom = Atom.findOrCreateAsciiAtom(targetPackageName);
final Atom targetSimpleClassAtom = Atom.findOrCreateAsciiAtom(targetSimpleClassName);
final TypeName targetType =
TypeName.findOrCreateClass(targetPackageAtom, targetSimpleClassAtom);
final Atom targetMethodAtom = Atom.findOrCreateAsciiAtom(targetMethodName);
logger.finer("finding entrypoint " + targetMethodAtom + " in " + targetType);
final Set<Entrypoint> entryPts = HashSetFactory.make();
for (IClass klass : cha) {
TypeName klassType = klass.getName();
if (klassType.equals(targetType) && isJUnitTestCase(klass)) {
logger.finer("found test class");
// add entry point corresponding to the target method
for (IMethod method : klass.getDeclaredMethods()) {
Atom methodAtom = method.getName();
if (methodAtom.equals(targetMethodAtom)) {
entryPts.add(new DefaultEntrypoint(method, cha));
logger.fine(() -> "- adding entry point of the call graph: " + methodAtom);
}
}
// add entry points of setUp/tearDown methods
Set<IMethod> setUpTearDowns = getSetUpTearDownMethods(klass);
for (IMethod m : setUpTearDowns) {
entryPts.add(new DefaultEntrypoint(m, cha));
}
}
}
return entryPts::iterator;
}
/**
* Check if the given class is a JUnit test class. A JUnit test class is a subclass of
* junit.framework.TestCase or junit.framework.TestSuite.
*
* @throws IllegalArgumentException if klass is null
* @apiNote Applicable only to JUnit3.
*/
public static boolean isJUnitTestCase(IClass klass) {
if (klass == null) {
throw new IllegalArgumentException("klass is null");
}
final Atom junitPackage = Atom.findOrCreateAsciiAtom("junit/framework");
final Atom junitClass = Atom.findOrCreateAsciiAtom("TestCase");
final Atom junitSuite = Atom.findOrCreateAsciiAtom("TestSuite");
final TypeName junitTestCaseType = TypeName.findOrCreateClass(junitPackage, junitClass);
final TypeName junitTestSuiteType = TypeName.findOrCreateClass(junitPackage, junitSuite);
IClass ancestor = klass.getSuperclass();
while (ancestor != null) {
TypeName t = ancestor.getName();
if (t.equals(junitTestCaseType) || t.equals(junitTestSuiteType)) {
return true;
}
ancestor = ancestor.getSuperclass();
}
return false;
}
/**
* Check if the given method is a JUnit test method, assuming that it is declared in a JUnit test
* class. A method is a JUnit test method if the name has the prefix "test", or its name is
* "setUp" or "tearDown".
*
* @throws IllegalArgumentException if m is null
* @apiNote Only handles JUnit3.
*/
public static boolean isJUnitMethod(IMethod m) {
if (m == null) {
throw new IllegalArgumentException("m is null");
}
if (!isJUnitTestCase(m.getDeclaringClass())) {
return false;
}
Atom method = m.getName();
String methodName = method.toString();
return methodName.startsWith("test")
|| methodName.equals("setUp")
|| methodName.equals("tearDown");
}
/**
* Get the "setUp" and "tearDown" methods in the given class
*
* @apiNote Only handles JUnit3.
*/
public static Set<IMethod> getSetUpTearDownMethods(IClass testClass) {
final Atom junitPackage = Atom.findOrCreateAsciiAtom("junit/framework");
final Atom junitClass = Atom.findOrCreateAsciiAtom("TestCase");
final Atom junitSuite = Atom.findOrCreateAsciiAtom("TestSuite");
final TypeName junitTestCaseType = TypeName.findOrCreateClass(junitPackage, junitClass);
final TypeName junitTestSuiteType = TypeName.findOrCreateClass(junitPackage, junitSuite);
final Atom setUpMethodAtom = Atom.findOrCreateAsciiAtom("setUp");
final Atom tearDownMethodAtom = Atom.findOrCreateAsciiAtom("tearDown");
Set<IMethod> result = HashSetFactory.make();
IClass currClass = testClass;
while (currClass != null
&& !currClass.getName().equals(junitTestCaseType)
&& !currClass.getName().equals(junitTestSuiteType)) {
for (IMethod method : currClass.getDeclaredMethods()) {
final Atom methodAtom = method.getName();
if (methodAtom.equals(setUpMethodAtom)
|| methodAtom.equals(tearDownMethodAtom)
|| method.isClinit()
|| method.isInit()) {
result.add(method);
}
}
currClass = currClass.getSuperclass();
}
return result;
}
}
| 10,497
| 37.036232
| 99
|
java
|
WALA
|
WALA-master/core/src/main/java/com/ibm/wala/core/util/shrike/Exceptions.java
|
/*
* Copyright (c) 2002 - 2006 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.core.util.shrike;
import com.ibm.wala.core.util.warnings.Warning;
import com.ibm.wala.types.MemberReference;
/** Utility class to help deal with analysis of exceptions. */
public class Exceptions {
/** A warning for when we fail to resolve the type for a checkcast */
public static class MethodResolutionFailure extends Warning {
final MemberReference method;
MethodResolutionFailure(byte code, MemberReference method) {
super(code);
this.method = method;
}
@Override
public String getMsg() {
return getClass().toString() + " : " + method;
}
public static MethodResolutionFailure moderate(MemberReference method) {
return new MethodResolutionFailure(Warning.MODERATE, method);
}
public static MethodResolutionFailure severe(MemberReference method) {
return new MethodResolutionFailure(Warning.SEVERE, method);
}
}
}
| 1,296
| 29.162791
| 76
|
java
|
WALA
|
WALA-master/core/src/main/java/com/ibm/wala/core/util/shrike/ShrikeClassReaderHandle.java
|
/*
* Copyright (c) 2002 - 2006 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.core.util.shrike;
import com.ibm.wala.classLoader.ModuleEntry;
import com.ibm.wala.core.util.ref.CacheReference;
import com.ibm.wala.shrike.shrikeCT.ClassReader;
import com.ibm.wala.shrike.shrikeCT.InvalidClassFileException;
import com.ibm.wala.util.debug.Assertions;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
/**
* A soft handle to a Shrike class reader
*
* <p>TODO: implement more effective caching than just soft references TODO: push weakness up the
* chain the InputStream, etc ... TODO: reduce reliance on reader throughout the analysis packages
*/
public class ShrikeClassReaderHandle {
private static final boolean DEBUG = false;
/** The module entry that defines the class file */
private final ModuleEntry entry;
private Object reader;
/** The number of times we hydrate the reader */
private int hydrateCount = 0;
public ShrikeClassReaderHandle(ModuleEntry entry) {
if (entry == null) {
throw new IllegalArgumentException("null entry");
}
this.entry = entry;
}
/**
* @return an instance of the class reader ... create one if necessary
* @throws InvalidClassFileException iff Shrike fails to read the class file correctly.
*/
public ClassReader get() throws InvalidClassFileException {
ClassReader result = (ClassReader) CacheReference.get(reader);
if (result == null) {
hydrateCount++;
if (DEBUG) {
if (hydrateCount > 1) {
System.err.println(("Hydrate " + entry + ' ' + hydrateCount));
try {
throw new Exception();
} catch (Exception e) {
e.printStackTrace();
}
}
}
ByteArrayOutputStream S = new ByteArrayOutputStream();
try {
InputStream s = entry.getInputStream();
readBytes(s, S);
s.close();
} catch (IOException e) {
e.printStackTrace();
Assertions.UNREACHABLE();
}
result = new ClassReader(S.toByteArray());
reader = CacheReference.make(result);
}
return result;
}
/** Read is into bytes */
private static void readBytes(InputStream is, ByteArrayOutputStream bytes) throws IOException {
int n = 0;
byte[] buffer = new byte[1024];
while (n > -1) {
n = is.read(buffer, 0, 1024);
if (n > -1) {
bytes.write(buffer, 0, n);
}
}
}
public String getFileName() {
return entry.getName();
}
/** Force the reference to be cleared/collected */
public void clear() {
reader = null;
}
public ModuleEntry getModuleEntry() {
return entry;
}
}
| 3,019
| 28.038462
| 98
|
java
|
WALA
|
WALA-master/core/src/main/java/com/ibm/wala/core/util/shrike/ShrikeUtil.java
|
/*
* Copyright (c) 2002 - 2006 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.core.util.shrike;
import com.ibm.wala.core.util.strings.ImmutableByteArray;
import com.ibm.wala.shrike.shrikeBT.BytecodeConstants;
import com.ibm.wala.shrike.shrikeBT.Constants;
import com.ibm.wala.types.ClassLoaderReference;
import com.ibm.wala.types.TypeName;
import com.ibm.wala.types.TypeReference;
import com.ibm.wala.util.collections.HashMapFactory;
import java.util.HashMap;
/** Utilities to interface with the Shrike CT library. */
public class ShrikeUtil implements BytecodeConstants {
private static final HashMap<String, TypeReference> primitiveMap;
static {
primitiveMap = HashMapFactory.make(10);
primitiveMap.put("I", TypeReference.Int);
primitiveMap.put("J", TypeReference.Long);
primitiveMap.put("S", TypeReference.Short);
primitiveMap.put("B", TypeReference.Byte);
primitiveMap.put("C", TypeReference.Char);
primitiveMap.put("D", TypeReference.Double);
primitiveMap.put("F", TypeReference.Float);
primitiveMap.put("Z", TypeReference.Boolean);
primitiveMap.put("V", TypeReference.Void);
primitiveMap.put(Constants.TYPE_null, TypeReference.Null);
}
/** @param type a type as a String returned by Shrike */
public static TypeReference makeTypeReference(ClassLoaderReference loader, String type)
throws IllegalArgumentException {
if (type == null) {
throw new IllegalArgumentException("null type");
}
TypeReference p = primitiveMap.get(type);
if (p != null) {
return p;
}
ImmutableByteArray b = ImmutableByteArray.make(type);
TypeName T = null;
/*if (b.get(0) != '[') {
T = TypeName.findOrCreate(b, 0, b.length() - 1);
} else {*/
if (b.get(b.length() - 1) == ';') {
T = TypeName.findOrCreate(b, 0, b.length() - 1);
} else {
T = TypeName.findOrCreate(b);
}
// }
return TypeReference.findOrCreate(loader, T);
}
}
| 2,273
| 33.984615
| 89
|
java
|
WALA
|
WALA-master/core/src/main/java/com/ibm/wala/core/util/ssa/ClassLookupException.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.core.util.ssa;
/**
* Class is not in scope.
*
* <p>A ClassLookupException will be thrown when the IClass to a TypeReferece cannot be resolved
* using the ClassHierarchy.
*
* <p>In typical cases this should not be propergated out from the utility classes.
*
* @author Tobias Blaschke <code@tobiasblaschke.de>
*/
public class ClassLookupException extends RuntimeException {
private static final long serialVersionUID = 7551139209041666026L;
public ClassLookupException(String message) {
super(message);
}
}
| 2,499
| 39.322581
| 96
|
java
|
WALA
|
WALA-master/core/src/main/java/com/ibm/wala/core/util/ssa/IInstantiator.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.core.util.ssa;
import com.ibm.wala.types.TypeReference;
/**
* Used for CallBacks to create an Instance.
*
* <p>When methods in this package detect, that they have to generate a new instance of a type this
* CallBack will be used.
*
* <p>This mainly applies to the connectThrough-Function.
*
* @author Tobias Blaschke <code@tobiasblaschke.de>
*/
public interface IInstantiator {
/**
* Create an instance of type.
*
* <p>The varArgs argument gets passed through from functions like connectThrough (which have
* varArgs as well) to the instantiatior.
*
* @param type Type to generate an instance from
* @param instantiatorArgs passed through utility functions
* @return SSA-Number of the instance
*/
int createInstance(TypeReference type, Object... instantiatorArgs);
}
| 2,782
| 38.757143
| 99
|
java
|
WALA
|
WALA-master/core/src/main/java/com/ibm/wala/core/util/ssa/InstructionByIIndexMap.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.core.util.ssa;
import com.ibm.wala.ssa.SSAInstruction;
import java.util.AbstractMap;
import java.util.Collection;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.Map;
import java.util.Set;
public class InstructionByIIndexMap<Instruction extends SSAInstruction, T>
implements Map<Instruction, T> {
private final Map<InstructionByIIndexWrapper<Instruction>, T> map;
public InstructionByIIndexMap(Map<InstructionByIIndexWrapper<Instruction>, T> map) {
this.map = map;
}
public InstructionByIIndexMap() {
this.map = new LinkedHashMap<>();
}
@Override
public int size() {
return map.size();
}
@Override
public boolean isEmpty() {
return map.isEmpty();
}
@Override
public boolean containsKey(Object key) {
if (key instanceof SSAInstruction) {
SSAInstruction instruction = (SSAInstruction) key;
if (instruction.iIndex() >= 0) {
return map.containsKey(new InstructionByIIndexWrapper<>(instruction));
}
}
return false;
}
@Override
public boolean containsValue(Object value) {
return map.containsValue(value);
}
@Override
public T get(Object key) {
if (key instanceof SSAInstruction) {
SSAInstruction instruction = (SSAInstruction) key;
if (instruction.iIndex() >= 0) {
return map.get(new InstructionByIIndexWrapper<>(instruction));
}
}
return null;
}
@Override
public T put(Instruction key, T value) {
return map.put(new InstructionByIIndexWrapper<>(key), value);
}
@Override
public T remove(Object key) {
if (key instanceof SSAInstruction) {
SSAInstruction instruction = (SSAInstruction) key;
if (instruction.iIndex() >= 0) {
return map.remove(new InstructionByIIndexWrapper<>(instruction));
}
}
return null;
}
@Override
public void putAll(Map<? extends Instruction, ? extends T> m) {
for (java.util.Map.Entry<? extends Instruction, ? extends T> entry : m.entrySet()) {
this.put(entry.getKey(), entry.getValue());
}
}
@Override
public void clear() {
map.clear();
}
@Override
public Set<Instruction> keySet() {
Set<Instruction> result = new LinkedHashSet<>();
for (InstructionByIIndexWrapper<Instruction> wrapper : map.keySet()) {
result.add(wrapper.getInstruction());
}
return result;
}
@Override
public Collection<T> values() {
return map.values();
}
@Override
public Set<java.util.Map.Entry<Instruction, T>> entrySet() {
Set<java.util.Map.Entry<Instruction, T>> result = new LinkedHashSet<>();
for (java.util.Map.Entry<InstructionByIIndexWrapper<Instruction>, T> entry : map.entrySet()) {
result.add(
new AbstractMap.SimpleImmutableEntry<>(
entry.getKey().getInstruction(), entry.getValue()));
}
return result;
}
}
| 3,263
| 25.112
| 98
|
java
|
WALA
|
WALA-master/core/src/main/java/com/ibm/wala/core/util/ssa/InstructionByIIndexWrapper.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.core.util.ssa;
import com.ibm.wala.ssa.SSAInstruction;
public class InstructionByIIndexWrapper<T extends SSAInstruction> {
private final T instruction;
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + getInstruction().iIndex();
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (obj == null) return false;
if (getClass() != obj.getClass()) return false;
InstructionByIIndexWrapper<?> other = (InstructionByIIndexWrapper<?>) obj;
if (getInstruction().iIndex() != other.getInstruction().iIndex()) return false;
return true;
}
public T getInstruction() {
return instruction;
}
public InstructionByIIndexWrapper(T instruction) {
if (instruction.iIndex() < 0) {
throw new IllegalArgumentException("The given instruction, can not be identified by iindex.");
}
this.instruction = instruction;
}
}
| 1,364
| 28.042553
| 100
|
java
|
WALA
|
WALA-master/core/src/main/java/com/ibm/wala/core/util/ssa/ParameterAccessor.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.core.util.ssa;
import com.ibm.wala.classLoader.IClass;
import com.ibm.wala.classLoader.IClassLoader;
import com.ibm.wala.classLoader.IMethod;
import com.ibm.wala.core.util.PrimitiveAssignability;
import com.ibm.wala.core.util.ssa.SSAValue.WeaklyNamedKey;
import com.ibm.wala.ipa.cha.IClassHierarchy;
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 java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Objects;
import java.util.Set;
/**
* Access parameters without confusion on their numbers.
*
* <p>Depending on the representation of a method (IMethod, MethodReference) parameters are placed
* at a different position. Functions furthermore may have an implicit this-pointer which alters the
* positions again.
*
* <p>Accessing parameters of these functions by their numbers only is error prone and leads to
* confusion. This class tries to leverage parameter-access.
*
* <p>You can use this class using now numbers at all. However if you choose to use numbers this
* class has yet another numbering convention (jupeee): 1 is the first parameter appearing in the
* Selector, no matter if the Method has an implicit this. It is not zero as Java initializes new
* integer-arrays with zero.
*
* <p>If you want to alter the values of the incoming parameters you may also want to use the
* ParameterManager which tracks the changes.
*
* @author Tobias Blaschke <code@tobiasblaschke.de>
* @since 2013-10-19
*/
public class ParameterAccessor {
private static final boolean DEBUG = false;
/**
* The Constructor used to create ParameterAccessor influences the parameter-offset.
*
* <p>If this enum is extended many functions will throw if not also extended.
*/
public enum BasedOn {
/** ParameterAccessor was constructed using an IMethod */
IMETHOD,
/** ParameterAccessor was constructed using a MethodReference */
METHOD_REFERENCE
}
/**
* The kind of parameter.
*
* <p>Extending this enum should not introduce any problems in ParameterAccessor.
*/
public enum ParamerterDisposition {
/** Parameter is an implicit this-pointer */
THIS,
/** Parameter is a regular parameter occurring in the Descriptor */
PARAM,
/** The return-value of a method (has to be crafted manually) */
RETURN,
NEW
}
/** This key is identified by type and parameter number. */
public static class ParameterKey extends WeaklyNamedKey {
final int paramNo;
public ParameterKey(final TypeName type, final int no, final String name) {
super(type, ((name == null) ? "param_" + no : name));
this.paramNo = no;
}
@Override
public boolean equals(Object o) {
return super.equals(o);
}
@Override
public int hashCode() {
return this.type.hashCode();
}
@Override
public String toString() {
return "<ParameterKey no="
+ this.paramNo
+ " type="
+ this.type
+ " name=\""
+ this.name
+ "\" />";
}
}
/**
* The representation of a Parameter handled using a ParameterAccessor.
*
* <p>It basically consists of a SSA-Value and an associated TypeReference.
*
* <p>Use .getNumber() to access the associated SSA-Value.
*
* @author Tobias Blaschke <code@tobiasblaschke.de>
* @since 2013-10-19
*/
public static class Parameter extends SSAValue {
/** Implicit this or regular parameter? */
private final ParamerterDisposition disp;
/** Add to number to get position in descriptor */
private final int descriptorOffset;
/**
* Create Parameters using ParameterAccessor.
*
* @param number SSA-Value to access this parameter
* @param name Optional variable-name - may be null
* @param type Variable Type to this parameter
* @param disp Implicit this, regular parameter or return value?
* @param basedOn Is Accessor constructed with IMethod or MethodReference
* @param mRef Method this parameter belongs to
* @param descriptorOffset add to number to get position in descriptor
*/
protected Parameter(
final int number,
final String name,
final TypeReference type,
final ParamerterDisposition disp,
final BasedOn basedOn,
final MethodReference mRef,
final int descriptorOffset) {
super(number, type, mRef, new ParameterKey(type.getName(), number + descriptorOffset, name));
if (mRef == null) {
throw new IllegalArgumentException("MethodReference (mRef) of a Parameter may not be null");
}
if (basedOn == null) {
throw new IllegalArgumentException("Argument basedOn of a Parameter may not be null");
}
if (disp == null) {
throw new IllegalArgumentException(
"ParamerterDisposition (disp) of a Parameter may not be null");
}
// If type was null the call to super failed
if ((number < 1) && (basedOn == BasedOn.METHOD_REFERENCE)) {
throw new IllegalArgumentException(
"The first accessible SSA-Value of a MethodReference is 1 but the "
+ "Value-Number given is "
+ number);
}
if ((number < 0) && (basedOn == BasedOn.IMETHOD)) {
throw new IllegalArgumentException(
"The first accessible SSA-Value of an IMethod is 0 but the "
+ "Value-Number given is "
+ number);
}
if ((disp == ParamerterDisposition.PARAM)
&& (number + descriptorOffset > mRef.getNumberOfParameters())) {
throw new IllegalArgumentException(
"The SSA-Value "
+ number
+ " (with added offset "
+ descriptorOffset
+ ") is beyond the number of Arguments ("
+ mRef.getNumberOfParameters()
+ ") of the Method "
+ mRef.getName()
+ '\n'
+ mRef.getSignature());
}
if ((disp == ParamerterDisposition.THIS)
&& (basedOn == BasedOn.METHOD_REFERENCE)
&& (number != 1)) {
throw new IllegalArgumentException(
"The implicit this-pointer of a MethodReference is located at SSA-Value 1. "
+ "The SSA-Value given is "
+ number);
}
if ((disp == ParamerterDisposition.THIS) && (basedOn == BasedOn.IMETHOD) && (number != 0)) {
throw new IllegalArgumentException(
"The implicit this-pointer of an IMethod is located at SSA-Value 0. "
+ "The SSA-Value given is "
+ number);
}
if ((descriptorOffset < -2) || (descriptorOffset > 1)) {
throw new IllegalArgumentException(
"The descriptor-offset given is not within its expected bounds: "
+ "-1 (for a method without implicit this-pointer) to 1. The given offset is "
+ descriptorOffset);
}
this.disp = disp;
this.descriptorOffset = descriptorOffset;
super.isAssigned();
}
/** The position of the parameter in the methods Desciptor starting with 1. */
public int getNumberInDescriptor() { // TODO: Verify all descriptorOffset stuff!
// if (this.descriptorOffset < 0) {
// return this.number;
// } else {
return this.number + this.descriptorOffset;
// }
}
public ParamerterDisposition getDisposition() {
return this.disp;
}
/** @throws IllegalArgumentException if you compare this to an object totally different. */
@Override
public boolean equals(final Object o) {
if (o instanceof Parameter) {
final Parameter other = (Parameter) o;
return (this.type.equals(other.type)
&& (this.number == other.number)
&& this.mRef.equals(other.mRef));
}
if (o instanceof SSAValue) {
return super.equals(o);
}
throw new IllegalArgumentException("Can't compare Parameter to " + o.getClass());
}
/** Clashes deliberately with SSAValue as it's basically the same thing. */
@Override
public final int hashCode() {
return super.hashCode();
}
@Override
public String toString() {
switch (this.disp) {
case THIS:
return "Implicit this-parameter of "
+ this.mRef.getName()
+ " as "
+ this.type
+ " accessible using "
+ "SSA-Value "
+ this.number;
case PARAM:
if (this.key instanceof NamedKey) {
return "Parameter "
+ getNumberInDescriptor()
+ " \""
+ getVariableName()
+ "\" of "
+ this.mRef.getName()
+ " is "
+ this.type
+ " accessible using SSA-Value "
+ this.number;
} else {
return "Parameter "
+ getNumberInDescriptor()
+ " of "
+ this.mRef.getName()
+ " is "
+ this.type
+ " accessible using SSA-Value "
+ this.number;
}
case RETURN:
return "Return Value of "
+ this.mRef.getName()
+ " as "
+ this.type
+ " accessible using SSA-Value "
+ this.number;
case NEW:
return "New instance of "
+ this.type
+ " accessible in "
+ this.mRef.getName()
+ " using number "
+ this.number;
default:
return "Parameter "
+ getNumberInDescriptor()
+ " - "
+ this.disp
+ " of "
+ this.mRef.getName()
+ " as "
+ this.type
+ " accessible using SSA-Value "
+ this.number;
}
}
}
/** The Constructor used to create this ParameterAceesor */
private final BasedOn base;
/** The Method associated to this ParameterAceesor if constructed using a mRef */
private final MethodReference mRef;
/** The Method associated to this ParameterAceesor if constructed using an IMethod */
private final IMethod method;
/** The Value-Number for the implicit this-pointer or -1 if there is none */
private final int implicitThis;
/**
* SSA-Number + descriptorOffset yield the parameters position in the Descriptor starting with 1
*/
private final int descriptorOffset;
/** Number of parameters _excluding_ implicit this */
private final int numberOfParameters;
/**
* Reads the parameters of a MethodReference CAUTION:.
*
* <p>Do _not_ use ParameterAceesor(IMethod.getReference()), but ParameterAceesor(IMehod)!
*
* <p>Using this Constructor influences the SSA-Values returned later. The cha is needed to
* determine whether mRef is static. If this is already known one should prefer the faster {@link
* #ParameterAccessor(MethodReference, boolean)}.
*
* @param mRef The method to read the parameters from.
*/
public ParameterAccessor(final MethodReference mRef, final IClassHierarchy cha) {
if (mRef == null) {
throw new IllegalArgumentException("Can't read the arguments from null.");
}
this.mRef = mRef;
this.method = null;
this.base = BasedOn.METHOD_REFERENCE;
this.numberOfParameters = mRef.getNumberOfParameters();
final boolean hasImplicitThis;
Set<IMethod> targets = cha.getPossibleTargets(mRef);
if (targets.size() < 1) {
warn("Unable to look up the method {} starting extensive search...", mRef);
targets = new HashSet<>();
final TypeReference mClass = mRef.getDeclaringClass();
final Selector mSel = mRef.getSelector();
final Set<IClass> testClasses = new HashSet<>();
// Look up all classes matching exactly
for (IClassLoader loader : cha.getLoaders()) {
final IClass cand = loader.lookupClass(mClass.getName());
if (cand != null) {
testClasses.add(cand);
}
}
// Try lookupClass..
final IClass lookedUp;
lookedUp = cha.lookupClass(mClass);
if (lookedUp != null) {
debug("Found using cha.lookupClass()");
testClasses.add(lookedUp);
}
info("Searching the classes {} for the method", testClasses);
for (IClass testClass : testClasses) {
final IMethod cand = testClass.getMethod(mSel);
if (cand != null) {
targets.add(cand);
}
}
if (targets.size() < 1) {
warn("Still no candidates for the method - continuing with super-classes (TODO)");
// TODO
{ // DEBUG
for (IClass testClass : testClasses) {
info("Known Methods in " + testClass);
for (IMethod contained : testClass.getAllMethods()) {
System.out.println(contained);
info("\t" + contained);
}
}
} // */
throw new IllegalStateException("Unable to look up the method " + mRef);
}
}
{ // Iterate all candidates
final Iterator<IMethod> it = targets.iterator();
final boolean testStatic = it.next().isStatic();
while (it.hasNext()) {
final boolean tmpStatic = it.next().isStatic();
if (testStatic != tmpStatic) {
throw new IllegalStateException(
"The ClassHierarchy knows multiple ("
+ targets.size()
+ ") targets for "
+ mRef
+ ". The targets contradict themselves if they have an implicit this!");
}
}
hasImplicitThis = !testStatic;
}
if (hasImplicitThis) {
info("The method {} has an implicit this pointer", mRef);
this.implicitThis = 1;
this.descriptorOffset = -1;
} else {
info("The method {} has no implicit this pointer", mRef);
this.implicitThis = -1;
this.descriptorOffset = 0;
}
}
/**
* Reads the parameters of a MethodReference CAUTION:.
*
* <p>Do _not_ use ParameterAceesor(IMethod.getReference()), but ParameterAceesor(IMehod)!
*
* <p>This constructor is faster than {@link #ParameterAccessor(MethodReference,
* IClassHierarchy)}.
*
* @param mRef The method to read the parameters from.
*/
public ParameterAccessor(final MethodReference mRef, final boolean hasImplicitThis) {
if (mRef == null) {
throw new IllegalArgumentException("Can't read the arguments from null.");
}
this.mRef = mRef;
this.method = null;
this.base = BasedOn.METHOD_REFERENCE;
this.numberOfParameters = mRef.getNumberOfParameters();
if (hasImplicitThis) {
info("The method {} has an implicit this pointer", mRef);
this.implicitThis = 1;
this.descriptorOffset = -1;
} else {
info("The method {} has no implicit this pointer", mRef);
this.implicitThis = -1;
this.descriptorOffset = 0;
}
}
/**
* Read the parameters from an IMethod.
*
* <p>Using this Constructor influences the SSA-Values returned later.
*
* @param method The method to read the parameters from.
*/
public ParameterAccessor(final IMethod method) {
if (method == null) {
throw new IllegalArgumentException("Can't read the arguments from null.");
}
// Don't make a mRef but keep the IMethod!
this.mRef = null;
this.method = method;
this.base = BasedOn.IMETHOD;
this.numberOfParameters = method.getReference().getNumberOfParameters();
if (method.isStatic() && !method.isInit()) {
assert (method.getNumberOfParameters() == method.getReference().getNumberOfParameters())
: "WTF!" + method;
this.implicitThis = -1;
this.descriptorOffset = 0;
} else {
assert (method.getNumberOfParameters() == 1 + method.getReference().getNumberOfParameters())
: "WTF!" + method;
this.implicitThis = 1;
this.descriptorOffset = -1;
}
}
/**
* Make an Parameter Object using a Descriptor-based numbering (starting with 1).
*
* <p>Number 1 is the first parameter in the methods Selector. No matter if the function has an
* implicit this pointer.
*
* <p>If the Function has an implicit this-pointer you can access it using getThis().
*
* @param no the number in the Selector
* @return new Parameter-Object for no
* @throws IllegalArgumentException if the parameter is zero
* @throws ArrayIndexOutOfBoundsException if no is not within bounds [1 to numberOfParameters]
*/
public Parameter getParameter(final int no) {
// no is checked by getParameterNo(int)
final int newNo = getParameterNo(no);
switch (this.base) {
case IMETHOD: // TODO: Try reading parameter name
return new Parameter(
newNo,
null,
this.method.getParameterType(no),
ParamerterDisposition.PARAM,
this.base,
this.method.getReference(),
this.descriptorOffset);
case METHOD_REFERENCE:
return new Parameter(
newNo,
null,
this.mRef.getParameterType(no - 1),
ParamerterDisposition.PARAM,
this.base,
this.mRef,
this.descriptorOffset);
default:
throw new UnsupportedOperationException(
"No implementation of getParameter() for base " + this.base);
}
}
/**
* Return the SSA-Value to access a parameter using a Descriptor-based numbering (starting with
* 1).
*
* <p>Number 1 is the first parameter in the methods Selector. No matter if the function has an
* implicit this pointer.
*
* <p>If the Function has an implicit this-pointer you can acess it using getThisNo().
*
* @param no the number in the Selector
* @return the offseted number for accessing the parameter
* @throws IllegalArgumentException if the parameter is zero
* @throws ArrayIndexOutOfBoundsException if no is not within bounds [1 to numberOfParameters]
*/
public int getParameterNo(final int no) {
if (no == 0) {
throw new IllegalArgumentException(
"Parameter numbers start with 1. Use getThis() to access a potential implicit this.");
}
if ((no < 0) || (no > this.numberOfParameters)) {
throw new ArrayIndexOutOfBoundsException(
"The given number ("
+ no
+ ") was not within bounds (1 to "
+ this.numberOfParameters
+ ") when acessing a parameter of "
+ this);
}
switch (this.base) {
case IMETHOD:
return no + this.implicitThis; // + this.implicitThis; // TODO: Verify
case METHOD_REFERENCE:
if (this.implicitThis > 0) {
return no + this.implicitThis; //
} else {
return no;
}
default:
throw new UnsupportedOperationException(
"No implementation of getParameter() for base " + this.base);
}
}
/**
* Same as Parameter.getNumber().
*
* @return SSA-Value to access the parameters contents.
*/
public int getParameterNo(final Parameter param) {
if (param == null) {
throw new IllegalArgumentException("Parameter may not be null");
}
return param.getNumber();
}
/**
* This list _excludes_ the implicit this-pointer (if any).
*
* <p>If you want the implicit this-pointer use getThis().
*
* @return All parameters appearing in the Selector.
*/
public List<Parameter> all() {
// TODO: Cache!
List<Parameter> all = new ArrayList<>(this.getNumberOfParameters());
if (this.getNumberOfParameters() == 0) {
return all;
} else {
switch (this.base) {
case IMETHOD:
{
// final int firstInSelector = firstInSelector();
for (int i = (hasImplicitThis() ? 1 : 0);
i < this.method.getNumberOfParameters();
++i) {
debug(
"all() adding: Parameter({}, {}, {}, {}, {})",
(i + 1),
this.method.getParameterType(i),
this.base,
this.method,
this.descriptorOffset);
all.add(
new Parameter(
i + 1,
null,
this.method.getParameterType(i),
ParamerterDisposition.PARAM,
this.base,
this.method.getReference(),
this.descriptorOffset));
}
}
break;
case METHOD_REFERENCE:
{
final int firstInSelector = firstInSelector();
for (int i = 0 /*firstInSelector()*/; i < this.numberOfParameters; ++i) { // TODO:
all.add(
new Parameter(
i + firstInSelector,
null,
this.mRef.getParameterType(i),
ParamerterDisposition.PARAM,
this.base,
this.mRef,
this.descriptorOffset));
}
}
break;
default:
throw new UnsupportedOperationException(
"No implementation of all() for base " + this.base);
}
}
return all;
}
/**
* Return the implicit this-pointer (or throw).
*
* <p>This obviously only works on non-static methods. You probably want to check if the method
* has such an implicit this using hasImplicitThis() as this method will throw if there is none.
*
* <p>If you only want the number use the more lightweight getThisNo().
*
* @return Object containing all Information on the parameter.
* @throws IllegalStateException if the function has no implicit this
*/
public Parameter getThis() {
final int self = getThisNo();
final TypeReference selfType;
switch (this.base) {
case IMETHOD:
selfType = this.method.getParameterType(self);
break;
case METHOD_REFERENCE:
selfType = this.mRef.getDeclaringClass();
break;
default:
throw new UnsupportedOperationException(
"No implementation of getThis() for base " + this.base);
}
return getThisAs(selfType);
}
/**
* Return the implicit this-pointer as a supertype.
*
* @param asType A type of a super-class of this
*/
public Parameter getThisAs(final TypeReference asType) {
final int self = getThisNo();
switch (this.base) {
case IMETHOD:
final IClassHierarchy cha = this.method.getClassHierarchy();
try {
if (!isSubclassOf(this.method.getParameterType(self), asType, cha)) {
throw new IllegalArgumentException(
"Class "
+ asType
+ " is not a super-class of "
+ this.method.getParameterType(self));
}
} catch (ClassLookupException e) {
// Cant't test assume all fitts
}
return new Parameter(
self,
"self",
asType,
ParamerterDisposition.THIS,
this.base,
this.method.getReference(),
this.descriptorOffset);
case METHOD_REFERENCE:
// TODO assert asType is a subtype of self.type - we need cha to do that :(
return new Parameter(
self,
"self",
asType,
ParamerterDisposition.THIS,
this.base,
this.mRef,
this.descriptorOffset);
default:
throw new UnsupportedOperationException(
"No implementation of getThis() for base " + this.base);
}
}
/**
* Return the SSA-Value of the implicit this-pointer (or throw).
*
* <p>This obviously only works on non-static methods. You probably want to check if the method
* has such an implicit this using hasImplicitThis() as this method will throw if there is none.
*
* @return Number of the this.
* @throws IllegalStateException if the function has no implicit this.
*/
public int getThisNo() {
if (this.implicitThis >= 0) {
return this.implicitThis;
} else {
throw new IllegalStateException("getThisNo called for a method that has no implicit this");
}
}
/** If the method has an implicit this parameter. */
public boolean hasImplicitThis() {
return (this.implicitThis >= 0);
}
/**
* Create a "Parameter" containing the Return-Type w/o Type-checking.
*
* <p>This should be of rather theoretical use.
*
* @throws IllegalStateException if used on a void-Function
*/
public Parameter makeReturn(final int ssa) {
if (!hasReturn()) {
throw new IllegalStateException("Can't generate a return-value for a void-function.");
}
switch (this.base) {
case IMETHOD:
return new Parameter(
ssa,
"retVal",
getReturnType(),
ParamerterDisposition.RETURN,
this.base,
this.method.getReference(),
this.descriptorOffset);
case METHOD_REFERENCE:
return new Parameter(
ssa,
"retVal",
getReturnType(),
ParamerterDisposition.RETURN,
this.base,
this.mRef,
this.descriptorOffset);
default:
throw new UnsupportedOperationException(
"No implementation of getReturn() for base " + this.base);
}
}
/**
* Create a "Parameter" containing the Return-Type with Type-checking.
*
* @param ssa The value to return
* @param type The type of ssa
* @param cha The ClassHierarchy to use for the assignability test
* @throws IllegalStateException if used on a void-Function
*/
public Parameter makeReturn(final int ssa, final TypeReference type, final IClassHierarchy cha) {
if (!hasReturn()) {
throw new IllegalStateException("Can't generate a return-value for a void-function.");
}
final TypeReference returnType = getReturnType();
if (returnType.equals(type)) {
return makeReturn(ssa);
} else if (cha == null) {
throw new IllegalArgumentException(
"Needed to test assignability but no cha given."); // TODO: Throw always or never
} else if (isAssignable(type, returnType, cha)) {
return makeReturn(ssa);
} else {
throw new IllegalStateException(
"Return type " + returnType + " is not assignable from " + type);
}
}
/**
* The SSA-Value to acces the parameter appearing first in the Descriptor with.
*
* @throws IllegalArgumentException if the method has no parameters in its Descriptor.
*/
public int firstInSelector() {
if (this.numberOfParameters == 0) {
throw new IllegalArgumentException(
"The method "
+ Objects.requireNonNullElseGet(method, mRef::toString)
+ " has no explicit parameters.");
}
if (this.implicitThis > 1) {
throw new IllegalStateException(
"An internal error in ParameterAccessor locating the implicit this pointer occurred! Invalid: "
+ this.implicitThis);
}
switch (this.base) {
case IMETHOD:
if (this.hasImplicitThis()) { // XXX TODO BUG!
debug(
"This IMethod {} has an implicit this pointer at {}, so firstInSelector is accessible using SSA-Value {}",
this.method,
this.implicitThis,
(this.implicitThis + 1));
return this.implicitThis + 1;
} else {
debug(
"This IMethod {} has no implicit this pointer, so firstInSelector is accessible using SSA-Value 1",
this.method);
return 1;
}
case METHOD_REFERENCE:
if (this.hasImplicitThis()) {
debug(
"This IMethod {} has an implicit this pointer at {}, so firstInSelector is accessible using SSA-Value {}",
this.mRef,
this.implicitThis,
(this.implicitThis + 1));
return this.implicitThis + 1;
} else {
debug(
"This mRef {} has no implicit this pointer, so firstInSelector is accessible using SSA-Value 1",
this.mRef);
return 1;
}
default:
throw new UnsupportedOperationException(
"No implementation of firstInSelector() for base " + this.base);
}
}
/**
* Prefer: getParameter(int no) or all().
*
* <p>Get the type of the parameter (not this) using a fixed numbering.
*
* <p>Number 1 is the first parameter in the methods Selector. No matter if the function has an
* implicit this pointer.
*
* <p>Use all() if you want to get all parameter-types.
*
* @param no the number in the Selector
* @return the type of the parameter
*/
public TypeReference getParameterType(final int no) { // XXX Remove?
switch (this.base) {
case IMETHOD:
case METHOD_REFERENCE:
return this.method.getParameterType(getParameterNo(no));
default:
throw new UnsupportedOperationException(
"No implementation of getParameterType() for base " + this.base);
}
}
/**
* First parameter in the selector that matches _exactly_.
*
* @return first parameter found or null if there is none
* @throws IllegalArgumentException if searching for void or null
*/
public Parameter firstOf(final TypeName tName) {
if (tName == null) {
throw new IllegalArgumentException("Search-name may not be null");
}
if (tName.equals(TypeReference.VoidName)) {
throw new IllegalArgumentException("You are searching for 'void' as a parameter.");
}
final List<Parameter> all = all();
// ****
// Implementation starts here
for (final Parameter cand : all) {
if (cand.getType().getName().equals(tName)) {
return cand;
}
}
return null;
}
/**
* First parameter in the selector that matches _exactly_.
*
* @return first parameter found or null if there is none
* @throws IllegalArgumentException if searching for void or null
*/
public Parameter firstOf(final TypeReference tRef) {
if (tRef == null) {
throw new IllegalArgumentException("Search-name may not be null");
}
if (tRef.equals(TypeReference.Void)) {
throw new IllegalArgumentException("You are searching for 'void' as a parameter.");
}
final List<Parameter> all = all();
// ****
// Implementation starts here
for (final Parameter cand : all) {
if (cand.getType().equals(tRef)) {
return cand;
}
}
return null;
}
/**
* All parameters in the selector that are a subclass of tName (slow).
*
* <p>TypeNames have to be looked up first, do prefer the variant with the TypeReference if one is
* available.
*
* @throws IllegalArgumentException if searching for void or null
*/
public List<Parameter> allExtend(final TypeName tName, final IClassHierarchy cha) {
if (tName == null) {
throw new IllegalArgumentException("Search-name may not be null");
}
if (tName.equals(TypeReference.VoidName)) {
throw new IllegalArgumentException("You are searching for 'void' as a parameter.");
}
if (cha == null) {
throw new IllegalArgumentException(
"Can't search ClassHierarchy without having a ClassHierarchy (is null)");
}
final List<Parameter> all = all();
final List<Parameter> allExctends = new ArrayList<>();
IClass searchType = null;
final IClassLoader[] allLoaders = cha.getLoaders();
// ****
// Implementation starts here
{ // Retrieve a reference of the type
for (final IClassLoader loader : allLoaders) {
searchType = loader.lookupClass(tName);
if (searchType != null) {
break;
}
}
}
if (searchType == null) {
throw new IllegalStateException("Could not find " + tName + " in any loader!");
} else {
debug("Retrieved {} as {}", tName, searchType);
}
for (final Parameter cand : all) {
final IClass candClass = cha.lookupClass(cand.getType());
if (candClass != null) { // TODO: Extra function
if (cha.isSubclassOf(candClass, searchType)) {
allExctends.add(cand);
}
} else {
for (final IClassLoader loader : cha.getLoaders()) {
final IClass c = loader.lookupClass(cand.getType().getName());
if (c != null) {
info("Using alternative for from: {}", cand);
if (cha.isSubclassOf(c, searchType)) {
allExctends.add(cand);
}
}
}
// TODO: That's true for base-type too
warn("Unable to look up IClass of {}", cand);
}
}
return allExctends;
}
/**
* All parameters in the selector that are a subclass of tRef (slow).
*
* @throws IllegalArgumentException if searching for void or null
*/
public List<Parameter> allExtend(final TypeReference tRef, final IClassHierarchy cha) {
if (tRef == null) {
throw new IllegalArgumentException("Search TypeReference may not be null");
}
if (tRef.equals(TypeReference.Void)) {
throw new IllegalArgumentException("You are searching for 'void' as a parameter.");
}
if (cha == null) {
throw new IllegalArgumentException(
"Can't search ClassHierarchy without having a ClassHierarchy (is null)");
}
// ****
// Implementation starts here
final IClass searchType = cha.lookupClass(tRef);
final List<Parameter> all = all();
final List<Parameter> allExctends = new ArrayList<>();
if (searchType == null) {
throw new IllegalStateException("Could not find the IClass of " + tRef);
} else {
debug("Reteived {} as {}", tRef, searchType);
}
for (final Parameter cand : all) {
final IClass candClass = cha.lookupClass(cand.getType());
if (candClass != null) {
if (cha.isSubclassOf(candClass, searchType)) {
allExctends.add(cand);
}
} else {
// TODO: That's true for base-type too
warn("Unable to look up IClass of {}", cand);
}
}
return allExctends;
}
/**
* First parameter in the selector that is a subclass of tName (slow).
*
* <p>TypeNames have to be lloked up first, do prefer the variant with the TypeReference if one is
* available.
*
* @return first parameter found or null if there is none
* @throws IllegalArgumentException if searching for void or null
*/
public Parameter firstExtends(final TypeName tName, final IClassHierarchy cha) {
if (tName == null) {
throw new IllegalArgumentException("Search-name may not be null");
}
if (tName.equals(TypeReference.VoidName)) {
throw new IllegalArgumentException("You are searching for 'void' as a parameter.");
}
if (cha == null) {
throw new IllegalArgumentException(
"Can't search ClassHierarchy without having a ClassHierarchy (is null)");
}
final List<Parameter> all = all();
IClass searchType = null;
final IClassLoader[] allLoaders = cha.getLoaders();
// ****
// Implementation starts here
{ // Reteive a reference of the type
for (final IClassLoader loader : allLoaders) {
searchType = loader.lookupClass(tName);
if (searchType != null) {
break;
}
}
}
if (searchType == null) {
throw new IllegalStateException("Could not find " + tName + " in any loader!");
} else {
debug("Reteived {} as {}", tName, searchType);
}
for (final Parameter cand : all) {
final IClass candClass = cha.lookupClass(cand.getType());
if (candClass != null) {
if (cha.isSubclassOf(candClass, searchType)) {
return cand;
}
} else {
for (final IClassLoader loader : cha.getLoaders()) {
final IClass c = loader.lookupClass(cand.getType().getName());
if (c != null) {
info("Using alternative for from: {}", cand);
if (cha.isSubclassOf(c, searchType)) {
return cand;
}
}
}
// TODO: That's true for primitive-type too
warn("Unable to look up IClass of {}", cand);
}
}
return null;
}
/**
* First parameter in the selector that is a subclass of tRef (slow).
*
* @return first parameter found or null if there is none
* @throws IllegalArgumentException if searching for void or null
*/
public Parameter firstExtends(final TypeReference tRef, final IClassHierarchy cha) {
if (tRef == null) {
throw new IllegalArgumentException("Search TypeReference may not be null");
}
if (tRef.equals(TypeReference.Void)) {
throw new IllegalArgumentException("You are searching for 'void' as a parameter.");
}
if (cha == null) {
throw new IllegalArgumentException(
"Can't search ClassHierarchy without having a ClassHierarchy (is null)");
}
// ****
// Implementation starts here
final IClass searchType = cha.lookupClass(tRef);
final List<Parameter> all = all();
if (searchType == null) {
throw new IllegalStateException("Could not find the IClass of " + tRef);
} else {
debug("Reteived {} as {}", tRef, searchType);
}
for (final Parameter cand : all) {
final IClass candClass = cha.lookupClass(cand.getType());
if (candClass != null) {
if (cha.isSubclassOf(candClass, searchType)) {
return cand;
}
} else {
// TODO: That's true for base-type too
warn("Unable to look up IClass of {}", cand);
}
}
return null;
}
/**
* The first SSA-Number after the parameters.
*
* <p>This is useful for making synthetic methods.
*/
public int getFirstAfter() {
return this.numberOfParameters + 2; // Should be +1 ?
}
/**
* Generate the params-param for an InvokeIstruction w/o type checking.
*
* @param args list to build the arguments from - without implicit this
*/
public int[] forInvokeStatic(final List<? extends SSAValue> args) {
if (args == null) { // XXX Allow?
throw new IllegalArgumentException("args is null");
}
int[] params = new int[args.size()];
if (params.length == 0) {
return params;
}
if ((args.get(1) instanceof Parameter)
&& (((Parameter) args.get(1)).getDisposition() == ParamerterDisposition.THIS)) {
warn("The first argument is an implicit this: {} this may be ok however.", args.get(1));
}
// ****
// Implementation starts here
Arrays.setAll(params, i -> args.get(i).getNumber());
return params;
}
/**
* Generate the params-param for an InvokeIstruction with type checking.
*
* @param args list to build the arguments from - without implicit this
* @param target the method to be called - for type checking only
* @param cha if types don't match exactly needed for the assignability check (may be null if that
* check is not wanted)
* @throws IllegalArgumentException if you call this method on a target that needs an implicit
* this
* @throws IllegalArgumentException if args length does not match the targets param-length
* @throws IllegalArgumentException if a parameter is unassignable
*/
public int[] forInvokeStatic(
final List<? extends SSAValue> args,
final ParameterAccessor target,
final IClassHierarchy cha) {
if (args == null) {
throw new IllegalArgumentException("args is null");
}
if (target == null) {
throw new IllegalArgumentException("ParameterAccessor for the target is null");
}
if (target.hasImplicitThis()) {
throw new IllegalArgumentException(
"You used forInvokeStatic on a method that has an implicit this pointer");
}
if (target.getNumberOfParameters() != args.size()) {
throw new IllegalArgumentException(
"Number of arguments mismatch: "
+ args.size()
+ " given on a method that "
+ "needs "
+ target.getNumberOfParameters()
+ " arguments. Arguments given were "
+ args
+ " for a static "
+ "call to "
+ target);
}
int[] params = new int[args.size()];
if (params.length == 0) {
return params;
}
if ((args.get(1) instanceof Parameter)
&& (((Parameter) args.get(1)).getDisposition() == ParamerterDisposition.THIS)) {
warn("The first argument is an implicit this: {} this may be ok however.", args.get(1));
}
// ****
// Implementation starts here
for (int i = 0; i < params.length; ++i) {
final SSAValue param = args.get(i);
if (param.getType().equals(target.getParameter(i).getType())) {
params[i] = param.getNumber();
} else {
if (cha == null) {
throw new IllegalArgumentException(
"Parameter "
+ i
+ " ("
+ param
+ ") of the Arguments list "
+ "is not equal to param "
+ i
+ " ( "
+ target.getParameter(i)
+ ") of "
+ target
+ "and no ClassHierarchy was given to test assignability");
} else if (isAssignable(param, target.getParameter(i), cha)) {
params[i] = param.getNumber();
} else {
throw new IllegalArgumentException(
"Parameter "
+ i
+ " ("
+ param
+ ") of the Arguments list "
+ "is not assignable to param "
+ i
+ " ( "
+ target.getParameter(i)
+ ") of "
+ target);
}
}
}
return params;
}
/**
* Generate the params-param for an InvokeIstruction w/o type checking.
*
* @param self the this-pointer to use
* @param args the rest of the arguments. Be shure it does not start with a this pointer. This is
* _not_ checked so you can use a this-pointer as an argument. However a warning is issued.
* @throws IllegalArgumentException if the value of self is to small in the current method
*/
public int[] forInvokeVirtual(final int self, final List<? extends SSAValue> args) {
if (args == null) {
throw new IllegalArgumentException("args is null");
}
if ((this.base == BasedOn.METHOD_REFERENCE) && (self < 1)) {
throw new IllegalArgumentException(
"The first SSA-Value of a MethodReference is 1. The given this (self) is " + self);
} else if (self < 0) {
throw new IllegalArgumentException("self = " + self + " < 0");
}
int[] params = new int[args.size() + 1];
if ((params.length > 1)
&& (args.get(1) instanceof Parameter)
&& (((Parameter) args.get(1)).getDisposition() == ParamerterDisposition.THIS)) {
warn("The first argument is an implicit this: {} this may be ok however.", args.get(1));
}
// ****
// Implementation starts here
//
params[0] = self;
for (int i = 1; i < params.length; ++i) {
params[i] = args.get(i - 1).getNumber();
}
return params;
}
/**
* Generate the params-param for an InvokeIstruction with type checking.
*
* @param self the this-pointer to use
* @param args list to build the arguments from - without implicit this
* @param target the method to be called - for type checking only
* @param cha if types don't match exactly needed for the assignability check (may be null if that
* check is not wanted)
* @throws IllegalArgumentException if you call this method on a target that needs an implicit
* this
* @throws IllegalArgumentException if args length does not match the targets param-length
* @throws IllegalArgumentException if a parameter is unassignable
*/
public int[] forInvokeVirtual(
final int self,
final List<? extends SSAValue> args,
final ParameterAccessor target,
final IClassHierarchy cha) {
if (args == null) {
throw new IllegalArgumentException("args is null");
}
if ((this.base == BasedOn.METHOD_REFERENCE) && (self < 1)) {
throw new IllegalArgumentException(
"The first SSA-Value of a MethodReference is 1. The given this (self) is " + self);
} else if (self < 0) {
throw new IllegalArgumentException("self = " + self + " < 0");
}
if (target == null) {
throw new IllegalArgumentException("ParameterAccessor for the target is null");
}
if (!target.hasImplicitThis()) {
throw new IllegalArgumentException(
"You used forInvokeVirtual on a method that has no implicit this pointer");
}
if (target.getNumberOfParameters() != args.size() + 1) { // TODO: Verify
throw new IllegalArgumentException(
"Number of arguments mismatch: "
+ args.size()
+ " given on a method that "
+ "needs "
+ target.getNumberOfParameters()
+ " arguments. Arguments given were "
+ args
+ " for a static "
+ "call to "
+ target);
}
int[] params = new int[args.size() + 1];
if ((params.length > 1)
&& (args.get(1) instanceof Parameter)
&& (((Parameter) args.get(1)).getDisposition() == ParamerterDisposition.THIS)) {
warn("The first argument is an implicit this: {} this may be ok however.", args.get(1));
}
// ****
// Implementation starts here
params[0] = self; // TODO: Can't typecheck this!
for (int i = 1; i < params.length; ++i) {
final SSAValue param = args.get(i - 1);
if (param.getType().equals(target.getParameter(i).getType())) {
params[i] = param.getNumber();
} else {
if (cha == null) {
throw new IllegalArgumentException(
"Parameter "
+ i
+ " ("
+ param
+ ") of the Arguments list "
+ "is not equal to param "
+ i
+ " ( "
+ target.getParameter(i)
+ ") of "
+ target
+ "and no ClassHierarchy was given to test assignability");
} else if (isAssignable(param, target.getParameter(i), cha)) {
params[i] = param.getNumber();
} else {
throw new IllegalArgumentException(
"Parameter "
+ i
+ " ("
+ param
+ ") of the Arguments list "
+ "is not assignable to param "
+ i
+ " ( "
+ target.getParameter(i)
+ ") of "
+ target);
}
}
}
return params;
}
/**
* Connects though parameters from the calling function (overridable) - CAUTION:.
*
* <p>This functions makes is decisions based on Type-Referes only so if a TypeReference occurs
* multiple times in the caller or callee it may make surprising connections.
*
* <p>The List of Parameters is generated based on the overrides, than parameters in 'this' are
* searched, finally we'll fall back to defaults. A "perfect match" is searched.
*
* <p>If a parameter was not assigned yet these three sources are considdered again but
* cha.isAssignableFrom is used.
*
* <p>If the parameter was still not found a value of 'null' is used.
*
* <p>This funktion is useful when generating wrapper-functions.
*
* @param callee The function to generate the parameter-list for
* @param overrides If a parameter occurs here, it is preferred over the ones present in this
* @param defaults If a parameter is not present in this or the overrides, defaults are searched.
* If the parameter is not present there null is assigned.
* @param cha Optional class hierarchy for testing assignability
* @return the parameter-list for the call of toMethod
*/
public List<SSAValue> connectThrough(
final ParameterAccessor callee,
Set<? extends SSAValue> overrides,
Set<? extends SSAValue> defaults,
final IClassHierarchy cha,
IInstantiator instantiator,
Object... instantiatorArgs) {
if (callee == null) {
throw new IllegalArgumentException("Cannot connect through to null-callee");
}
if (overrides == null) {
overrides = Collections.emptySet();
}
if (defaults == null) {
defaults = Collections.emptySet();
}
if (callee.getNumberOfParameters() == 0) {
return new ArrayList<>(0);
}
final List<SSAValue> assigned = new ArrayList<>(); // TODO: Set initial size
final List<Parameter> calleeParams = callee.all();
final List<Parameter> thisParams = all();
// ****
// Implementation starts here
debug(
"Collecting parameters for callee {}",
((callee.mRef != null) ? callee.mRef : callee.method));
debug("\tThe calling function is {}", ((this.mRef != null) ? this.mRef : this.method));
forEachParameter:
for (final Parameter param : calleeParams) {
debug("\tSearching candidate for {}", param);
final TypeReference paramType = param.getType();
{ // Exact match in overrides
for (final SSAValue cand : overrides) {
if (cand.getType().getName().equals(paramType.getName())) { // XXX: What about the loader?
assigned.add(cand);
debug("\t\tAsigning: {} from the overrides (eq)", cand);
continue forEachParameter;
} else {
debug("\t\tSkipping: {} of the overrides (eq)", cand);
}
}
}
{ // Exact match in this params
for (final Parameter cand : thisParams) {
if (cand.getType().getName().equals(paramType.getName())) {
assigned.add(cand);
debug("\t\tAsigning: {} from callers params (eq)", cand);
continue forEachParameter;
} else {
debug("\t\tSkipping: {} of the callers params (eq)", cand);
}
}
}
{ // Exact match in defaults
for (final SSAValue cand : defaults) {
if (cand.getType().getName().equals(paramType.getName())) {
assigned.add(cand);
debug("\t\tAsigning: {} from the defaults (eq)", cand);
continue forEachParameter;
}
}
}
debug("\tThe parameter is still not found - try again using an assignability check...");
// If we got here we need cha
if (cha != null) {
{ // Assignable from overrides
try {
for (final SSAValue cand : overrides) {
if (isAssignable(cand, param, cha)) {
assigned.add(cand);
debug("\t\tAsigning: {} from the overrides (ass)", cand);
continue forEachParameter;
}
}
} catch (ClassLookupException e) {
}
}
{ // Assignable from this params
for (final Parameter cand : thisParams) {
try {
if (isAssignable(cand, param, cha)) {
assigned.add(cand);
debug("\t\tAsigning: {} from the callrs params (ass)", cand);
continue forEachParameter;
}
} catch (ClassLookupException e) {
}
}
}
{ // Assignable from defaults
for (final SSAValue cand : defaults) {
if (isAssignable(cand, param, cha)) {
assigned.add(cand);
debug("\t\tAsigning: {} from the defaults (ass)", cand);
continue forEachParameter;
}
}
}
if (instantiator != null) {
info("Creating new instance of: {} in call to {}", param, callee);
/*{ // DEBUG
System.out.println("Creating new instance of: " + param);
System.out.println("in connectThrough");
System.out.println("\tCaller:\t\t" + this.forMethod());
System.out.println("\tCallee:\t\t" + callee.forMethod());
System.out.println("\tOverrides:\t" + overrides);
System.out.println("\tDefaults:\t" + defaults);
} // */
final int inst = instantiator.createInstance(param.getType(), instantiatorArgs);
if (inst < 0) {
warn(
"No type was assignable and the instantiator returned an invalidone! Using null for {}",
param);
assigned.add(null);
} else {
final Parameter newParam;
if (this.base == BasedOn.IMETHOD) {
newParam =
new Parameter(
inst,
"craftedForCall",
param.getType(),
ParamerterDisposition.NEW,
this.base,
this.method.getReference(),
this.descriptorOffset);
} else if (this.base == BasedOn.METHOD_REFERENCE) {
newParam =
new Parameter(
inst,
"craftedForCall",
param.getType(),
ParamerterDisposition.NEW,
this.base,
this.mRef,
this.descriptorOffset);
} else {
throw new UnsupportedOperationException("Can't handle base " + this.base);
}
assigned.add(newParam);
}
} else {
warn("No IInstantiator given and no known parameter assignable - using null");
assigned.add(null);
}
} else {
// TODO: CreateInstance Call-Back
warn("No type was equal. We can't ask isAssignable since we have no cha!");
assigned.add(null);
} // of (cha != null)
continue forEachParameter;
// Assertions.UNREACHABLE(); // Well it's unreachable
} // of final Parameter param : calleeParams
if (assigned.size() != calleeParams.size()) {
System.err.println(
"Assigned "
+ assigned.size()
+ " params to a method taking "
+ calleeParams.size()
+ " params!");
System.err.println("The call takes the parameters");
for (Parameter param : calleeParams) {
System.err.println("\t" + param);
}
System.err.println("The following were assigned:");
for (int i = 0; i < assigned.size(); ++i) {
System.err.println("\tAssigned parameter " + (i + 1) + " is " + assigned.get(i));
}
throw new IllegalStateException("Parameter mismatch!");
}
return assigned;
}
// *****************************************************************************
//
// Private helper functions follow...
/** Does "to x := from" hold?. */
public static boolean isAssignable(
final TypeReference from, final TypeReference to, final IClassHierarchy cha) {
if (cha == null) {
throw new IllegalArgumentException("ClassHierarchy may not be null");
}
if (from.getName().equals(to.getName())) return true;
if (from.isPrimitiveType() && to.isPrimitiveType()) {
// return PrimitiveAssignability.isAssignableFrom(from.getName(), to.getName());
return PrimitiveAssignability.isAssignableFrom(
to.getName(), from.getName()); // TODO: Which way
}
if (from.isPrimitiveType() || to.isPrimitiveType()) {
return false;
}
IClass fromClass = cha.lookupClass(from);
IClass toClass = cha.lookupClass(to);
if (fromClass == null) {
debug(
"Unable to look up the type of from="
+ from
+ " in the ClassHierarchy - tying other loaders...");
for (final IClassLoader loader : cha.getLoaders()) {
final IClass cand = loader.lookupClass(from.getName());
if (cand != null) {
debug("Using alternative for from: {}", cand);
fromClass = cand;
break;
}
}
if (fromClass == null) {
throw new ClassLookupException(
"Unable to look up the type of from=" + from + " in the ClassHierarchy");
// return false; // TODO
}
}
if (toClass == null) {
debug(
"Unable to look up the type of to="
+ to
+ " in the ClassHierarchy - tying other loaders...");
for (final IClassLoader loader : cha.getLoaders()) {
final IClass cand = loader.lookupClass(to.getName());
if (cand != null) {
debug("Using alternative for to: {}", cand);
toClass = cand;
break;
}
}
if (toClass == null) {
error("Unable to look up the type of to={} in the ClassHierarchy", to);
return false;
// throw new ClassLookupException("Unable to look up the type of to=" + to +
// " in the ClassHierarchy");
}
}
// cha.isAssignableFrom (IClass c1, IClass c2)
// Does an expression c1 x := c2 y typecheck?
trace(
"isAssignableFrom({}, {}) = {}",
toClass,
fromClass,
cha.isAssignableFrom(toClass, fromClass));
return cha.isAssignableFrom(toClass, fromClass);
}
/** Is sub a subclass of superC (or the same). */
public static boolean isSubclassOf(
final TypeReference sub, final TypeReference superC, final IClassHierarchy cha)
throws ClassLookupException {
if (cha == null) {
throw new IllegalArgumentException("ClassHierarchy may not be null");
}
if (sub.getName().equals(superC.getName())) return true;
if (sub.isPrimitiveType() || superC.isPrimitiveType()) {
return false;
}
IClass subClass = cha.lookupClass(sub);
IClass superClass = cha.lookupClass(superC);
if (subClass == null) {
debug(
"Unable to look up the type of from="
+ sub
+ " in the ClassHierarchy - tying other loaders...");
for (final IClassLoader loader : cha.getLoaders()) {
final IClass cand = loader.lookupClass(sub.getName());
if (cand != null) {
debug("Using alternative for from: {}", cand);
subClass = cand;
break;
}
}
if (subClass == null) {
throw new ClassLookupException(
"Unable to look up the type of from=" + sub + " in the ClassHierarchy");
}
}
if (superClass == null) {
debug(
"Unable to look up the type of to="
+ superC
+ " in the ClassHierarchy - tying other loaders...");
for (final IClassLoader loader : cha.getLoaders()) {
final IClass cand = loader.lookupClass(superC.getName());
if (cand != null) {
debug("Using alternative for to: {}", cand);
superClass = cand;
break;
}
}
if (superClass == null) {
error("Unable to look up the type of to={} in the ClassHierarchy", superC);
throw new ClassLookupException(
"Unable to look up the type of to=" + superC + " in the ClassHierarchy");
}
}
return cha.isSubclassOf(subClass, superClass);
}
/** The method this accessor reads the parameters from. */
public MethodReference forMethod() {
if (this.mRef != null) {
return this.mRef;
} else {
return this.method.getReference();
}
}
// *****************************************************************************
//
// Shorthand functions follow...
/** Does "to x := from" hold?. */
protected boolean isAssignable(
final SSAValue from, final SSAValue to, final IClassHierarchy cha) {
return isAssignable(from.getType(), to.getType(), cha);
}
/**
* Shorthand for forInvokeStatic(final List<? extends Parameter> args, final
* ParameterAccessor target, final IClassHierarchy cha).
*
* <p>Generates a new ParameterAccessor for target and hands the call through.
*/
public int[] forInvokeStatic(
final List<? extends Parameter> args,
final MethodReference target,
final IClassHierarchy cha) {
return forInvokeStatic(args, new ParameterAccessor(target, cha), cha);
}
/**
* Shorthand for forInvokeVirtual(final int self, final List<? extends Parameter> args,
* final ParameterAccessor target, final IClassHierarchy cha).
*
* <p>Generates a new ParameterAccessor for target and hands the call through.
*/
public int[] forInvokeVirtual(
final int self,
final List<? extends Parameter> args,
final MethodReference target,
final IClassHierarchy cha) {
return forInvokeVirtual(self, args, new ParameterAccessor(target, cha), cha);
}
/** If the method returns a value eg is non-void. */
public boolean hasReturn() {
return (getReturnType() != TypeReference.Void);
}
/**
* Assign parameters to a call based on their type.
*
* <p>this variant of connectThrough cannot create new instances if needed.
*
* @param callee The function to generate the parameter-list for
* @param overrides If a parameter occurs here, it is preferred over the ones present in this
* @param defaults If a parameter is not present in this or the overrides, defaults are searched.
* If the parameter is not present there null is assigned.
* @param cha Optional class hierarchy for testing assignability
* @return the parameter-list for the call of toMethod
*/
public List<SSAValue> connectThrough(
final ParameterAccessor callee,
Set<? extends SSAValue> overrides,
Set<? extends SSAValue> defaults,
final IClassHierarchy cha) {
return connectThrough(callee, overrides, defaults, cha, null);
}
// *****************************************************************************
//
// Hand-through functions follow...
/** Handed through to the IMethod / MethodReference */
public TypeReference getReturnType() {
switch (this.base) {
case IMETHOD:
return this.method.getReturnType();
case METHOD_REFERENCE:
return this.mRef.getReturnType();
default:
throw new UnsupportedOperationException(
"No implementation of getReturnType() for base " + this.base);
}
}
/** Number of parameters _excluding_ implicit this */
public int getNumberOfParameters() {
return this.numberOfParameters;
}
/** Extensive output for debugging purposes. */
public String dump() {
final StringBuilder ret =
new StringBuilder()
.append("Parameter Accessor for ")
.append(
(this.mRef != null) ? "mRef:" + this.mRef : "IMethod: " + this.method.toString())
.append("\nContains ")
.append(this.numberOfParameters)
.append(" Parameters ")
.append(this.base)
.append('\n');
/*for (int i = 1; i <= this.numberOfParameters; ++i) {
try {
ret += "\t" + getParameter(i).toString() + "\n";
} catch (Exception e) {
ret += "\tNone at " + i + "\n";
}
}*/
ret.append("\nAnd all is:\n");
for (Parameter p : all()) {
ret.append('\t').append(p).append('\n');
}
if (hasImplicitThis()) {
ret.append("This: ").append(getThis());
} else {
ret.append("Is static");
}
return ret.toString();
}
@Override
public String toString() {
return "<ParamAccessor forMethod=" + this.forMethod() + " />";
}
private static void debug(String s, Object... args) {
if (DEBUG) {
System.err.printf(s, args);
}
}
private static void info(String s, Object... args) {
if (DEBUG) {
System.err.printf(s, args);
}
}
private static void warn(String s, Object... args) {
if (DEBUG) {
System.err.printf(s, args);
}
}
private static void trace(String s, Object... args) {
if (DEBUG) {
System.err.printf(s, args);
}
}
private static void error(String s, Object... args) {
if (DEBUG) {
System.err.printf(s, args);
}
}
}
| 66,986
| 32.611139
| 120
|
java
|
WALA
|
WALA-master/core/src/main/java/com/ibm/wala/core/util/ssa/SSAValue.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.core.util.ssa;
import com.ibm.wala.types.MethodReference;
import com.ibm.wala.types.TypeName;
import com.ibm.wala.types.TypeReference;
/**
* A number representating an SSA-Value and its type.
*
* <p>WALA does not use this on a regular basis but it may come in handy for creating
* SyntheticMethods.
*
* <p>Use ParameterAccessor to get the parameters of a function as SSAValues.
*
* @see com.ibm.wala.core.util.ssa.TypeSafeInstructionFactory
* @see com.ibm.wala.core.util.ssa.ParameterAccessor
* @author Tobias Blaschke <code@tobiasblaschke.de>
* @since 2013-10-20
*/
public class SSAValue {
/** The SSA Value itself */
protected final int number;
/** The type of this variable */
protected final TypeReference type;
/** All variables with the same name in the source code share a key. */
public final VariableKey key; // TODO: Protect again?
/** Method the variable is valid in */
protected final MethodReference mRef;
/** If an instruction wrote to this value (set manually) */
private boolean isAssigned;
/** All variables with the same name in the source code. */
public interface VariableKey {}
/** A key that cannot be recreated. */
public static class UniqueKey implements VariableKey {
public UniqueKey() {}
}
/** A key that matches variables by their type - does not compare to NamedKey. */
public static class TypeKey implements VariableKey {
public final TypeName type;
public TypeKey(final TypeName type) {
this.type = type;
}
@Override
public boolean equals(Object o) {
if (o == null) {
return false;
} else if (o instanceof TypeKey) {
TypeKey other = (TypeKey) o;
return this.type.equals(other.type);
} else if (o instanceof WeaklyNamedKey) {
WeaklyNamedKey other = (WeaklyNamedKey) o;
return this.type.equals(other.type);
} else {
return false;
}
}
@Override
public int hashCode() {
return this.type.hashCode();
}
@Override
public String toString() {
return "<TypeKey type=\"" + this.type + "\" />";
}
}
/** This NamedKey also equals to TypeKeys. */
public static class WeaklyNamedKey extends NamedKey {
public WeaklyNamedKey(final TypeName type, final String name) {
super(type, name);
}
@Override
public boolean equals(Object o) {
if (o == null) {
return false;
} else if (o instanceof NamedKey) {
NamedKey other = (NamedKey) o;
return (this.type.equals(other.type) && this.name.equals(other.name));
} else if (o instanceof TypeKey) {
TypeKey other = (TypeKey) o;
return this.type.equals(other.type);
} else {
return false;
}
}
@Override
public int hashCode() {
return this.type.hashCode() * ((this.name == null) ? 1 : this.name.hashCode());
}
@Override
public String toString() {
return "<WaklyNamedKey type=\"" + this.type + "\" name=\"" + this.name + "\" />";
}
}
/** Identify variables by a string and type. */
public static class NamedKey implements VariableKey {
public final String name;
public final TypeName type;
public NamedKey(final TypeName type, final String name) {
this.name = name;
this.type = type;
}
@Override
public boolean equals(Object o) {
if (o == null) {
return false;
} else if (o instanceof NamedKey) {
NamedKey other = (NamedKey) o;
return (this.type.equals(other.type) && this.name.equals(other.name));
} else {
return false;
}
}
@Override
public int hashCode() {
return this.type.hashCode() * ((this.name == null) ? 1 : this.name.hashCode());
}
@Override
public String toString() {
return "<NamedKey type=\"" + this.type + "\" name=\"" + this.name + "\" />";
}
}
/**
* Makes a SSAValue with number and type valid in the specified Method.
*
* <p>The number is the one to use with SSAInstructions.
*
* <p>The MethodReference (validIn) is an optional value. However the TypeSafeInstructionFactory
* relies on it to verify its ReturnInstruction so setting it does not hurt.
*
* <p>The variableName is optional and not really used yet. It might be handy for debugging.
*
* @param number access the value using this number
* @param validIn optionally assign this value to a method
* @throws IllegalArgumentException on negative parameter number
*/
public SSAValue(
final int number,
final TypeReference type,
final MethodReference validIn,
final VariableKey key) {
if (number < 0) {
throw new IllegalArgumentException(
"A SSA-Value can't have a negative number, " + number + "given");
}
if (type == null) {
throw new IllegalArgumentException("The type for the SSA-Variable may not be null");
}
if (type.equals(TypeReference.Void)) {
throw new IllegalArgumentException("You can't create a SSA-Variable of type void");
}
this.type = type;
this.number = number;
this.key = key;
this.mRef = validIn;
this.isAssigned = false;
}
/** Generates a SSAValue with a NamedKey (or TypeKey if name==null). */
public SSAValue(
final int number,
final TypeReference type,
final MethodReference validIn,
final String variableName) {
this(
number,
type,
validIn,
((variableName == null)
? new TypeKey(type.getName())
: new NamedKey(type.getName(), variableName)));
}
/** Generates a SSAValue with a UniqueKey. */
public SSAValue(final int number, final TypeReference type, final MethodReference validIn) {
this(number, type, validIn, new UniqueKey());
}
/**
* Create a new instance of the same type, validity and name.
*
* <p>Of course you still have to assign something to this value.
*
* @param number the new number to use
* @param copyFrom where to get the rest of the attributes
*/
public SSAValue(final int number, SSAValue copyFrom) {
this(number, copyFrom.type, copyFrom.mRef, copyFrom.key);
}
/**
* The SSA-Value to use with SSAInstructions.
*
* <p>As an alternative one can generate Instructions using the TypeSafeInstructionFactory which
* takes SSAValues as parameters.
*/
public int getNumber() {
return this.number;
}
/** The type this SSA-Value represents. */
public TypeReference getType() {
return this.type;
}
/** If setAssigned() was called on this variable. */
public boolean isAssigned() {
return this.isAssigned;
}
/**
* Mark this variable as assigned.
*
* <p>Sets the value returned by isAssigned() to true. As a safety measure one can only call this
* method once on a SSAValue, the second time raises an exception.
*
* <p>The TypeSafeInstructionFactory calls this method when writing to an SSAValue. It does
* however not check the setting when reading from an SSAValue.
*
* <p>This does obviously not prevent from generating a new SSAValue with the same number and
* double-assign anyhow.
*
* @throws IllegalStateException if the variable was already assigned to
*/
public void setAssigned() {
if (this.isAssigned) {
throw new IllegalStateException("The SSA-Variable " + this + " was assigned to twice.");
}
this.isAssigned = true;
}
/**
* Return the MethodReference this Variable was set valid in.
*
* <p>The value returned by this method is the one set in the constructor. As this parameter is
* optional to it this function may return null if it was not set.
*
* @return the argument validIn to the constructor
*/
public MethodReference getValidIn() {
return this.mRef;
}
/**
* Return the optional variable name.
*
* @return the argument variableName to the constructor
*/
public String getVariableName() {
if (this.key instanceof NamedKey) {
return ((NamedKey) this.key).name;
} else {
return null; // TODO: build a name?
}
}
@Override
public String toString() {
return "<SSAValue " + this.number + " type=" + this.type + " validIn=" + this.mRef + '>';
}
@Override
public boolean equals(Object o) {
if (o instanceof SSAValue) {
final SSAValue other = (SSAValue) o;
return ((this.number == other.number)
&& this.mRef.equals(other.mRef)
&& this.type.equals(other.type));
}
throw new IllegalArgumentException("Can't compare SSAValue to " + o.getClass());
}
@Override
public int hashCode() {
return 157 * this.number * this.mRef.hashCode() * this.type.hashCode();
}
}
| 10,720
| 31.195195
| 99
|
java
|
WALA
|
WALA-master/core/src/main/java/com/ibm/wala/core/util/ssa/SSAValueManager.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.core.util.ssa;
import com.ibm.wala.core.util.ssa.SSAValue.NamedKey;
import com.ibm.wala.core.util.ssa.SSAValue.VariableKey;
import com.ibm.wala.core.util.strings.Atom;
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.HashMap;
import java.util.List;
import java.util.Map;
/**
* Manage SSA-Variables in synthetic methods.
*
* @author Tobias Blaschke <code@tobiasblaschke.de>
* @since 2013-09-19
*/
public class SSAValueManager {
private static final boolean DEBUG = false;
private final boolean AUTOMAKE_NAMES = true;
private enum ValueStatus {
/** Value has never been mentioned before */
UNUSED,
/** Awaiting to be set using setAllocation */
UNALLOCATED,
/** Set and ready to use */
ALLOCATED,
/** Has to be assigned using a Phi-Instruction */
FREE,
/** Should only be used as argument to a Phi Instruction */
INVALIDATED,
/** Should not be referenced any more */
CLOSED,
/** Well FREE and INVALIDATED */
FREE_INVALIDATED,
/** Well FREE and CLOSED */
FREE_CLOSED
}
// TODO: nextLocal may be 0 on getUnamanged!
/** The next variable not under management yet */
private int nextLocal;
/** for managing cascaded code blocks */
private int currentScope = 0;
/** Description only used for toString() */
private final String description;
private final MethodReference forMethod;
/** User-Defined debugging info */
public String breadCrumb = "";
private static class Managed<T extends SSAValue> {
public ValueStatus status = ValueStatus.UNUSED;
public SSAInstruction setBy = null;
public int setInScope = -1;
public final VariableKey key;
public final T value;
public Managed(final T value, final VariableKey key) {
this.value = value;
this.key = key;
}
@Override
public String toString() {
return "<Managed "
+ this.value
+ " key=\""
+ this.key
+ "\" status=\""
+ this.status
+ " setIn=\""
+ this.setInScope
+ "\" setBy=\""
+ this.setBy
+ "\" />";
}
}
/** The main data-structure of the management */
private final Map<VariableKey, List<Managed<? extends SSAValue>>> seenTypes =
HashMapFactory.make();
private final List<SSAValue> unmanaged = new ArrayList<>();
public SSAValueManager(ParameterAccessor acc) {
this.nextLocal = acc.getFirstAfter();
this.description = " based on ParameterAccessor " + acc;
this.forMethod = acc.forMethod();
for (SSAValue val : acc.all()) {
setAllocation(val, null);
}
}
/*
public SSAValueManager(final MethodReference forMethod) {
this (new
//this.nextLocal = nextLocal;
this.description = " stand alone";
this.forMethod = forMethod;
}*/
/**
* Register a variable _after_ allocation.
*
* <p>The proper way to add an allocation is to get a Variable using {@link #getUnallocated}. Then
* assign it a value. And at last call this function.
*
* <p>You can however directly call the function if the type has not been seen before.
*
* @param value an unallocated SSA-Variable to assign the allocation to
* @param setBy The instruction that set the value (optional)
* @throws IllegalStateException if you set more than one allocation for that type (TODO better
* check!)
* @throws IllegalArgumentException if type is null or ssaValue is zero or negative
*/
public void setAllocation(SSAValue value, SSAInstruction setBy) {
if (value == null) {
throw new IllegalArgumentException("The SSA-Variable may not be null");
}
if (seenTypes.containsKey(value.key)) {
for (Managed<? extends SSAValue> param : seenTypes.get(value.key)) {
if (param.status == ValueStatus.UNALLOCATED) {
// XXX: Allow more?
assert param.value.getType().equals(value.getType()) : "Inequal types";
if ((param.value.getNumber() + 1) > nextLocal) {
nextLocal = param.value.getNumber() + 1;
}
debug("reSetting SSA {} to allocated", value);
param.status = ValueStatus.ALLOCATED;
param.setInScope = currentScope;
param.setBy = setBy;
return;
} else {
continue;
}
}
{ // DEBUG
System.out.println("Keys for " + value + ':');
for (Managed<? extends SSAValue> param : seenTypes.get(value.key)) {
System.out.println("\tKey " + param.key + "\t=>" + param.status);
}
} // */
throw new IllegalStateException(
"The parameter " + value + " using Key " + value.key + " has already been allocated");
} else {
info("New variable in management: {}", value);
final Managed<SSAValue> param = new Managed<>(value, value.key);
param.status = ValueStatus.ALLOCATED;
param.setInScope = currentScope;
param.setBy = setBy;
final List<Managed<? extends SSAValue>> aParam = new ArrayList<>();
aParam.add(param);
seenTypes.put(value.key, aParam);
}
}
/**
* Register a Phi-Instruction _after_ added to the model.
*
* @param value the number the SSA-Instruction assigns to
* @param setBy the Phi-Instruction itself - may be null
* @throws IllegalArgumentException if you assign to a number requested using {@link #getFree} but
* types mismatch.
* @throws IllegalStateException if you forgot to close some Phis
*/
public void setPhi(final SSAValue value, SSAInstruction setBy) {
if (value == null) {
throw new IllegalArgumentException("The SSA-Variable may not be null.");
}
boolean didPhi = false;
if (seenTypes.containsKey(value.key)) {
for (Managed<? extends SSAValue> param : seenTypes.get(value.key)) {
if ((param.status == ValueStatus.FREE)
|| (param.status == ValueStatus.FREE_INVALIDATED)
|| (param.status == ValueStatus.FREE_CLOSED)) {
// XXX: Allow more?
assert param.value.getType().equals(value.getType()) : "Unequal types";
if (param.value.getNumber() != value.getNumber()) {
if ((param.status == ValueStatus.FREE) && (param.setInScope == currentScope)) {
param.status = ValueStatus.FREE_CLOSED;
}
continue;
}
if (param.status == ValueStatus.FREE) {
param.status = ValueStatus.ALLOCATED;
} else if (param.status == ValueStatus.FREE_INVALIDATED) {
param.status = ValueStatus.INVALIDATED;
} else if (param.status == ValueStatus.FREE_CLOSED) {
param.status = ValueStatus.CLOSED;
}
param.setInScope = currentScope;
param.setBy = setBy;
info("Setting SSA {} to phi! now {}", value, param.status);
didPhi = true;
} else if (param.setInScope == currentScope) {
if (param.status == ValueStatus.INVALIDATED) {
info("Closing SSA Value {} in scope {}", param.value, param.setInScope);
param.status = ValueStatus.CLOSED;
} else if (param.status == ValueStatus.FREE_INVALIDATED) { // TODO: FREE CLOSED
info("Closing free SSA Value {} in scope {}", param.value, param.setInScope);
param.status = ValueStatus.FREE_CLOSED;
}
} else if (param.setInScope < currentScope) {
// param.status = ValueStatus.INVALIDATED;
} else {
// TODO: NO! I JUST WANTED TO ADD THEM! *grrr*
// error("MISSING PHI for "
// throw new IllegalStateException("You forgot Phis in subordinate blocks");
}
}
assert didPhi;
return;
} else {
throw new IllegalStateException("This should not be reached!");
}
}
/**
* Returns and registers a free SSA-Number to a Type.
*
* <p>You have to set the type using a Phi-Instruction. Also you don't have to add that
* instruction immediately it is required that it is added before the Model gets finished.
*
* <p>You can request the List of unmet Phi-Instructions by using XXX
*
* @return an unused SSA-Number
* @throws IllegalArgumentException if type is null
*/
public SSAValue getFree(TypeReference type, VariableKey key) {
if (type == null) {
throw new IllegalArgumentException("The argument type may not be null");
}
if (key == null) {
throw new IllegalArgumentException("The argument key may not be null");
}
final SSAValue var = new SSAValue(nextLocal++, type, this.forMethod, key);
final Managed<SSAValue> param = new Managed<>(var, key);
param.status = ValueStatus.FREE;
param.setInScope = currentScope;
if (seenTypes.containsKey(key)) {
seenTypes.get(key).add(param);
} else {
List<Managed<? extends SSAValue>> aParam = new ArrayList<>();
aParam.add(param);
seenTypes.put(key, aParam);
}
debug("Returning as Free SSA: {}", param);
return var;
}
/**
* Get an unused number to assign to.
*
* <p>There may only be one unallocated value for each type at a time. XXX: Really?
*
* @return SSA-Variable
* @throws IllegalStateException if there is already an unallocated variable of that type
* @throws IllegalArgumentException if type is null
*/
public SSAValue getUnallocated(TypeReference type, VariableKey key) {
if (type == null) {
throw new IllegalArgumentException("The argument type may not be null");
}
if (key == null) {
throw new IllegalArgumentException("The argument key may not be null");
}
if (seenTypes.containsKey(key)) {
for (Managed<? extends SSAValue> p : seenTypes.get(key)) {
if (p.status == ValueStatus.UNALLOCATED) {
throw new IllegalStateException(
"There may be only one unallocated instance to a kay (" + key + ") at a time");
}
}
}
final SSAValue var = new SSAValue(nextLocal++, type, this.forMethod, key);
final Managed<SSAValue> param = new Managed<>(var, key);
param.status = ValueStatus.UNALLOCATED;
param.setInScope = currentScope;
if (seenTypes.containsKey(key)) {
seenTypes.get(key).add(param);
} else {
List<Managed<? extends SSAValue>> aParam = new ArrayList<>();
aParam.add(param);
seenTypes.put(key, aParam);
}
debug("Returning as Unallocated SSA: {}", param);
return var;
}
/**
* Retrieve a SSA-Value that is not under management.
*
* <p>Use instead of 'nextLocal++', else SSA-Values will clash!
*
* @return SSA-Variable
*/
public SSAValue getUnmanaged(TypeReference type, VariableKey key) {
final SSAValue var = new SSAValue(nextLocal++, type, this.forMethod, key);
this.unmanaged.add(var);
return var;
}
public SSAValue getUnmanaged(TypeReference type, String name) {
return getUnmanaged(type, new NamedKey(type.getName(), name));
}
/**
* Retrieve the SSA-Number that is valid for a type in the current scope.
*
* <p>Either that number origins from an allocation or a PhiInstruction (to be).
*
* @return a ssa number
* @throws IllegalStateException if no number is assignable
* @throws IllegalArgumentException if type was not seen before or is null
*/
public SSAValue getCurrent(VariableKey key) {
if (key == null) {
throw new IllegalArgumentException("The argument key may not be null");
}
Managed<? extends SSAValue> candidate = null;
if (seenTypes.containsKey(key)) {
for (Managed<? extends SSAValue> param : seenTypes.get(key)) {
if ((param.status == ValueStatus.FREE) || (param.status == ValueStatus.ALLOCATED)) {
// assert (param.value.getType().equals(type)) : "Unequal types";
if (param.setInScope > currentScope) {
debug("SSA Value {} is out of scope {}", param, currentScope);
continue;
} else if (param.setInScope == currentScope) {
debug("Returning SSA Value {} is {}", param.value, param.status);
return param.value;
} else {
if ((candidate == null) || (param.setInScope > candidate.setInScope)) {
candidate = param;
}
}
} else {
debug("SSA Value {} is {}", param, param.status);
}
}
} else {
throw new IllegalArgumentException(
"Key " + key + " has never been seen before! Known keys are " + seenTypes.keySet());
}
if (candidate != null) {
debug("Returning inherited (from {}) SSA Value {}", candidate.setInScope, candidate);
return candidate.value;
} else {
throw new IllegalStateException("No suitable candidate has been found for Key " + key);
}
}
/**
* Retrieve the SSA-Number that is valid for a type in the super-ordinate scope.
*
* <p>Either that number origins from an allocation or a PhiInstruction (to be).
*
* @return a ssa number
* @throws IllegalStateException if no number is assignable
* @throws IllegalArgumentException if type was not seen before or is null
*/
public SSAValue getSuper(VariableKey key) {
if (key == null) {
throw new IllegalArgumentException("The argument key may not be null");
}
final SSAValue cand;
currentScope--;
assert (currentScope >= 0);
cand = getCurrent(key);
currentScope++;
return cand;
}
/**
* Returns all "free" and "allocated" variables and the invalid ones in a sub-scope.
*
* <p>This is a suggestion which variables to considder as parameter to a Phi-Function.
*
* @throws IllegalArgumentException if type was not seen before or is null
*/
public List<SSAValue> getAllForPhi(VariableKey key) {
if (key == null) {
throw new IllegalArgumentException("The argument key may not be null");
}
List<SSAValue> ret = new ArrayList<>();
if (seenTypes.containsKey(key)) {
for (Managed<? extends SSAValue> param : seenTypes.get(key)) {
if ((param.status == ValueStatus.FREE) || (param.status == ValueStatus.ALLOCATED)) {
// assert (param.type.equals(type)) : "Unequal types";
ret.add(param.value);
} else if ((param.status == ValueStatus.INVALIDATED) && param.setInScope > currentScope) {
ret.add(param.value);
}
}
} else {
throw new IllegalArgumentException("Key " + key + " has never been seen before!");
}
return ret;
}
/**
* Return if the type is managed by this class.
*
* @param withSuper when true return true if a managed key may be cast to type, when false type
* has to match exactly
* @param key the type in question
* @throws IllegalArgumentException if key is null
*/
public boolean isSeen(VariableKey key, boolean withSuper) {
if (key == null) {
throw new IllegalArgumentException("The argument key may not be null");
}
if (withSuper) {
return seenTypes.containsKey(key);
} else {
if (seenTypes.containsKey(key)) {
/* if (seenTypes.get(key).get(0).type.equals(type)) { // TODO: Rethink
return true;
}*/
}
return false;
}
}
/**
* Return if the type is managed by this class.
*
* <p>This variant respects super-types. Use isSeen(VariableKey, boolean) with a setting for
* withSuper of false to enforce exact matches.
*
* @return if the type is managed by this class.
*/
public boolean isSeen(VariableKey key) {
return isSeen(key, true);
}
/**
* Returns if an instance for that type needs to be allocated.
*
* <p>However this function does not respect weather a PhiInstruction is needed.
*
* @throws IllegalArgumentException if type is null
*/
public boolean needsAllocation(VariableKey key) {
if (key == null) {
throw new IllegalArgumentException("The argument key may not be null");
}
if (seenTypes.containsKey(key)) {
if (seenTypes.get(key).size() > 1) { // TODO INCORRECT may all be UNALLOCATED
return false;
} else {
return (seenTypes.get(key).get(0).status == ValueStatus.UNALLOCATED);
}
} else {
return true;
}
}
/**
* Returns if a PhiInstruction (still) has to be added.
*
* <p>This is true if the Value has changed in a deeper scope, has been invalidated or requested
* using getFree
*
* @throws IllegalArgumentException if type is null or has not been seen before
*/
public boolean needsPhi(VariableKey key) {
if (key == null) {
throw new IllegalArgumentException("The argument key may not be null");
}
boolean seenLive = false;
if (seenTypes.containsKey(key)) {
for (Managed<? extends SSAValue> param : seenTypes.get(key)) { // TODO: Check all these
if ((param.status == ValueStatus.FREE)) { // TODO: What about scopes
return true;
}
if (param.status == ValueStatus.ALLOCATED) {
if (seenLive) {
return true;
} else {
seenLive = true;
}
}
}
} else {
throw new IllegalArgumentException("Key " + key + " has never been seen before!");
}
throw new IllegalStateException("No suitable candidate has been found"); // TODO WRONG text
}
/**
* Marks all known instances of VariableKey invalid.
*
* <p>A call to this method is useful before a call to setAllocation. This methods sets all known
* instances to invalid, setAllocation will assign the new "current" instance to use.
*
* @param key Which variables to invalidate.
* @throws IllegalArgumentException if type was not seen before or is null
*/
public void invalidate(VariableKey key) {
if (key == null) {
throw new IllegalArgumentException("The argument key may not be null");
}
if (seenTypes.containsKey(key)) {
for (Managed<? extends SSAValue> param : seenTypes.get(key)) {
if ((param.status != ValueStatus.CLOSED)
&& (param.status != ValueStatus.FREE_CLOSED)
&& (param.status != ValueStatus.FREE_INVALIDATED)
&& (param.status != ValueStatus.INVALIDATED)
&& (param.setInScope == currentScope)) {
// assert(param.type.equals(type));
if (param.status == ValueStatus.FREE) {
param.status = ValueStatus.FREE_INVALIDATED;
} else {
param.status = ValueStatus.INVALIDATED;
}
info("Invalidated SSA {} for key {}", param, key);
}
}
}
}
/**
* Enter a subordinate scope.
*
* <p>Call this whenever a new code block starts i.e. when ever you would have to put a left
* curly-bracket in the java code.
*
* <p>This function influences the placement of Phi-Functions. Thus if you don't change values you
* don't have to call it.
*
* @param doesLoop set to true if the scope is introduced for a loop
* @return The depth
*/
public int scopeDown(boolean doesLoop) { // TODO: Rename scopeInto
// TODO: Delete Parameters if there already was scopeNo
currentScope++;
return currentScope;
}
/**
* Leave a subordinate scope.
*
* <p>All changes are marked invalid thus to be expected to be collected by a PhiInstruction.
*
* @throws IllegalStateException if already at top level
*/
public int scopeUp() { // TODO: Rename scopeOut
// First: Invalidate changed values
for (List<Managed<? extends SSAValue>> plist : seenTypes.values()) {
for (Managed<? extends SSAValue> param : plist) {
if (param.setInScope == currentScope) {
invalidate(param.value.key);
} else if ((param.setInScope > currentScope)
&& ((param.status != ValueStatus.INVALIDATED)
&& (param.status != ValueStatus.CLOSED))) {
throw new IllegalStateException(
"A parameter was in wrong status when leaving a sub-subordinate scope: "
+ param
+ " should have been invalidated or closed by an other scope.");
}
}
}
currentScope--;
return currentScope;
}
@Override
public String toString() {
return "<AndroidModelParameterManager " + this.description + '>';
}
/**
* Create new SSAValue with UniqueKey and Exception-Type.
*
* <p>The generated SSAValue will be unmanaged. It is mainly useful for SSAInvokeInstructions.
*
* @return new unmanaged SSAValue with Exception-Type
*/
public SSAValue getException() {
SSAValue exc =
new SSAValue(
nextLocal++,
TypeReference.JavaLangException,
this.forMethod,
"exception_" + nextLocal); // UniqueKey
this.unmanaged.add(exc);
return exc;
}
/** Collect the variable-names of all known variables. */
public Map<Integer, Atom> makeLocalNames() {
final Map<Integer, Atom> names = new HashMap<>();
final Map<VariableKey, Integer> suffix = new HashMap<>();
int currentSuffix = 0;
for (final List<Managed<? extends SSAValue>> manageds : seenTypes.values()) {
for (final Managed<? extends SSAValue> managed : manageds) {
final SSAValue val = managed.value;
final String name = val.getVariableName();
if (name != null) {
final Atom nameAtom = Atom.findOrCreateAsciiAtom(name);
names.put(val.getNumber(), nameAtom);
} else if (AUTOMAKE_NAMES) {
@SuppressWarnings("NonConstantStringShouldBeStringBuffer")
String autoName = val.getType().getName().toString();
if (autoName.contains("/")) {
autoName = autoName.substring(autoName.lastIndexOf('/') + 1);
}
if (autoName.contains("$")) {
autoName = autoName.substring(autoName.lastIndexOf('$') + 1);
}
autoName = autoName.replace("[", "Ar");
final int mySuffix;
if (suffix.containsKey(val.key)) {
mySuffix = suffix.get(val.key);
} else {
mySuffix = currentSuffix++;
suffix.put(val.key, mySuffix);
}
autoName = 'm' + autoName + '_' + mySuffix;
final Atom nameAtom = Atom.findOrCreateAsciiAtom(autoName);
names.put(val.getNumber(), nameAtom);
}
}
}
for (final SSAValue val : this.unmanaged) {
final String name = val.getVariableName();
if (name != null) {
final Atom nameAtom = Atom.findOrCreateAsciiAtom(name);
names.put(val.getNumber(), nameAtom);
} else if (AUTOMAKE_NAMES) {
@SuppressWarnings("NonConstantStringShouldBeStringBuffer")
String autoName = val.getType().getName().toString();
if (autoName.contains("/")) {
autoName = autoName.substring(autoName.lastIndexOf('/') + 1);
}
if (autoName.contains("$")) {
autoName = autoName.substring(autoName.lastIndexOf('$') + 1);
}
autoName = autoName.replace("[", "Ar");
final int mySuffix;
if (suffix.containsKey(val.key)) {
mySuffix = suffix.get(val.key);
} else {
mySuffix = currentSuffix++;
suffix.put(val.key, mySuffix);
}
autoName = 'm' + autoName + '_' + mySuffix;
final Atom nameAtom = Atom.findOrCreateAsciiAtom(autoName);
names.put(val.getNumber(), nameAtom);
}
}
return names;
}
private static void debug(String s, Object... args) {
if (DEBUG) {
System.err.printf(s, args);
}
}
private static void info(String s, Object... args) {
if (DEBUG) {
System.err.printf(s, args);
}
}
}
| 25,875
| 33.137203
| 100
|
java
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.