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/ssa/SSACache.java
/* * Copyright (c) 2002 - 2006 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package com.ibm.wala.ssa; import com.ibm.wala.classLoader.IMethod; import com.ibm.wala.ipa.callgraph.Context; import com.ibm.wala.ipa.callgraph.impl.Everywhere; /** * A mapping from IMethod -&gt; SSAOptions -&gt; SoftReference -&gt; Something * * <p>This doesn't work very well ... GCs don't do such a great job with SoftReferences ... revamp * it. */ public class SSACache { /** used for debugging */ private static final boolean DISABLE = false; /** The factory that actually creates new IR objects */ private final IRFactory<IMethod> factory; /** A cache of SSA IRs */ private final IAuxiliaryCache irCache; /** A cache of DefUse information */ private final IAuxiliaryCache duCache; /** @param factory a factory for creating IRs */ public SSACache(IRFactory<IMethod> factory, IAuxiliaryCache irCache, IAuxiliaryCache duCache) { this.factory = factory; this.irCache = irCache; this.duCache = duCache; } /** * @param m a "normal" (bytecode-based) method * @param options options governing ssa construction * @return an IR for m, built according to the specified options. null if m is abstract or native. * @throws IllegalArgumentException if m is null */ public synchronized IR findOrCreateIR(final IMethod m, Context c, final SSAOptions options) { if (m == null) { throw new IllegalArgumentException("m is null"); } if (m.isAbstract() || m.isNative()) { return null; } if (factory.contextIsIrrelevant(m)) { c = Everywhere.EVERYWHERE; } if (DISABLE) { return factory.makeIR(m, c, options); } IR ir = (IR) irCache.find(m, c, options); if (ir == null) { ir = factory.makeIR(m, c, options); irCache.cache(m, c, options, ir); } return ir; } /** * @param m a method * @param options options governing ssa construction * @return DefUse information for m, built according to the specified options. null if unavailable * @throws IllegalArgumentException if m is null */ public synchronized DefUse findOrCreateDU(IMethod m, Context c, SSAOptions options) { if (m == null) { throw new IllegalArgumentException("m is null"); } if (m.isAbstract() || m.isNative()) { return null; } if (factory.contextIsIrrelevant(m)) { c = Everywhere.EVERYWHERE; } DefUse du = (DefUse) duCache.find(m, c, options); if (du == null) { IR ir = findOrCreateIR(m, c, options); du = new DefUse(ir); duCache.cache(m, c, options, du); } return du; } /** * @return {@link DefUse} information for m, built according to the specified options. null if * unavailable * @throws IllegalArgumentException if ir is null */ public synchronized DefUse findOrCreateDU(IR ir, Context C) { if (ir == null) { throw new IllegalArgumentException("ir is null"); } DefUse du = (DefUse) duCache.find(ir.getMethod(), C, ir.getOptions()); if (du == null) { du = new DefUse(ir); duCache.cache(ir.getMethod(), C, ir.getOptions(), du); } return du; } /** The existence of this is unfortunate. */ public void wipe() { irCache.wipe(); duCache.wipe(); } /** Invalidate the cached IR for a &lt;method,context&gt; pair */ public void invalidateIR(IMethod method, Context c) { irCache.invalidate(method, c); } /** Invalidate the cached {@link DefUse} for a &lt;method,context&gt; pair */ public void invalidateDU(IMethod method, Context c) { duCache.invalidate(method, c); } /** Invalidate all cached information for a &lt;method,context&gt; pair */ public void invalidate(IMethod method, Context c) { invalidateIR(method, c); invalidateDU(method, c); } }
4,137
28.557143
100
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/ssa/SSACheckCastInstruction.java
/* * Copyright (c) 2002 - 2006 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package com.ibm.wala.ssa; import com.ibm.wala.types.TypeReference; /** * A checkcast (dynamic type test) instruction. This instruction produces a new value number (like * an assignment) if the check succeeds. * * <p>Note that this instruction generalizes the meaning of checkcast in Java since it supports * multiple types for which to check. The meaning is that the case succeeds if the object is of any * of the desired types. */ public abstract class SSACheckCastInstruction extends SSAInstruction { /** A new value number def'fed by this instruction when the type check succeeds. */ private final int result; /** The value being checked by this instruction */ private final int val; /** * The types for which this instruction checks; the assignment succeeds if the val is a subtype of * one of these types */ private final TypeReference[] declaredResultTypes; /** whether the type test throws an exception */ private final boolean isPEI; /** * @param result A new value number def'fed by this instruction when the type check succeeds. * @param val The value being checked by this instruction * @param types The types which this instruction checks */ protected SSACheckCastInstruction( int iindex, int result, int val, TypeReference[] types, boolean isPEI) { super(iindex); assert val != -1; this.result = result; this.val = val; this.declaredResultTypes = types; this.isPEI = isPEI; } @Override public SSAInstruction copyForSSA(SSAInstructionFactory insts, int[] defs, int[] uses) { if (defs != null && defs.length == 0) { throw new IllegalArgumentException("(defs != null) and (defs.length == 0)"); } if (uses != null && uses.length == 0) { throw new IllegalArgumentException("(uses != null) and (uses.length == 0)"); } return insts.CheckCastInstruction( iIndex(), defs == null ? result : defs[0], uses == null ? val : uses[0], declaredResultTypes, isPEI); } @Override public String toString(SymbolTable symbolTable) { final StringBuilder v = new StringBuilder(getValueString(symbolTable, result)).append(" = checkcast"); for (TypeReference t : declaredResultTypes) { v.append(' ').append(t); } v.append(getValueString(symbolTable, val)); return v.toString(); } @Override public void visit(IVisitor v) { if (v == null) { throw new IllegalArgumentException("v is null"); } v.visitCheckCast(this); } @Override public boolean hasDef() { return true; } /** @return A new value number def'fed by this instruction when the type check succeeds. */ @Override public int getDef() { return result; } @Override public int getDef(int i) { assert i == 0; return result; } /** @see com.ibm.wala.ssa.SSAInstruction#getNumberOfUses() */ @Override public int getNumberOfDefs() { return 1; } @Override public int getNumberOfUses() { return 1; } @Override public int getUse(int j) { assert j == 0; return val; } /** * @deprecated the system now supports multiple types, so this accessor will not work for all * languages. */ @Deprecated public TypeReference getDeclaredResultType() { assert declaredResultTypes.length == 1; return declaredResultTypes[0]; } public TypeReference[] getDeclaredResultTypes() { return declaredResultTypes; } public int getResult() { return result; } public int getVal() { return val; } @Override public int hashCode() { return result * 7529 + val; } @Override public boolean isPEI() { return isPEI; } @Override public boolean isFallThrough() { return true; } @Override public String toString() { final StringBuilder s = new StringBuilder(super.toString()); for (TypeReference t : declaredResultTypes) { s.append(' ').append(t); } return s.toString(); } }
4,374
24.735294
100
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/ssa/SSAComparisonInstruction.java
/* * Copyright (c) 2002 - 2006 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package com.ibm.wala.ssa; import com.ibm.wala.shrike.shrikeBT.IComparisonInstruction; /** SSA Instruction for comparisons between floats, longs and doubles */ public class SSAComparisonInstruction extends SSAInstruction { private final int result; private final int val1; private final int val2; private final IComparisonInstruction.Operator operator; /** */ public SSAComparisonInstruction( int iindex, IComparisonInstruction.Operator operator, int result, int val1, int val2) { super(iindex); this.operator = operator; this.result = result; this.val1 = val1; this.val2 = val2; } @Override public SSAInstruction copyForSSA(SSAInstructionFactory insts, int[] defs, int[] uses) throws IllegalArgumentException { if (uses != null && uses.length != 2) { throw new IllegalArgumentException("expected 2 uses or null, but got " + uses.length); } return insts.ComparisonInstruction( iIndex(), operator, defs == null || defs.length == 0 ? result : defs[0], uses == null ? val1 : uses[0], uses == null ? val2 : uses[1]); } @Override public String toString(SymbolTable symbolTable) { return getValueString(symbolTable, result) + " = compare " + getValueString(symbolTable, val1) + ',' + getValueString(symbolTable, val2) + " opcode=" + operator; } @Override public void visit(IVisitor v) throws NullPointerException { v.visitComparison(this); } /** @see com.ibm.wala.ssa.SSAInstruction#getDef() */ @Override public boolean hasDef() { return true; } @Override public int getDef() { return result; } @Override public int getDef(int i) { assert i == 0; return result; } /** @see com.ibm.wala.ssa.SSAInstruction#getNumberOfUses() */ @Override public int getNumberOfDefs() { return 1; } @Override public int getNumberOfUses() { return 2; } @Override public int getUse(int j) { assert j <= 1; return (j == 0) ? val1 : val2; } @Override public int hashCode() { return 6311 * result ^ 2371 * val1 + val2; } @Override public boolean isFallThrough() { return true; } /** @return Returns the opcode. */ public IComparisonInstruction.Operator getOperator() { return operator; } }
2,731
22.964912
93
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/ssa/SSAConditionalBranchInstruction.java
/* * Copyright (c) 2002 - 2006 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package com.ibm.wala.ssa; import com.ibm.wala.shrike.shrikeBT.IConditionalBranchInstruction; import com.ibm.wala.shrike.shrikeBT.IConditionalBranchInstruction.IOperator; import com.ibm.wala.types.TypeReference; /** A conditional branch instruction, which tests two values according to some {@link IOperator}. */ public class SSAConditionalBranchInstruction extends SSAInstruction { private final IConditionalBranchInstruction.IOperator operator; private final int val1; private final int val2; private final TypeReference type; private final int target; public SSAConditionalBranchInstruction( int iindex, IConditionalBranchInstruction.IOperator operator, TypeReference type, int val1, int val2, int target) throws IllegalArgumentException { super(iindex); this.target = target; this.operator = operator; this.val1 = val1; this.val2 = val2; this.type = type; if (val1 <= 0) { throw new IllegalArgumentException("Invalid val1: " + val1); } if (val2 <= 0) { throw new IllegalArgumentException("Invalid val2: " + val2); } } public int getTarget() { return target; } @Override public SSAInstruction copyForSSA(SSAInstructionFactory insts, int[] defs, int[] uses) throws IllegalArgumentException { if (uses != null && uses.length < 2) { throw new IllegalArgumentException("(uses != null) and (uses.length < 2)"); } return insts.ConditionalBranchInstruction( iIndex(), operator, type, uses == null ? val1 : uses[0], uses == null ? val2 : uses[1], target); } public IConditionalBranchInstruction.IOperator getOperator() { return operator; } @Override public String toString(SymbolTable symbolTable) { return "conditional branch(" + operator + ", to iindex=" + target + ") " + getValueString(symbolTable, val1) + ',' + getValueString(symbolTable, val2); } @Override public void visit(IVisitor v) { if (v == null) { throw new IllegalArgumentException("v is null"); } v.visitConditionalBranch(this); } @Override public int getNumberOfUses() { return 2; } @Override public int getUse(int j) { assert j <= 1; return (j == 0) ? val1 : val2; } public TypeReference getType() { return type; } public boolean isObjectComparison() { return type.isReferenceType(); } public boolean isIntegerComparison() { return type == TypeReference.Int; } @Override public int hashCode() { return 7151 * val1 + val2; } @Override public boolean isFallThrough() { return true; } }
3,101
23.425197
100
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/ssa/SSAConversionInstruction.java
/* * Copyright (c) 2002 - 2006 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package com.ibm.wala.ssa; import com.ibm.wala.types.TypeReference; /** An instruction which converts a value of one primitive type into another primitive type. */ public abstract class SSAConversionInstruction extends SSAInstruction { private final int result; private final int val; private final TypeReference fromType; private final TypeReference toType; protected SSAConversionInstruction( int iindex, int result, int val, TypeReference fromType, TypeReference toType) { super(iindex); this.result = result; this.val = val; this.fromType = fromType; this.toType = toType; } @Override public String toString(SymbolTable symbolTable) { return getValueString(symbolTable, result) + " = conversion(" + toType.getName() + ") " + getValueString(symbolTable, val); } @Override public void visit(IVisitor v) throws NullPointerException { v.visitConversion(this); } /** @see com.ibm.wala.ssa.SSAInstruction#getDef() */ @Override public boolean hasDef() { return true; } @Override public int getDef() { return result; } @Override public int getDef(int i) { assert i == 0; return result; } @Override public int getNumberOfUses() { return 1; } @Override public int getNumberOfDefs() { return 1; } public TypeReference getToType() { return toType; } public TypeReference getFromType() { return fromType; } @Override public int getUse(int j) { assert j == 0; return val; } @Override public int hashCode() { return 6311 * result ^ val; } @Override public boolean isFallThrough() { return true; } }
2,076
19.979798
95
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/ssa/SSAFieldAccessInstruction.java
/* * Copyright (c) 2002 - 2006 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package com.ibm.wala.ssa; import com.ibm.wala.types.FieldReference; import com.ibm.wala.types.TypeReference; /** Abstract base class for {@link SSAGetInstruction} and {@link SSAPutInstruction}. */ public abstract class SSAFieldAccessInstruction extends SSAInstruction { private final FieldReference field; private final int ref; protected SSAFieldAccessInstruction(int iindex, FieldReference field, int ref) throws IllegalArgumentException { super(iindex); this.field = field; this.ref = ref; if (field == null) { throw new IllegalArgumentException("field cannot be null"); } } public TypeReference getDeclaredFieldType() { return field.getFieldType(); } public FieldReference getDeclaredField() { return field; } public int getRef() { return ref; } public boolean isStatic() { return ref == -1; } @Override public boolean isPEI() { return !isStatic(); } }
1,325
23.109091
87
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/ssa/SSAGetCaughtExceptionInstruction.java
/* * Copyright (c) 2002 - 2006 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package com.ibm.wala.ssa; /** * A "catch" instruction, inserted at the head of a catch block, which assigns a pending exception * object to a local variable. * * <p>In SSA {@link IR}s, these instructions do <em>not</em> appear in the normal instruction array * returned by IR.getInstructions(); instead these instructions live in {@link ISSABasicBlock}. */ public class SSAGetCaughtExceptionInstruction extends SSAInstruction { private final int exceptionValueNumber; private final int bbNumber; public SSAGetCaughtExceptionInstruction(int iindex, int bbNumber, int exceptionValueNumber) { super(iindex); this.exceptionValueNumber = exceptionValueNumber; this.bbNumber = bbNumber; } @Override public SSAInstruction copyForSSA(SSAInstructionFactory insts, int[] defs, int[] uses) { assert defs == null || defs.length == 1; return insts.GetCaughtExceptionInstruction( iIndex(), bbNumber, defs == null ? exceptionValueNumber : defs[0]); } @Override public String toString(SymbolTable symbolTable) { return getValueString(symbolTable, exceptionValueNumber) + " = getCaughtException "; } @Override public void visit(IVisitor v) { if (v == null) { throw new IllegalArgumentException("v is null"); } v.visitGetCaughtException(this); } /** * Returns the result. * * @return int */ public int getException() { return exceptionValueNumber; } /** @see com.ibm.wala.ssa.SSAInstruction#getDef() */ @Override public boolean hasDef() { return true; } @Override public int getDef() { return exceptionValueNumber; } @Override public int getDef(int i) { assert i == 0; return exceptionValueNumber; } @Override public int getNumberOfDefs() { return 1; } public int getBasicBlockNumber() { return bbNumber; } @Override public int hashCode() { return 2243 * exceptionValueNumber; } @Override public boolean isFallThrough() { return true; } }
2,388
23.885417
99
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/ssa/SSAGetInstruction.java
/* * Copyright (c) 2002 - 2006 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package com.ibm.wala.ssa; import com.ibm.wala.types.FieldReference; /** SSA instruction that reads a field (i.e. getstatic or getfield). */ public abstract class SSAGetInstruction extends SSAFieldAccessInstruction { private final int result; protected SSAGetInstruction(int iindex, int result, int ref, FieldReference field) { super(iindex, field, ref); this.result = result; } protected SSAGetInstruction(int iindex, int result, FieldReference field) { super(iindex, field, -1); this.result = result; } @Override public SSAInstruction copyForSSA(SSAInstructionFactory insts, int[] defs, int[] uses) { if (isStatic()) return insts.GetInstruction( iIndex(), defs == null || defs.length == 0 ? result : defs[0], getDeclaredField()); else return insts.GetInstruction( iIndex(), defs == null || defs.length == 0 ? result : defs[0], uses == null ? getRef() : uses[0], getDeclaredField()); } @Override public String toString(SymbolTable symbolTable) { if (isStatic()) { return getValueString(symbolTable, result) + " = getstatic " + getDeclaredField(); } else { return getValueString(symbolTable, result) + " = getfield " + getDeclaredField() + ' ' + getValueString(symbolTable, getRef()); } } /** @see com.ibm.wala.ssa.SSAInstruction#visit(IVisitor) */ @Override public void visit(IVisitor v) throws NullPointerException { v.visitGet(this); } /** @see com.ibm.wala.ssa.SSAInstruction#getDef() */ @Override public boolean hasDef() { return true; } @Override public int getDef() { return result; } @Override public int getDef(int i) { assert i == 0; return result; } /** @see com.ibm.wala.ssa.SSAInstruction#getNumberOfUses() */ @Override public int getNumberOfDefs() { return 1; } @Override public int getNumberOfUses() { return isStatic() ? 0 : 1; } /** @see com.ibm.wala.ssa.SSAInstruction#getUse(int) */ @Override public int getUse(int j) { assert j == 0 && getRef() != -1; return getRef(); } @Override public int hashCode() { return result * 2371 + 6521; } /** @see com.ibm.wala.ssa.SSAInstruction#isFallThrough() */ @Override public boolean isFallThrough() { return true; } }
2,746
24.435185
93
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/ssa/SSAGotoInstruction.java
/* * Copyright (c) 2002 - 2006 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package com.ibm.wala.ssa; /** Unconditional branch instruction for SSA form. */ public class SSAGotoInstruction extends SSAInstruction { private final int target; public SSAGotoInstruction(int iindex, int target) { super(iindex); this.target = target; } /** * getTarget returns the IIndex for the Goto-target. Not to be confused with the array-index in * InducedCFG.getStatements() */ public int getTarget() { return this.target; } @Override public SSAInstruction copyForSSA(SSAInstructionFactory insts, int[] defs, int[] uses) { return insts.GotoInstruction(iIndex(), target); } @Override public String toString(SymbolTable symbolTable) { return "goto (from iindex= " + this.iIndex() + " to iindex = " + this.target + ')'; } @Override public void visit(IVisitor v) { if (v == null) { throw new IllegalArgumentException("v is null"); } v.visitGoto(this); } @Override public int hashCode() { return 1409 + 17 * target; } @Override public boolean isFallThrough() { return false; } }
1,461
24.206897
97
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/ssa/SSAIndirectionData.java
/* * Copyright (c) 2007 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package com.ibm.wala.ssa; import java.util.Collection; /** * A mapping that tells, for a given instruction s, what "names" does s def and use * <em>indirectly</em>. * * <p>For example, an {@link SSALoadIndirectInstruction} takes as an argument a pointer value. This * map tells which locals that pointer may alias. * * <p>So if we have * * <p>Example A: * * <pre> * v2 = SSAAddressOf v1; * v7 = #1; * v3 = SSALoadIndirect v2; (1) * </pre> * * Then this map will tell us that instruction (1) indirectly uses whichever source-level entity (in * the source or bytecode) v1 represents. * * <p>(Don't be confused by AddressOf v1 .. we're not actually taking the address of v1 ... we're * taking the address of some source level entity (like a local variable in source code or bytecode) * for which v1 is just an SSA name) * * <p>As a more complex example, when we have lexical scoping, we can have the following IR * generated, which passes a local by reference: * * <p>Example B: {@code foo: v3 = AddressOf v2; bar(v3) (1) bar(v1): StoreIndirect v1, #7.} * * <p>In this case, the instruction (1) potentially defs the locals aliased by v2. The lexical * scoping support could/should use this information to rebuild SSA accounting for the fact that (1) * defs v2. */ public interface SSAIndirectionData<T extends SSAIndirectionData.Name> { /** * A Name is a mock interface introduced just for strong typing. A Name represents some semantic * entity in the program representation (e.g. a local variable in the source code or a local * number in the bytecode) */ interface Name {} /** * Returns the set of "source" level names (e.g. local variables in bytecode or source code) for * which this map holds information. */ Collection<T> getNames(); /** * For the instruction at the given index, and a source-level name, return the SSA value number * which represents this instruction's def of that name. * * <p>For example, in Example B in header comment above, suppose v2 referred to a "source"-entity * called "Local1". Since instruction (1) (call to bar) defs "Local1", we introduce in this table * a new SSA value number, say v7, which represents the value of "Local1" immediately after this * instruction. */ int getDef(int instructionIndex, T name); /** * Record the fact that a particular instruction defs a particular SSA value number (newDef), * representing the value of a "source" entity "name". * * @see #getDef */ void setDef(int instructionIndex, T name, int newDef); /** * For the instruction at the given index, and a source-level name, return the SSA value number * which represents this instruction's use of that name. * * <p>For example, in Example A in header comment above, suppose v1 referred to a "source"-entity * called "Local1". Since instruction (1) (LoadIndirect) uses "Local1", we record in this table * the SSA value number that represents "Local1" immediately before instruction (1). So if v1 and * v7 both refer to "Local1", then (1) uses v7. If v7 does NOT refer to "Local1", then (1) uses * v1. */ int getUse(int instructionIndex, T name); /** @see #getUse */ void setUse(int instructionIndex, T name, int newUse); }
3,659
36.731959
100
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/ssa/SSAInstanceofInstruction.java
/* * Copyright (c) 2002 - 2006 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package com.ibm.wala.ssa; import com.ibm.wala.types.TypeReference; /** A dynamic type test (instanceof) instruction. */ public class SSAInstanceofInstruction extends SSAInstruction { private final int result; private final int ref; private final TypeReference checkedType; public SSAInstanceofInstruction(int iindex, int result, int ref, TypeReference checkedType) { super(iindex); this.result = result; this.ref = ref; this.checkedType = checkedType; } @Override public SSAInstruction copyForSSA(SSAInstructionFactory insts, int[] defs, int[] uses) { if (defs != null && defs.length == 0) { throw new IllegalArgumentException("defs.length == 0"); } if (uses != null && uses.length == 0) { throw new IllegalArgumentException("uses.length == 0"); } return insts.InstanceofInstruction( iIndex(), defs == null || defs.length == 0 ? result : defs[0], uses == null ? ref : uses[0], checkedType); } @Override public String toString(SymbolTable symbolTable) { return getValueString(symbolTable, result) + " = instanceof " + getValueString(symbolTable, ref) + ' ' + checkedType; } @Override public void visit(IVisitor v) throws NullPointerException { v.visitInstanceof(this); } /** @see com.ibm.wala.ssa.SSAInstruction#getDef() */ @Override public boolean hasDef() { return true; } @Override public int getDef() { return result; } @Override public int getDef(int i) { assert i == 0; return result; } public TypeReference getCheckedType() { return checkedType; } /** @see com.ibm.wala.ssa.SSAInstruction#getNumberOfUses() */ @Override public int getNumberOfDefs() { return 1; } @Override public int getNumberOfUses() { return 1; } @Override public int getUse(int j) { assert j == 0; return ref; } @Override public int hashCode() { return ref * 677 ^ result * 3803; } @Override public boolean isFallThrough() { return true; } public int getRef() { return ref; } }
2,503
21.558559
95
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/ssa/SSAInstruction.java
/* * Copyright (c) 2002 - 2006 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package com.ibm.wala.ssa; import com.ibm.wala.types.TypeReference; import java.util.Collection; import java.util.Collections; /** An instruction in SSA form. */ public abstract class SSAInstruction { public static final int NO_INDEX = -1; private int instructionIndex; /** prevent instantiation by the outside */ protected SSAInstruction(int iindex) { this.instructionIndex = iindex; } /** * This method is meant to be used during SSA conversion for an IR that is not in SSA form. It * creates a new SSAInstruction of the same type as the receiver, with a combination of the * receiver's uses and defs and those from the method parameters. * * <p>In particular, if the 'defs' parameter is null, then the new instruction has the same defs * as the receiver. If 'defs' is not null, it must be an array with a size equal to the number of * defs that the receiver instruction has. In this case, the new instruction has defs taken from * the array. The uses of the new instruction work in the same way with the 'uses' parameter. * * <p>Note that this only applies to CAst-based IR translation, since Java bytecode-based IR * generation uses a different SSA construction mechanism. * * <p>TODO: move this into the SSAInstructionFactory */ public abstract SSAInstruction copyForSSA(SSAInstructionFactory insts, int[] defs, int[] uses); public abstract String toString(SymbolTable symbolTable); @Override public String toString() { return toString(null); } protected String getValueString(SymbolTable symbolTable, int valueNumber) { if (symbolTable == null) { return Integer.toString(valueNumber); } else { return symbolTable.getValueString(valueNumber); } } /** * Apply an IVisitor to this instruction. We invoke the appropriate IVisitor method according to * the type of this instruction. */ public abstract void visit(IVisitor v); /** This interface is used by Instruction.visit to dispatch based on the instruction type. */ @SuppressWarnings("unused") public interface IVisitor { default void visitGoto(SSAGotoInstruction instruction) {} default void visitArrayLoad(SSAArrayLoadInstruction instruction) {} default void visitArrayStore(SSAArrayStoreInstruction instruction) {} default void visitBinaryOp(SSABinaryOpInstruction instruction) {} default void visitUnaryOp(SSAUnaryOpInstruction instruction) {} default void visitConversion(SSAConversionInstruction instruction) {} default void visitComparison(SSAComparisonInstruction instruction) {} default void visitConditionalBranch(SSAConditionalBranchInstruction instruction) {} default void visitSwitch(SSASwitchInstruction instruction) {} default void visitReturn(SSAReturnInstruction instruction) {} default void visitGet(SSAGetInstruction instruction) {} default void visitPut(SSAPutInstruction instruction) {} default void visitInvoke(SSAInvokeInstruction instruction) {} default void visitNew(SSANewInstruction instruction) {} default void visitArrayLength(SSAArrayLengthInstruction instruction) {} default void visitThrow(SSAThrowInstruction instruction) {} default void visitMonitor(SSAMonitorInstruction instruction) {} default void visitCheckCast(SSACheckCastInstruction instruction) {} default void visitInstanceof(SSAInstanceofInstruction instruction) {} default void visitPhi(SSAPhiInstruction instruction) {} default void visitPi(SSAPiInstruction instruction) {} default void visitGetCaughtException(SSAGetCaughtExceptionInstruction instruction) {} default void visitLoadMetadata(SSALoadMetadataInstruction instruction) {} } /** A base visitor implementation that does nothing. */ public abstract static class Visitor implements IVisitor { @Override public void visitGoto(SSAGotoInstruction instruction) {} @Override public void visitArrayLoad(SSAArrayLoadInstruction instruction) {} @Override public void visitArrayStore(SSAArrayStoreInstruction instruction) {} @Override public void visitBinaryOp(SSABinaryOpInstruction instruction) {} @Override public void visitUnaryOp(SSAUnaryOpInstruction instruction) {} @Override public void visitConversion(SSAConversionInstruction instruction) {} @Override public void visitComparison(SSAComparisonInstruction instruction) {} @Override public void visitConditionalBranch(SSAConditionalBranchInstruction instruction) {} @Override public void visitSwitch(SSASwitchInstruction instruction) {} @Override public void visitReturn(SSAReturnInstruction instruction) {} @Override public void visitGet(SSAGetInstruction instruction) {} @Override public void visitPut(SSAPutInstruction instruction) {} @Override public void visitInvoke(SSAInvokeInstruction instruction) {} @Override public void visitNew(SSANewInstruction instruction) {} @Override public void visitArrayLength(SSAArrayLengthInstruction instruction) {} @Override public void visitThrow(SSAThrowInstruction instruction) {} @Override public void visitMonitor(SSAMonitorInstruction instruction) {} @Override public void visitCheckCast(SSACheckCastInstruction instruction) {} @Override public void visitInstanceof(SSAInstanceofInstruction instruction) {} @Override public void visitPhi(SSAPhiInstruction instruction) {} @Override public void visitPi(SSAPiInstruction instruction) {} @Override public void visitGetCaughtException(SSAGetCaughtExceptionInstruction instruction) {} @Override public void visitLoadMetadata(SSALoadMetadataInstruction instruction) {} } /** * Does this instruction define a normal value, as distinct from a set of exceptions possibly * thrown by it (e.g. for invoke instructions). * * @return true if the instruction does define a proper value. */ public boolean hasDef() { return false; } public int getDef() { return -1; } /** * Return the ith def * * @param i number of the def, starting at 0. */ public int getDef(int i) { return -1; } public int getNumberOfDefs() { return 0; } public int getNumberOfUses() { return 0; } /** * @return value number representing the jth use in this instruction. -1 means TOP (i.e., the * value doesn't matter) */ public int getUse(@SuppressWarnings("unused") int j) throws UnsupportedOperationException { throw new UnsupportedOperationException(); } @Override public abstract int hashCode(); /** @return true iff this instruction may throw an exception. */ public boolean isPEI() { return false; } /** * This method should never return null. * * @return the set of exception types that an instruction might throw ... disregarding athrows and * invokes. */ public Collection<TypeReference> getExceptionTypes() { assert !isPEI(); return Collections.emptySet(); } /** @return true iff this instruction may fall through to the next */ public abstract boolean isFallThrough(); /** * We assume these instructions are canonical and managed by a governing IR object. Be careful. * * <p>Depending on the caching policy (see {@link com.ibm.wala.ssa.SSACache}), the governing IR * may be deleted to reclaim memory and recomputed as needed. When an IR is recomputed, it also * creates fresh SSAInstruction objects that will not equal old ones. Thus, do not compare for * identity SSAInstructions obtained from distinct calls that retrieve cached values (e.g. * distinct CGNode.getIR() calls). See <a href="https://github.com/wala/WALA/issues/6">the github * issue </a> for details. */ @Override public final boolean equals(Object obj) { if (this == obj) return true; if (obj != null && obj instanceof SSAInstruction) return this.instructionIndex == ((SSAInstruction) obj).instructionIndex; else return false; } public int iIndex() { return instructionIndex; } public void setInstructionIndex(int instructionIndex) { this.instructionIndex = instructionIndex; } }
8,629
30.268116
100
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/ssa/SSAInstructionFactory.java
/* * Copyright (c) 2002 - 2006 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package com.ibm.wala.ssa; import com.ibm.wala.classLoader.CallSiteReference; import com.ibm.wala.classLoader.NewSiteReference; 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.IUnaryOpInstruction; import com.ibm.wala.shrike.shrikeCT.BootstrapMethodsReader.BootstrapMethod; import com.ibm.wala.types.FieldReference; import com.ibm.wala.types.TypeReference; /** An instruction factory for SSA. */ public interface SSAInstructionFactory { SSAAddressOfInstruction AddressOfInstruction( int iindex, int lval, int local, TypeReference pointeeType); SSAAddressOfInstruction AddressOfInstruction( int iindex, int lval, int local, int indexVal, TypeReference pointeeType); SSAAddressOfInstruction AddressOfInstruction( int iindex, int lval, int local, FieldReference field, TypeReference pointeeType); SSAArrayLengthInstruction ArrayLengthInstruction(int iindex, int result, int arrayref); SSAArrayLoadInstruction ArrayLoadInstruction( int iindex, int result, int arrayref, int index, TypeReference declaredType); SSAArrayStoreInstruction ArrayStoreInstruction( int iindex, int arrayref, int index, int value, TypeReference declaredType); SSAAbstractBinaryInstruction BinaryOpInstruction( int iindex, IBinaryOpInstruction.IOperator operator, boolean overflow, boolean unsigned, int result, int val1, int val2, boolean mayBeInteger); SSACheckCastInstruction CheckCastInstruction( int iindex, int result, int val, int[] typeValues, boolean isPEI); SSACheckCastInstruction CheckCastInstruction( int iindex, int result, int val, int typeValue, boolean isPEI); SSACheckCastInstruction CheckCastInstruction( int iindex, int result, int val, TypeReference[] types, boolean isPEI); SSACheckCastInstruction CheckCastInstruction( int iindex, int result, int val, TypeReference type, boolean isPEI); SSAComparisonInstruction ComparisonInstruction( int iindex, IComparisonInstruction.Operator operator, int result, int val1, int val2); SSAConditionalBranchInstruction ConditionalBranchInstruction( int iindex, IConditionalBranchInstruction.IOperator operator, TypeReference type, int val1, int val2, int target); SSAConversionInstruction ConversionInstruction( int iindex, int result, int val, TypeReference fromType, TypeReference toType, boolean overflow); SSAGetCaughtExceptionInstruction GetCaughtExceptionInstruction( int iindex, int bbNumber, int exceptionValueNumber); SSAGetInstruction GetInstruction(int iindex, int result, FieldReference field); SSAGetInstruction GetInstruction(int iindex, int result, int ref, FieldReference field); SSAGotoInstruction GotoInstruction(int iindex, int target); SSAInstanceofInstruction InstanceofInstruction( int iindex, int result, int ref, TypeReference checkedType); SSAAbstractInvokeInstruction InvokeInstruction( int iindex, int result, int[] params, int exception, CallSiteReference site, BootstrapMethod bootstrap); SSAAbstractInvokeInstruction InvokeInstruction( int iindex, int[] params, int exception, CallSiteReference site, BootstrapMethod bootstrap); SSALoadIndirectInstruction LoadIndirectInstruction( int iindex, int lval, TypeReference t, int addressVal); SSALoadMetadataInstruction LoadMetadataInstruction( int iindex, int lval, TypeReference entityType, Object token); SSAMonitorInstruction MonitorInstruction(int iindex, int ref, boolean isEnter); SSANewInstruction NewInstruction(int iindex, int result, NewSiteReference site); SSANewInstruction NewInstruction(int iindex, int result, NewSiteReference site, int[] params); SSAPhiInstruction PhiInstruction(int iindex, int result, int[] params); SSAPiInstruction PiInstruction( int iindex, int result, int val, int piBlock, int successorBlock, SSAInstruction cause); SSAPutInstruction PutInstruction(int iindex, int ref, int value, FieldReference field); SSAPutInstruction PutInstruction(int iindex, int value, FieldReference field); SSAReturnInstruction ReturnInstruction(int iindex); SSAReturnInstruction ReturnInstruction(int iindex, int result, boolean isPrimitive); SSAStoreIndirectInstruction StoreIndirectInstruction( int iindex, int addressVal, int rval, TypeReference pointeeType); SSASwitchInstruction SwitchInstruction( int iindex, int val, int defaultLabel, int[] casesAndLabels); SSAThrowInstruction ThrowInstruction(int iindex, int exception); SSAUnaryOpInstruction UnaryOpInstruction( int iindex, IUnaryOpInstruction.IOperator operator, int result, int val); }
5,296
35.784722
98
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/ssa/SSAInvokeDynamicInstruction.java
/* * Copyright (c) 2007 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package com.ibm.wala.ssa; import com.ibm.wala.classLoader.CallSiteReference; import com.ibm.wala.shrike.shrikeCT.BootstrapMethodsReader.BootstrapMethod; /** * Used for representing the JVML invokedynamic instruction. When generated by the Java compiler for * compilation of Java lambdas / method references, the instruction components are: * * <ul> * <li>the bootstrap method, which refers to {@link * java.lang.invoke.LambdaMetafactory#metafactory(java.lang.invoke.MethodHandles.Lookup, * String, java.lang.invoke.MethodType, java.lang.invoke.MethodType, * java.lang.invoke.MethodHandle, java.lang.invoke.MethodType)}, * <li>the call site, which contains the static arguments passed to the bootstrap method (i.e., * the method signature for the corresponding functional interface method), and * <li>the standard invoke instruction parameters, representing the dynamic arguments (captured * local variables) * </ul> * * <p>The behavior of WALA for other uses of invokedynamic is currently unspecified (though it aims * to not crash for any valid use). */ public class SSAInvokeDynamicInstruction extends SSAInvokeInstruction { private final BootstrapMethod bootstrap; public SSAInvokeDynamicInstruction( int iindex, int result, int[] params, int exception, CallSiteReference site, BootstrapMethod bootstrap) { super(iindex, result, params, exception, site); this.bootstrap = bootstrap; } public SSAInvokeDynamicInstruction( int iindex, int[] params, int exception, CallSiteReference site, BootstrapMethod bootstrap) { super(iindex, params, exception, site); this.bootstrap = bootstrap; } @Override public SSAInstruction copyForSSA(SSAInstructionFactory insts, int[] defs, int[] uses) { return new SSAInvokeDynamicInstruction( iIndex(), defs == null || result == -1 ? result : defs[0], uses == null ? params : uses, defs == null ? exception : defs[result == -1 ? 0 : 1], site, bootstrap); } public BootstrapMethod getBootstrap() { return bootstrap; } /** * Mark the instruction as an invokedynamic. The String will also contain the invocation type of * the boostrap method * * @param symbolTable the symbol table * @return result of {@link SSAAbstractInvokeInstruction#toString(SymbolTable)} with * "[invokedynamic] " pre-pended */ @Override public String toString(SymbolTable symbolTable) { return "[invokedynamic] " + super.toString(symbolTable); } }
2,951
35
100
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/ssa/SSAInvokeInstruction.java
/* * Copyright (c) 2002 - 2006 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package com.ibm.wala.ssa; import com.ibm.wala.classLoader.CallSiteReference; import com.ibm.wala.shrike.shrikeBT.IInvokeInstruction; import com.ibm.wala.types.TypeReference; /** */ public abstract class SSAInvokeInstruction extends SSAAbstractInvokeInstruction { protected final int result; /** * The value numbers of the arguments passed to the call. For non-static methods, params[0] == * this. If params == null, this should be a static method with no parameters. */ protected final int[] params; protected SSAInvokeInstruction( int iindex, int result, int[] params, int exception, CallSiteReference site) { super(iindex, exception, site); this.result = result; this.params = params; assertParamsKosher(result, params, site); } /** Constructor InvokeInstruction. This case for void return values */ protected SSAInvokeInstruction(int iindex, int[] params, int exception, CallSiteReference site) { this(iindex, -1, params, exception, site); } @Override public SSAInstruction copyForSSA(SSAInstructionFactory insts, int[] defs, int[] uses) { // result == -1 for void-returning methods, which are the only calls // that have a single value def. return insts.InvokeInstruction( iIndex(), defs == null || result == -1 ? result : defs[0], uses == null ? params : uses, defs == null ? exception : defs[result == -1 ? 0 : 1], site, null); } public static void assertParamsKosher(int result, int[] params, CallSiteReference site) throws IllegalArgumentException { if (site == null) { throw new IllegalArgumentException("site cannot be null"); } if (site.getDeclaredTarget().getReturnType().equals(TypeReference.Void)) { if (result != -1) { assert result == -1 : "bogus call to " + site; } } int nExpected = 0; if (!site.isStatic()) { nExpected++; } nExpected += site.getDeclaredTarget().getNumberOfParameters(); if (nExpected > 0) { assert params != null : "null params for " + site; if (params.length != nExpected) { assert params.length == nExpected : "wrong number of params for " + site + " Expected " + nExpected + " got " + params.length; } } } /** * @see com.ibm.wala.ssa.SSAInstruction#visit(IVisitor) * @throws IllegalArgumentException if v is null */ @Override public void visit(IVisitor v) { if (v == null) { throw new IllegalArgumentException("v is null"); } v.visitInvoke(this); } /** @see com.ibm.wala.ssa.SSAInstruction#getNumberOfUses() */ @Override public int getNumberOfUses() { if (params == null) { assert site.getInvocationCode() == IInvokeInstruction.Dispatch.STATIC || site.getInvocationCode() == IInvokeInstruction.Dispatch.SPECIAL; assert site.getDeclaredTarget().getNumberOfParameters() == 0; return 0; } else { return params.length; } } @Override public int getNumberOfPositionalParameters() { return getNumberOfUses(); } @Override public int getNumberOfReturnValues() { return (result == -1) ? 0 : 1; } @Override public int getReturnValue(int i) { assert i == 0 : "i != 0"; assert (result != -1) : "SSA-Result is -1"; return result; } /** @see com.ibm.wala.ssa.SSAInstruction#getUse(int) */ @Override public int getUse(int j) { if (params == null) { assert false : "Invalid getUse: " + j + " , null params " + this; } if (j >= params.length) { throw new ArrayIndexOutOfBoundsException( "Invalid getUse: " + this + ", index " + j + ", params.length " + params.length); } if (j < 0) { throw new ArrayIndexOutOfBoundsException( "j may not be negative! In getUse " + this + ", index " + j + ", params.length " + params.length); } return params[j]; } @Override public int hashCode() { return (site.hashCode() * 7529) + (exception * 9823); } }
4,550
28.551948
99
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/ssa/SSALoadIndirectInstruction.java
/* * Copyright (c) 2007 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package com.ibm.wala.ssa; import com.ibm.wala.types.TypeReference; import com.ibm.wala.util.debug.Assertions; /** * A load from a pointer. * * <p>v = *p */ public class SSALoadIndirectInstruction extends SSAAbstractUnaryInstruction { private final TypeReference loadedType; /** * @param lval the value number which is def'fed by this instruction. * @param addressVal the value number holding the pointer p deferenced (*p) */ public SSALoadIndirectInstruction(int iindex, int lval, TypeReference t, int addressVal) { super(iindex, lval, addressVal); this.loadedType = t; } public TypeReference getLoadedType() { return loadedType; } @Override public SSAInstruction copyForSSA(SSAInstructionFactory insts, int[] defs, int[] uses) { Assertions.UNREACHABLE("not implemented"); return null; } @Override public String toString(SymbolTable symbolTable) { return getValueString(symbolTable, getDef(0)) + " = *" + getValueString(symbolTable, getUse(0)) + ": " + loadedType; } @Override public void visit(IVisitor v) { ((IVisitorWithAddresses) v).visitLoadIndirect(this); } }
1,546
25.672414
92
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/ssa/SSALoadMetadataInstruction.java
/* * Copyright (c) 2002 - 2006 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package com.ibm.wala.ssa; import com.ibm.wala.types.TypeReference; /** * An instruction that represents a reflective or meta-programming operation, like loadClass in Java */ public abstract class SSALoadMetadataInstruction extends SSAInstruction { private final int lval; /** * A representation of the meta-data itself. For a loadClass operation, this would be a {@link * TypeReference} representing the class object being manipulated */ private final Object token; /** * The type of the thing that this meta-data represents. For a loadClass instruction, entityType * is java.lang.Class */ private final TypeReference entityType; protected SSALoadMetadataInstruction( int iindex, int lval, TypeReference entityType, Object token) { super(iindex); this.lval = lval; this.token = token; this.entityType = entityType; if (token == null) { throw new IllegalArgumentException("null typeRef"); } } @Override public SSAInstruction copyForSSA(SSAInstructionFactory insts, int[] defs, int[] uses) { if (defs != null && defs.length == 0) { throw new IllegalArgumentException("(defs != null) and (defs.length == 0)"); } return insts.LoadMetadataInstruction( iIndex(), defs == null ? lval : defs[0], entityType, token); } @Override public String toString(SymbolTable symbolTable) { return getValueString(symbolTable, lval) + " = load_metadata: " + token + ", " + entityType; } @Override public void visit(IVisitor v) { if (v == null) { throw new IllegalArgumentException("v is null"); } v.visitLoadMetadata(this); } @Override public int hashCode() { return token.hashCode() * lval; } @Override public boolean isPEI() { return true; } @Override public boolean hasDef() { return true; } @Override public int getDef() { return lval; } @Override public int getDef(int i) { assert i == 0; return lval; } @Override public int getNumberOfDefs() { return 1; } @Override public boolean isFallThrough() { return true; } public Object getToken() { return token; } public TypeReference getType() { return entityType; } }
2,616
22.576577
100
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/ssa/SSAMonitorInstruction.java
/* * Copyright (c) 2002 - 2006 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package com.ibm.wala.ssa; /** An instruction representing a monitorenter or monitorexit operation. */ public abstract class SSAMonitorInstruction extends SSAInstruction { /** The value number of the object being locked or unlocked */ private final int ref; /** Does this instruction represent a monitorenter? */ private final boolean isEnter; /** * @param ref The value number of the object being locked or unlocked * @param isEnter Does this instruction represent a monitorenter? */ protected SSAMonitorInstruction(int iindex, int ref, boolean isEnter) { super(iindex); this.ref = ref; this.isEnter = isEnter; } @Override public SSAInstruction copyForSSA(SSAInstructionFactory insts, int[] defs, int[] uses) { assert uses == null || uses.length == 1; return insts.MonitorInstruction(iIndex(), uses == null ? ref : uses[0], isEnter); } @Override public String toString(SymbolTable symbolTable) { return "monitor" + (isEnter ? "enter " : "exit ") + getValueString(symbolTable, ref); } @Override public void visit(IVisitor v) { if (v == null) { throw new IllegalArgumentException("v is null"); } v.visitMonitor(this); } @Override public int getNumberOfUses() { return 1; } @Override public int getUse(int j) { assert j == 0; return ref; } @Override public int hashCode() { return ref * 6173 + 4423; } @Override public boolean isPEI() { return true; } @Override public boolean isFallThrough() { return true; } /** @return The value number of the object being locked or unlocked */ public int getRef() { return ref; } /** Does this instruction represent a monitorenter? */ public boolean isMonitorEnter() { return isEnter; } }
2,168
24.22093
89
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/ssa/SSANewInstruction.java
/* * Copyright (c) 2002 - 2006 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package com.ibm.wala.ssa; import com.ibm.wala.classLoader.NewSiteReference; import com.ibm.wala.types.ClassLoaderReference; import com.ibm.wala.types.TypeReference; /** * An allocation instruction ("new") for SSA form. * * <p>This includes allocations of both scalars and arrays. */ public abstract class SSANewInstruction extends SSAInstruction { private final int result; private final NewSiteReference site; /** * The value numbers of the arguments passed to the call. If params == null, this should be a * static this statement allocates a scalar. if params != null, then params[i] is the size of the * ith dimension of the array. */ private final int[] params; /** Create a new instruction to allocate a scalar. */ protected SSANewInstruction(int iindex, int result, NewSiteReference site) throws IllegalArgumentException { super(iindex); if (site == null) { throw new IllegalArgumentException("site cannot be null"); } this.result = result; this.site = site; this.params = null; } /** * Create a new instruction to allocate an array. * * @throws IllegalArgumentException if site is null * @throws IllegalArgumentException if params is null */ protected SSANewInstruction(int iindex, int result, NewSiteReference site, int[] params) { super(iindex); if (params == null) { throw new IllegalArgumentException("params is null"); } if (site == null) { throw new IllegalArgumentException("site is null"); } assert site.getDeclaredType().isArrayType() || site.getDeclaredType().getClassLoader().getLanguage() != ClassLoaderReference.Java; this.result = result; this.site = site; this.params = params.clone(); } @Override public SSAInstruction copyForSSA(SSAInstructionFactory insts, int[] defs, int[] uses) { if (params == null) { return insts.NewInstruction(iIndex(), defs == null ? result : defs[0], site); } else { return insts.NewInstruction( iIndex(), defs == null ? result : defs[0], site, uses == null ? params : uses); } } @Override public String toString(SymbolTable symbolTable) { return getValueString(symbolTable, result) + " = new " + site.getDeclaredType() + '@' + site.getProgramCounter() + (params == null ? "" : array2String(params, symbolTable)); } private String array2String(int[] params, SymbolTable symbolTable) { StringBuilder result = new StringBuilder(); for (int param : params) { result.append(getValueString(symbolTable, param)); result.append(' '); } return result.toString(); } @Override public void visit(IVisitor v) { if (v == null) { throw new IllegalArgumentException("v is null"); } v.visitNew(this); } /** @see com.ibm.wala.ssa.SSAInstruction#getDef() */ @Override public boolean hasDef() { return true; } @Override public int getDef() { return result; } @Override public int getDef(int i) { assert i == 0; return result; } @Override public int getNumberOfDefs() { return 1; } /** @return TypeReference */ public TypeReference getConcreteType() { return site.getDeclaredType(); } public NewSiteReference getNewSite() { return site; } @Override public int hashCode() { return result * 7529 + site.getDeclaredType().hashCode(); } @Override public int getNumberOfUses() { return params == null ? 0 : params.length; } @Override public int getUse(int j) { assert params != null : "expected params but got null in " + this; assert params.length > j : "found too few parameters"; return params[j]; } @Override public boolean isPEI() { return true; } @Override public boolean isFallThrough() { return true; } }
4,245
25.209877
99
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/ssa/SSAOptions.java
/* * Copyright (c) 2002 - 2006 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package com.ibm.wala.ssa; /** Options that govern SSA construction */ public class SSAOptions { /** * While SSA form makes the not-unreasonable assumption that values must be defined before they * are used, many languages permit using undefined variables and simply give them some default * value. Rather than requiring an IR used in SSA conversion to add bogus assignments of the * default that will get copy propagated away, this interface is a way to specify what the default * values are: this object will be invoked whenever SSA conversion needs to read a value with an * no definition. */ public interface DefaultValues { int getDefaultValue(SymbolTable symtab, int valueNumber); } /** policy for pi node insertion. */ private SSAPiNodePolicy piNodePolicy; private DefaultValues defaultValues = null; private static final SSAOptions defaultOptions = new SSAOptions(); /** return a policy that enables all built-in pi node policies */ public static SSAPiNodePolicy getAllBuiltInPiNodes() { return CompoundPiPolicy.createCompoundPiPolicy( InstanceOfPiPolicy.createInstanceOfPiPolicy(), NullTestPiPolicy.createNullTestPiPolicy()); } public void setDefaultValues(DefaultValues defaultValues) { this.defaultValues = defaultValues; } public DefaultValues getDefaultValues() { return defaultValues; } /** @return the default SSA Options */ public static SSAOptions defaultOptions() { return defaultOptions; } public SSAPiNodePolicy getPiNodePolicy() { return piNodePolicy; } public void setPiNodePolicy(SSAPiNodePolicy piNodePolicy) { this.piNodePolicy = piNodePolicy; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((piNodePolicy == null) ? 0 : piNodePolicy.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 SSAOptions other = (SSAOptions) obj; if (piNodePolicy == null) { if (other.piNodePolicy != null) return false; } else if (!piNodePolicy.equals(other.piNodePolicy)) return false; return true; } }
2,646
31.280488
100
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/ssa/SSAPhiInstruction.java
/* * Copyright (c) 2002 - 2006 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package com.ibm.wala.ssa; import com.ibm.wala.analysis.stackMachine.AbstractIntStackMachine; import com.ibm.wala.cfg.ControlFlowGraph; import java.util.Arrays; import java.util.Iterator; /** * A phi instruction in SSA form. * * <p>See any modern compiler textbook for the definition of phi and the nature of SSA. * * <p>Note: In SSA {@link IR}s, these instructions do <em>not</em> appear in the normal instruction * array returned by IR.getInstructions(); instead these instructions live in {@link * ISSABasicBlock}. * * <p>{@code getUse(i)} corresponds to the value number from the i<sup>th</sup> predecessor of the * corresponding {@link ISSABasicBlock} {@code b} in {@link ControlFlowGraph} {@code g}, where * predecessor order is the order of nodes returned by the {@link Iterator} {@code * g.getPredNodes(b)}. * * <p>Note: if getUse(i) returns {@link AbstractIntStackMachine}.TOP (that is, -1), then that use * represents an edge in the CFG which is infeasible in verifiable bytecode. */ public class SSAPhiInstruction extends SSAInstruction { private final int result; private int[] params; public SSAPhiInstruction(int iindex, int result, int[] params) throws IllegalArgumentException { super(iindex); if (params == null) { throw new IllegalArgumentException("params is null"); } this.result = result; this.params = params; if (params.length == 0) { throw new IllegalArgumentException("can't have phi with no params"); } for (int p : params) { if (p == 0) { throw new IllegalArgumentException( "zero is an invalid value number for a parameter to phi"); } } } @Override public SSAInstruction copyForSSA(SSAInstructionFactory insts, int[] defs, int[] uses) throws IllegalArgumentException { if (defs != null && defs.length == 0) { throw new IllegalArgumentException(); } return insts.PhiInstruction( iIndex(), defs == null ? result : defs[0], uses == null ? params : uses); } @Override public String toString(SymbolTable symbolTable) { StringBuilder s = new StringBuilder(); s.append(getValueString(symbolTable, result)).append(" = phi "); s.append(' ').append(getValueString(symbolTable, params[0])); for (int i = 1; i < params.length; i++) { s.append(',').append(getValueString(symbolTable, params[i])); } return s.toString(); } @Override public void visit(IVisitor v) { if (v == null) { throw new IllegalArgumentException("v is null"); } v.visitPhi(this); } /** @see com.ibm.wala.ssa.SSAInstruction#getDef() */ @Override public boolean hasDef() { return true; } @Override public int getDef() { return result; } @Override public int getDef(int i) { if (i != 0) { throw new IllegalArgumentException("invalid i: " + i); } return result; } @Override public int getNumberOfUses() { return params.length; } @Override public int getNumberOfDefs() { return 1; } @Override public int getUse(int j) throws IllegalArgumentException { if (j >= params.length || j < 0) { throw new IllegalArgumentException("Bad use " + j); } return params[j]; } /** Clients should not call this. only for SSA builders. I hate this. Nuke it someday. */ public void setValues(int[] i) { if (i == null || i.length < 1) { throw new IllegalArgumentException("illegal i: " + Arrays.toString(i)); } this.params = i; } @Override protected String getValueString(SymbolTable symbolTable, int valueNumber) { if (valueNumber == AbstractIntStackMachine.TOP) { return "TOP"; } else { return super.getValueString(symbolTable, valueNumber); } } @Override public int hashCode() { return 7823 * result; } @Override public boolean isFallThrough() { return true; } }
4,284
27.190789
99
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/ssa/SSAPiInstruction.java
/* * Copyright (c) 2002 - 2006 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package com.ibm.wala.ssa; /** * A Pi instruction is a dummy assignment inserted at the tail of a basic block, in order to get a * new variable name to associate with some flow-insensitive dataflow fact. You can build an {@link * IR} with or without Pi instructions, depending on {@link SSAOptions} selected. * * <p>A Pi instruction is linked to its "cause" instruction, which is usually a conditional branch. * * <p>For example, the following pseudo-code * * <pre> * boolean condition = (x instanceof Integer); * if (condition) { * S1; * else { * S2; * } * </pre> * * <p>could be translated roughly as follows: * * <pre> * boolean condition = (x instanceof Integer); * LABEL1: if (condition) { * x_1 = pi(x, LABEL1); * S1; * else { * x_2 = pi(x, LABEL2); * S2; * } * </pre> */ public class SSAPiInstruction extends SSAUnaryOpInstruction { private final SSAInstruction cause; private final int successorBlock; private final int piBlock; /** * @param successorBlock the successor block; this PI assignment happens on the transition between * this basic block and the successor block. */ public SSAPiInstruction( int iindex, int result, int val, int piBlock, int successorBlock, SSAInstruction cause) { super(iindex, null, result, val); this.cause = cause; this.successorBlock = successorBlock; this.piBlock = piBlock; } @Override public SSAInstruction copyForSSA(SSAInstructionFactory insts, int[] defs, int[] uses) { assert defs == null || defs.length == 1; assert uses == null || uses.length == 1; return insts.PiInstruction( iIndex(), defs == null ? result : defs[0], uses == null ? val : uses[0], piBlock, successorBlock, cause); } @Override public String toString(SymbolTable symbolTable) { return getValueString(symbolTable, result) + " = pi " + getValueString(symbolTable, val) + " for BB" + successorBlock + ", cause " + cause; } @Override public void visit(IVisitor v) { if (v == null) { throw new IllegalArgumentException("v is null"); } v.visitPi(this); } public int getSuccessor() { return successorBlock; } public int getPiBlock() { return piBlock; } public SSAInstruction getCause() { return cause; } public int getVal() { return getUse(0); } }
2,874
24.900901
100
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/ssa/SSAPiNodePolicy.java
/* * Copyright (c) 2007 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package com.ibm.wala.ssa; import com.ibm.wala.util.collections.Pair; import java.util.List; /** * The {@link SSABuilder} consults this as an oracle to decide how to insert {@link * SSAPiInstruction}s */ public interface SSAPiNodePolicy { /** * Do we need to introduce a new name for some value immediately after a call? * * <p>If so, returns a pair consisting of the value number needing renaming, and the instruction * which should be recorded as the cause of the pi instruction * * @param call the call instruction in question * @param symbolTable current state of the symbol table for the IR under construction * @return description of the necessary pi instruction, or null if no pi instruction is needed. */ Pair<Integer, SSAInstruction> getPi(SSAAbstractInvokeInstruction call, SymbolTable symbolTable); /** * Do we need to introduce a new name for some value after deciding on an outcome for a * conditional branch instruction? * * <p>If so, returns a pair consisting of the value number needing renaming, and the instruction * which should be recorded as the cause of the pi instruction * * @param cond the conditional branch instruction in question * @param def1 the {@link SSAInstruction} that defs cond.getUse(0), or null if none * @param def2 the {@link SSAInstruction} that defs cond.getUse(1), or null if none * @param symbolTable current state of the symbol table for the IR under construction * @return description of the necessary pi instruction, or null if no pi instruction is needed. */ Pair<Integer, SSAInstruction> getPi( SSAConditionalBranchInstruction cond, SSAInstruction def1, SSAInstruction def2, SymbolTable symbolTable); List<Pair<Integer, SSAInstruction>> getPis( SSAConditionalBranchInstruction cond, SSAInstruction def1, SSAInstruction def2, SymbolTable symbolTable); }
2,298
37.966102
98
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/ssa/SSAPutInstruction.java
/* * Copyright (c) 2002 - 2006 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package com.ibm.wala.ssa; import com.ibm.wala.types.FieldReference; /** A putfield or putstatic instruction */ public abstract class SSAPutInstruction extends SSAFieldAccessInstruction { private final int val; protected SSAPutInstruction(int iindex, int ref, int val, FieldReference field) { super(iindex, field, ref); this.val = val; } protected SSAPutInstruction(int iindex, int val, FieldReference field) { super(iindex, field, -1); this.val = val; } @Override public SSAInstruction copyForSSA(SSAInstructionFactory insts, int[] defs, int[] uses) { if (isStatic()) return insts.PutInstruction(iIndex(), uses == null ? val : uses[0], getDeclaredField()); else return insts.PutInstruction( iIndex(), uses == null ? getRef() : uses[0], uses == null ? val : uses[1], getDeclaredField()); } @Override public String toString(SymbolTable symbolTable) { if (isStatic()) { return "putstatic " + getDeclaredField() + " = " + getValueString(symbolTable, val); } else { return "putfield " + getValueString(symbolTable, getRef()) + '.' + getDeclaredField() + " = " + getValueString(symbolTable, val); } } /** * @see com.ibm.wala.ssa.SSAInstruction#visit(IVisitor) * @throws IllegalArgumentException if v is null */ @Override public void visit(IVisitor v) { if (v == null) { throw new IllegalArgumentException("v is null"); } v.visitPut(this); } /** @see com.ibm.wala.ssa.SSAInstruction#getNumberOfUses() */ @Override public int getNumberOfUses() { return isStatic() ? 1 : 2; } /** @see com.ibm.wala.ssa.SSAInstruction#getUse(int) */ @Override public int getUse(int j) { assert j == 0 || (!isStatic() && j == 1); return (j == 0 && !isStatic()) ? getRef() : val; } public int getVal() { return val; } @Override public int hashCode() { return val * 9929 ^ 2063; } /** @see com.ibm.wala.ssa.SSAInstruction#isFallThrough() */ @Override public boolean isFallThrough() { return true; } }
2,524
25.302083
94
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/ssa/SSAReturnInstruction.java
/* * Copyright (c) 2002 - 2006 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package com.ibm.wala.ssa; /** A return instruction. */ public class SSAReturnInstruction extends SSAInstruction { /** value number of the result. By convention result == -1 means returns void. */ private final int result; private final boolean isPrimitive; public SSAReturnInstruction(int iindex, int result, boolean isPrimitive) { super(iindex); this.result = result; this.isPrimitive = isPrimitive; } public SSAReturnInstruction(int iindex) { super(iindex); this.result = -1; this.isPrimitive = false; } @Override public SSAInstruction copyForSSA(SSAInstructionFactory insts, int[] defs, int[] uses) { if (result == -1) return insts.ReturnInstruction(iIndex()); else { if (uses != null && uses.length != 1) { throw new IllegalArgumentException("invalid uses. must have exactly one use."); } return insts.ReturnInstruction(iIndex(), uses == null ? result : uses[0], isPrimitive); } } @Override public String toString(SymbolTable table) { if (result == -1) { return "return"; } else { return "return " + getValueString(table, result); } } @Override public void visit(IVisitor v) { if (v == null) { throw new IllegalArgumentException("v is null"); } v.visitReturn(this); } @Override public int getNumberOfUses() { return (result == -1) ? 0 : 1; } @Override public int getUse(int j) { if (j != 0) { throw new IllegalArgumentException("illegal j: " + j); } return result; } /** @return true iff this return instruction returns a primitive value */ public boolean returnsPrimitiveType() { return isPrimitive; } public int getResult() { return result; } public boolean returnsVoid() { return result == -1; } @Override public int hashCode() { return result * 8933; } @Override public boolean isFallThrough() { return false; } }
2,330
22.785714
93
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/ssa/SSAStoreIndirectInstruction.java
/* * Copyright (c) 2007 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package com.ibm.wala.ssa; import com.ibm.wala.types.TypeReference; import com.ibm.wala.util.debug.Assertions; /** * A store from a pointer. * * <p>*p = v */ public class SSAStoreIndirectInstruction extends SSAInstruction { private final int addressVal; private final int rval; private final TypeReference pointeeType; /** * @param addressVal the value number holding the pointer p deferenced (*p) * @param rval the value number which is stored into the pointer location */ public SSAStoreIndirectInstruction( int iindex, int addressVal, int rval, TypeReference pointeeType) { super(iindex); this.addressVal = addressVal; this.rval = rval; this.pointeeType = pointeeType; } public TypeReference getPointeeType() { return pointeeType; } @Override public SSAInstruction copyForSSA(SSAInstructionFactory insts, int[] defs, int[] uses) { Assertions.UNREACHABLE("unimplemented"); return null; } @Override public int hashCode() { return addressVal * 353456 * rval; } @Override public boolean isFallThrough() { return true; } @Override public String toString(SymbolTable symbolTable) { return '*' + getValueString(symbolTable, addressVal) + " = " + getValueString(symbolTable, rval); } @Override public void visit(IVisitor v) { ((IVisitorWithAddresses) v).visitStoreIndirect(this); } }
1,791
23.216216
89
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/ssa/SSASwitchInstruction.java
/* * Copyright (c) 2002 - 2006 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package com.ibm.wala.ssa; import com.ibm.wala.util.intset.IntIterator; /** SSA instruction representing a switch statement. */ public class SSASwitchInstruction extends SSAInstruction { private final int val; private final int defaultLabel; private final int[] casesAndLabels; /** * The labels in casesAndLabels represent <em>instruction indices</em> in the IR that each switch * case branches to. */ public SSASwitchInstruction(int iindex, int val, int defaultLabel, int[] casesAndLabels) { super(iindex); this.val = val; this.defaultLabel = defaultLabel; this.casesAndLabels = casesAndLabels; } @Override public SSAInstruction copyForSSA(SSAInstructionFactory insts, int[] defs, int[] uses) { assert uses == null || uses.length == 1; for (int i = 1; i < casesAndLabels.length; i += 2) { assert casesAndLabels[i] != iIndex() : "do not branch to self: " + this; } return insts.SwitchInstruction( iIndex(), uses == null ? val : uses[0], defaultLabel, casesAndLabels); } @Override public String toString(SymbolTable symbolTable) { StringBuilder result = new StringBuilder(iIndex() + ": switch "); result.append(getValueString(symbolTable, val)); result.append(" ["); for (int i = 0; i < casesAndLabels.length - 1; i++) { result.append(casesAndLabels[i]); i++; result.append("->"); result.append(casesAndLabels[i]); if (i < casesAndLabels.length - 2) { result.append(','); } } result.append("] default: ").append(defaultLabel); return result.toString(); } @Override public void visit(IVisitor v) { if (v == null) { throw new IllegalArgumentException("v is null"); } v.visitSwitch(this); } @Override public int getNumberOfUses() { return 1; } @Override public int getUse(int j) { assert j <= 1; return val; } // public int[] getTargets() { // // TODO Auto-generated method stub // Assertions.UNREACHABLE(); // return null; // } public int getTarget(int caseValue) { for (int i = 0; i < casesAndLabels.length; i += 2) if (caseValue == casesAndLabels[i]) return casesAndLabels[i + 1]; return defaultLabel; } public int getDefault() { return defaultLabel; } public int[] getCasesAndLabels() { return casesAndLabels; } public IntIterator iterateLabels() { return new IntIterator() { private int i = 0; @Override public boolean hasNext() { return i < casesAndLabels.length; } @Override public int next() { int v = casesAndLabels[i]; i += 2; return v; } }; } @Override public int hashCode() { return val * 1663 + 3499; } @Override public boolean isFallThrough() { return false; } }
3,217
23.564885
99
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/ssa/SSAThrowInstruction.java
/* * Copyright (c) 2002 - 2006 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package com.ibm.wala.ssa; /** An instruction which unconditionally throws an exception */ public abstract class SSAThrowInstruction extends SSAAbstractThrowInstruction { protected SSAThrowInstruction(int iindex, int exception) { super(iindex, exception); } /** * @see com.ibm.wala.ssa.SSAInstruction#copyForSSA(com.ibm.wala.ssa.SSAInstructionFactory, int[], * int[]) */ @Override public SSAInstruction copyForSSA(SSAInstructionFactory insts, int[] defs, int[] uses) throws IllegalArgumentException { if (uses != null && uses.length != 1) { throw new IllegalArgumentException("if non-null, uses.length must be 1"); } return insts.ThrowInstruction(iIndex(), uses == null ? getException() : uses[0]); } /** @see com.ibm.wala.ssa.SSAInstruction#visit(IVisitor) */ @Override public void visit(IVisitor v) throws NullPointerException { v.visitThrow(this); } }
1,298
32.307692
99
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/ssa/SSAUnaryOpInstruction.java
/* * Copyright (c) 2002 - 2006 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package com.ibm.wala.ssa; import com.ibm.wala.shrike.shrikeBT.IUnaryOpInstruction; /** * An SSA instruction for some unary operator. * * @see IUnaryOpInstruction for a list of operators */ public class SSAUnaryOpInstruction extends SSAAbstractUnaryInstruction { private final IUnaryOpInstruction.IOperator operator; public SSAUnaryOpInstruction( int iindex, IUnaryOpInstruction.IOperator operator, int result, int val) { super(iindex, result, val); this.operator = operator; } @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.UnaryOpInstruction( iIndex(), operator, defs == null || defs.length == 0 ? result : defs[0], uses == null ? val : uses[0]); } @Override public String toString(SymbolTable symbolTable) { return getValueString(symbolTable, result) + " = " + operator + ' ' + getValueString(symbolTable, val); } /** @see com.ibm.wala.ssa.SSAInstruction#visit(IVisitor) */ @Override public void visit(IVisitor v) throws NullPointerException { v.visitUnaryOp(this); } public IUnaryOpInstruction.IOperator getOpcode() { return operator; } }
1,788
27.854839
87
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/ssa/ShrikeIndirectionData.java
/* * Copyright (c) 2007 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package com.ibm.wala.ssa; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.Map; /** An implementation of {@link SSAIndirectionData} specialized for IRs originated from Shrike. */ public class ShrikeIndirectionData implements SSAIndirectionData<ShrikeIndirectionData.ShrikeLocalName> { /** * In Shrike, the only "source" level entities which have names relevant to indirect pointer * operations are bytecode locals. */ public static class ShrikeLocalName implements com.ibm.wala.ssa.SSAIndirectionData.Name { private final int bytecodeLocalNumber; public ShrikeLocalName(int bytecodeLocalNumber) { this.bytecodeLocalNumber = bytecodeLocalNumber; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + bytecodeLocalNumber; return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; ShrikeLocalName other = (ShrikeLocalName) obj; if (bytecodeLocalNumber != other.bytecodeLocalNumber) return false; return true; } @Override public String toString() { return "(local:" + bytecodeLocalNumber + ')'; } } private final Map<ShrikeLocalName, Integer>[] defs; private final Map<ShrikeLocalName, Integer>[] uses; @SuppressWarnings("unchecked") public ShrikeIndirectionData(int instructionArrayLength) { defs = new HashMap[instructionArrayLength]; uses = new HashMap[instructionArrayLength]; } @Override public int getDef(int instructionIndex, ShrikeLocalName name) { if (defs[instructionIndex] == null || !defs[instructionIndex].containsKey(name)) { return -1; } else { return defs[instructionIndex].get(name); } } @Override public int getUse(int instructionIndex, ShrikeLocalName name) { if (uses[instructionIndex] == null || !uses[instructionIndex].containsKey(name)) { return -1; } else { return uses[instructionIndex].get(name); } } @Override public void setDef(int instructionIndex, ShrikeLocalName name, int newDef) { if (defs[instructionIndex] == null) { defs[instructionIndex] = new HashMap<>(2); } defs[instructionIndex].put(name, newDef); } @Override public void setUse(int instructionIndex, ShrikeLocalName name, int newUse) { if (uses[instructionIndex] == null) { uses[instructionIndex] = new HashMap<>(2); } uses[instructionIndex].put(name, newUse); } @Override public Collection<ShrikeLocalName> getNames() { HashSet<ShrikeLocalName> result = new HashSet<>(); for (int i = 0; i < uses.length; i++) { if (uses[i] != null) { result.addAll(uses[i].keySet()); } if (defs[i] != null) { result.addAll(defs[i].keySet()); } } return result; } @Override public String toString() { StringBuilder result = new StringBuilder(); for (int i = 0; i < defs.length; i++) { if (defs[i] != null) { result.append(i).append(" <- ").append(defs[i]).append('\n'); } if (uses[i] != null) { result.append(i).append(" -> ").append(uses[i]).append('\n'); } } return result.toString(); } }
3,746
27.603053
98
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/ssa/SymbolTable.java
/* * Copyright (c) 2002 - 2006 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package com.ibm.wala.ssa; import com.ibm.wala.util.collections.HashMapFactory; import com.ibm.wala.util.debug.Assertions; import java.util.Arrays; import java.util.HashMap; /** * A symbol table which associates information with each variable (value number) in an SSA IR. * * <p>By convention, symbol numbers start at 1 ... the "this" parameter will be symbol number 1 in a * virtual method. * * <p>This class is used heavily during SSA construction by {@link SSABuilder}. */ public class SymbolTable implements Cloneable { private static final int MAX_VALUE_NUMBER = Integer.MAX_VALUE / 4; /** value numbers for parameters to this method */ private final int[] parameters; /** Mapping from Constant -&gt; value number */ private HashMap<ConstantValue, Integer> constants = HashMapFactory.make(10); private boolean copy = false; /** @param numberOfParameters in the IR .. should be ir.getNumberOfParameters() */ public SymbolTable(int numberOfParameters) { if (numberOfParameters < 0) { throw new IllegalArgumentException("Illegal numberOfParameters: " + numberOfParameters); } parameters = new int[numberOfParameters]; for (int i = 0; i < parameters.length; i++) { parameters[i] = getNewValueNumber(); } } /** * Values. Note: this class must maintain the following invariant: values.length &gt; * nextFreeValueNumber. */ private Value[] values = new Value[5]; private int nextFreeValueNumber = 1; /** * Method newSymbol. * * @return int */ public int newSymbol() { return getNewValueNumber(); } int findOrCreateConstant(Object o) { return findOrCreateConstant(o, false); } /** * Common part of getConstant functions. * * @param o instance of a Java 'boxed-primitive' class, String or NULL. * @return value number for constant. */ int findOrCreateConstant(Object o, boolean isDefault) { ConstantValue v = new ConstantValue(o); Integer result = constants.get(v); if (result == null) { assert !(copy && !isDefault) : "making value for " + o; int r = getNewValueNumber(); result = r; constants.put(v, result); assert r < nextFreeValueNumber; values[r] = v; } else { assert values[result] instanceof ConstantValue; } return result; } public void setConstantValue(int vn, ConstantValue val) { try { assert vn < nextFreeValueNumber; values[vn] = val; } catch (ArrayIndexOutOfBoundsException e) { throw new IllegalArgumentException("invalid vn: " + vn, e); } } private Object[] defaultValues; /** * Set the default value for a value number. The notion of a default value is for use by languages * that do not require variables to be defined before they are used. In this situation, SSA * conversion can fail since it depends on the assumption that values are always defined when * used. The default value is the constant to be used in cases when a given value is used without * having been defined. Currently, this is used only by CAst front ends for languages with this * "feature". */ public void setDefaultValue(int vn, final Object defaultValue) { assert vn < nextFreeValueNumber; if (defaultValues == null) { defaultValues = new Object[vn * 2 + 1]; } if (defaultValues.length <= vn) { defaultValues = Arrays.copyOf(defaultValues, vn * 2 + 1); } defaultValues[vn] = defaultValue; } public int getDefaultValue(int vn) { return findOrCreateConstant(defaultValues[vn], true); } public int getNullConstant() { return findOrCreateConstant(null); } public int getConstant(boolean b) { return findOrCreateConstant(b); } public int getConstant(int i) { return findOrCreateConstant(i); } public int getConstant(long l) { return findOrCreateConstant(l); } public int getConstant(float f) { return findOrCreateConstant(f); } public int getConstant(double d) { return findOrCreateConstant(d); } public int getOtherConstant(Object v) { return findOrCreateConstant(v); } public int getConstant(String s) { return findOrCreateConstant(s); } /** * Return the value number of the ith parameter * * <p>By convention, for a non-static method, the 0th parameter is 'this' */ public int getParameter(int i) throws IllegalArgumentException { try { return parameters[i]; } catch (ArrayIndexOutOfBoundsException e) { throw new IllegalArgumentException("invalid i: " + i, e); } } private void expandForNewValueNumber(int vn) { if (vn >= values.length) { values = Arrays.copyOf(values, 2 * vn); } } private int getNewValueNumber() { int result = nextFreeValueNumber++; expandForNewValueNumber(result); return result; } /** * ensure that the symbol table has allocated space for the particular value number * * @param i a value number */ public void ensureSymbol(int i) { if (i < 0 || i > MAX_VALUE_NUMBER) { throw new IllegalArgumentException("Illegal i: " + i); } try { if (i != -1) { if (i >= values.length || values[i] == null) { if (nextFreeValueNumber <= i) { nextFreeValueNumber = i + 1; } expandForNewValueNumber(i); } } } catch (ArrayIndexOutOfBoundsException e) { throw new IllegalArgumentException("invalid i: " + i, e); } } public String getValueString(int valueNumber) { if (valueNumber < 0 || valueNumber > getMaxValueNumber() || values[valueNumber] == null || values[valueNumber] instanceof PhiValue) { return "v" + valueNumber; } else { return "v" + valueNumber + ':' + values[valueNumber].toString(); } } public boolean isConstant(int v) { try { return v < values.length && values[v] instanceof ConstantValue; } catch (ArrayIndexOutOfBoundsException e) { throw new IllegalArgumentException("invalid v: " + v, e); } } public boolean isZero(int v) { try { return (values[v] instanceof ConstantValue) && ((ConstantValue) values[v]).isZeroConstant(); } catch (ArrayIndexOutOfBoundsException e) { throw new IllegalArgumentException("invalid v: " + v, e); } } public boolean isOne(int v) { try { return (values[v] instanceof ConstantValue) && ((ConstantValue) values[v]).isOneConstant(); } catch (ArrayIndexOutOfBoundsException e) { throw new IllegalArgumentException("invalid v: " + v, e); } } public boolean isTrue(int v) { try { return (values[v] instanceof ConstantValue) && ((ConstantValue) values[v]).isTrueConstant(); } catch (ArrayIndexOutOfBoundsException e) { throw new IllegalArgumentException("invalid v: " + v, e); } } public boolean isZeroOrFalse(int v) { return isZero(v) || isFalse(v); } public boolean isOneOrTrue(int v) { return isOne(v) || isTrue(v); } public boolean isFalse(int v) { try { return (values[v] instanceof ConstantValue) && ((ConstantValue) values[v]).isFalseConstant(); } catch (ArrayIndexOutOfBoundsException e) { throw new IllegalArgumentException("invalid v: " + v, e); } } public boolean isBooleanOrZeroOneConstant(int v) { return isBooleanConstant(v) || isZero(v) || isOne(v); } public boolean isBooleanConstant(int v) { try { return (values[v] instanceof ConstantValue) && ((ConstantValue) values[v]).getValue() instanceof Boolean; } catch (ArrayIndexOutOfBoundsException e) { throw new IllegalArgumentException("invalid v: " + v, e); } } public boolean isIntegerConstant(int v) { try { return (values[v] instanceof ConstantValue) && (((ConstantValue) values[v]).getValue() instanceof Integer); } catch (ArrayIndexOutOfBoundsException e) { throw new IllegalArgumentException("invalid v: " + v, e); } } public boolean isLongConstant(int v) { try { return (values[v] instanceof ConstantValue) && (((ConstantValue) values[v]).getValue() instanceof Long); } catch (ArrayIndexOutOfBoundsException e) { throw new IllegalArgumentException("invalid v: " + v, e); } } public boolean isFloatConstant(int v) { try { return (values[v] instanceof ConstantValue) && ((ConstantValue) values[v]).getValue() instanceof Float; } catch (ArrayIndexOutOfBoundsException e) { throw new IllegalArgumentException("invalid v: " + v, e); } } public boolean isDoubleConstant(int v) { try { return (values[v] instanceof ConstantValue) && ((ConstantValue) values[v]).getValue() instanceof Double; } catch (ArrayIndexOutOfBoundsException e) { throw new IllegalArgumentException("invalid v: " + v, e); } } public boolean isNumberConstant(int v) { try { return (values[v] instanceof ConstantValue) && ((ConstantValue) values[v]).getValue() instanceof Number; } catch (ArrayIndexOutOfBoundsException e) { throw new IllegalArgumentException("invalid v: " + v, e); } } public boolean isStringConstant(int v) { try { return (values[v] instanceof ConstantValue) && ((ConstantValue) values[v]).getValue() instanceof String; } catch (ArrayIndexOutOfBoundsException e) { throw new IllegalArgumentException("invalid v: " + v, e); } } public boolean isNullConstant(int v) { try { return (values.length > v) && (values[v] instanceof ConstantValue) && (((ConstantValue) values[v]).getValue() == null); } catch (ArrayIndexOutOfBoundsException e) { throw new IllegalArgumentException("invalid v: " + v, e); } } /** @throws IllegalArgumentException if rhs is null */ public int newPhi(int[] rhs) throws IllegalArgumentException { if (rhs == null) { throw new IllegalArgumentException("rhs is null"); } int result = getNewValueNumber(); SSAPhiInstruction phi = new SSAPhiInstruction(SSAInstruction.NO_INDEX, result, rhs.clone()); assert result < nextFreeValueNumber; values[result] = new PhiValue(phi); return result; } /** Return the PhiValue that is associated with a given value number */ public PhiValue getPhiValue(int valueNumber) { try { return (PhiValue) values[valueNumber]; } catch (ArrayIndexOutOfBoundsException | ClassCastException e) { throw new IllegalArgumentException("invalid valueNumber: " + valueNumber, e); } } public int getMaxValueNumber() { // return values.length - 1; return nextFreeValueNumber - 1; } public int[] getParameterValueNumbers() { return parameters; } public int getNumberOfParameters() { return parameters.length; } public String getStringValue(int v) throws IllegalArgumentException { if (!isStringConstant(v)) { throw new IllegalArgumentException("not a string constant: value number " + v); } return (String) ((ConstantValue) values[v]).getValue(); } public float getFloatValue(int v) throws IllegalArgumentException { if (!isNumberConstant(v)) { throw new IllegalArgumentException("value number " + v + " is not a numeric constant."); } return ((Number) ((ConstantValue) values[v]).getValue()).floatValue(); } public double getDoubleValue(int v) throws IllegalArgumentException { if (!isNumberConstant(v)) { throw new IllegalArgumentException("value number " + v + " is not a numeric constant."); } return ((Number) ((ConstantValue) values[v]).getValue()).doubleValue(); } public int getIntValue(int v) throws IllegalArgumentException { if (!isNumberConstant(v)) { throw new IllegalArgumentException("value number " + v + " is not a numeric constant."); } return ((Number) ((ConstantValue) values[v]).getValue()).intValue(); } public long getLongValue(int v) throws IllegalArgumentException { if (!isNumberConstant(v)) { throw new IllegalArgumentException("value number " + v + " is not a numeric constant."); } return ((Number) ((ConstantValue) values[v]).getValue()).longValue(); } public Object getConstantValue(int v) throws IllegalArgumentException { if (!isConstant(v)) { throw new IllegalArgumentException("value number " + v + " is not a constant."); } Object value = ((ConstantValue) values[v]).getValue(); if (value == null) { return null; } else { return value; } } /** * @return the Value object for given value number or null if we have no special information about * the value */ public Value getValue(int valueNumber) { if (valueNumber < 1 || valueNumber >= values.length) { throw new IllegalArgumentException("Invalid value number " + valueNumber); } return values[valueNumber]; } /** @return true iff this valueNumber is a parameter */ public boolean isParameter(int valueNumber) { return valueNumber <= getNumberOfParameters(); } public SymbolTable copy() { try { SymbolTable nt = (SymbolTable) clone(); nt.values = this.values.clone(); if (this.defaultValues != null) { nt.defaultValues = this.defaultValues.clone(); } nt.constants = HashMapFactory.make(this.constants); nt.copy = true; return nt; } catch (CloneNotSupportedException e) { Assertions.UNREACHABLE(); return null; } } }
13,923
29.269565
100
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/ssa/Value.java
/* * Copyright (c) 2002 - 2006 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package com.ibm.wala.ssa; /** * Representation of a particular value which appears in an SSA IR. * * <p>Clients probably shouldn't use this; it's only public (for now) due to Java's package-based * weak module system. */ public interface Value { /** Is this value a string constant? */ boolean isStringConstant(); /** Is this value a null constant? */ boolean isNullConstant(); }
771
27.592593
97
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/ssa/analysis/DeadAssignmentElimination.java
/* * Copyright (c) 2002 - 2006 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package com.ibm.wala.ssa.analysis; import com.ibm.wala.cfg.ControlFlowGraph; import com.ibm.wala.core.util.CancelRuntimeException; import com.ibm.wala.fixedpoint.impl.DefaultFixedPointSolver; import com.ibm.wala.fixpoint.BooleanVariable; import com.ibm.wala.fixpoint.UnaryOr; import com.ibm.wala.ssa.*; import com.ibm.wala.ssa.SSACFG.BasicBlock; import com.ibm.wala.util.CancelException; import com.ibm.wala.util.collections.HashMapFactory; import com.ibm.wala.util.collections.HashSetFactory; import com.ibm.wala.util.collections.Iterator2Iterable; import java.util.HashSet; import java.util.Map; import java.util.Map.Entry; /** Eliminate dead assignments (phis) from an SSA IR. */ public class DeadAssignmentElimination { private static final boolean DEBUG = false; /** * eliminate dead phis from an ir * * @throws IllegalArgumentException if ir is null */ public static void perform(IR ir) { if (ir == null) { throw new IllegalArgumentException("ir is null"); } DefUse DU = new DefUse(ir); DeadValueSystem system = new DeadValueSystem(ir, DU); try { system.solve(null); } catch (CancelException e) { throw new CancelRuntimeException(e); } doTransformation(ir, system); } /** * Perform the transformation * * @param ir IR to transform * @param solution dataflow solution for dead assignment elimination */ private static void doTransformation(IR ir, DeadValueSystem solution) { ControlFlowGraph<?, ISSABasicBlock> cfg = ir.getControlFlowGraph(); for (ISSABasicBlock issaBasicBlock : cfg) { BasicBlock b = (BasicBlock) issaBasicBlock; if (DEBUG) { System.err.println("eliminateDeadPhis: " + b); } if (b.hasPhi()) { HashSet<SSAPhiInstruction> toRemove = HashSetFactory.make(5); for (SSAPhiInstruction phi : Iterator2Iterable.make(b.iteratePhis())) { if (phi != null) { int def = phi.getDef(); if (solution.isDead(def)) { if (DEBUG) { System.err.println("Will remove phi: " + phi); } toRemove.add(phi); } } } b.removePhis(toRemove); } } } /** A dataflow system which computes whether or not a value is dead */ private static class DeadValueSystem extends DefaultFixedPointSolver<BooleanVariable> { /** Map: value number -&gt; BooleanVariable isLive */ private final Map<Integer, BooleanVariable> vars = HashMapFactory.make(); /** set of value numbers that are trivially dead */ private final HashSet<Integer> trivialDead = HashSetFactory.make(); /** * @param ir the IR to analyze * @param DU def-use information for the IR */ DeadValueSystem(IR ir, DefUse DU) { // create a variable for each potentially dead phi instruction. for (SSAInstruction inst : Iterator2Iterable.make(ir.iteratePhis())) { SSAPhiInstruction phi = (SSAPhiInstruction) inst; if (phi == null) { continue; } int def = phi.getDef(); if (DU.isUnused(def)) { // the phi is certainly dead ... record this with a dataflow fact. trivialDead.add(def); } else { boolean maybeDead = true; for (SSAInstruction u : Iterator2Iterable.make(DU.getUses(def))) { if (!(u instanceof SSAPhiInstruction)) { // certainly not dead maybeDead = false; break; } } if (maybeDead) { // perhaps the phi is dead .. create a variable BooleanVariable B = new BooleanVariable(false); vars.put(def, B); } } } // Now create dataflow equations; v is live iff any phi that uses v is live for (Entry<Integer, BooleanVariable> E : vars.entrySet()) { Integer def = E.getKey(); BooleanVariable B = E.getValue(); for (SSAInstruction use : Iterator2Iterable.make(DU.getUses(def))) { SSAPhiInstruction u = (SSAPhiInstruction) use; Integer ud = u.getDef(); if (trivialDead.contains(ud)) { // do nothing ... u will not keep def live } else { if (!vars.containsKey(ud)) { // u is not potentially dead ... certainly v is live. // record this. B.set(true); } else { // maybe u is dead? // add constraint v is live if u is live. BooleanVariable U = vars.get(ud); newStatement(B, UnaryOr.instance(), U, true, false); } } } } } @Override protected void initializeVariables() { // do nothing: all variables are initialized to false (TOP), meaning "not live" } @Override protected void initializeWorkList() { addAllStatementsToWorkList(); } /** @return true iff there are no uses of the given value number */ private boolean isDead(int value) { Integer V = value; if (trivialDead.contains(V)) { return true; } else { BooleanVariable B = vars.get(V); if (B == null) { return false; } else { return !B.getValue(); } } } @Override protected BooleanVariable[] makeStmtRHS(int size) { return new BooleanVariable[size]; } } }
5,814
31.305556
89
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/ssa/analysis/ExplodedControlFlowGraph.java
/* * Copyright (c) 2002 - 2006 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package com.ibm.wala.ssa.analysis; import com.ibm.wala.cfg.ControlFlowGraph; import com.ibm.wala.classLoader.IMethod; import com.ibm.wala.ssa.IR; import com.ibm.wala.ssa.ISSABasicBlock; import com.ibm.wala.ssa.SSACFG.ExceptionHandlerBasicBlock; import com.ibm.wala.ssa.SSAGetCaughtExceptionInstruction; import com.ibm.wala.ssa.SSAInstruction; import com.ibm.wala.ssa.SSAPhiInstruction; import com.ibm.wala.ssa.SSAPiInstruction; import com.ibm.wala.types.TypeReference; import com.ibm.wala.util.collections.EmptyIterator; import com.ibm.wala.util.collections.HashSetFactory; import com.ibm.wala.util.collections.Iterator2Collection; import com.ibm.wala.util.collections.Iterator2Iterable; import com.ibm.wala.util.collections.NonNullSingletonIterator; import com.ibm.wala.util.collections.SimpleVector; import com.ibm.wala.util.debug.Assertions; import com.ibm.wala.util.debug.UnimplementedError; import com.ibm.wala.util.intset.BitVector; import com.ibm.wala.util.intset.IntSet; import com.ibm.wala.util.intset.MutableSparseIntSet; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.stream.Stream; /** * A view of a control flow graph where each basic block corresponds to exactly one SSA instruction * index. * * <p>Prototype: Not terribly efficient. */ public class ExplodedControlFlowGraph implements ControlFlowGraph<SSAInstruction, IExplodedBasicBlock> { private static final int ENTRY_INDEX = -1; private static final int EXIT_INDEX = -2; private final IR ir; /** * The ith element of this vector is the basic block holding instruction i. this basic block has * number i+1. */ private final SimpleVector<IExplodedBasicBlock> normalNodes = new SimpleVector<>(); private final Collection<IExplodedBasicBlock> allNodes = HashSetFactory.make(); private final IExplodedBasicBlock entry; private final IExplodedBasicBlock exit; private ExplodedControlFlowGraph(IR ir) { assert ir != null; this.ir = ir; this.entry = new ExplodedBasicBlock(ENTRY_INDEX, null); this.exit = new ExplodedBasicBlock(EXIT_INDEX, null); createNodes(); } private void createNodes() { allNodes.add(entry); allNodes.add(exit); for (ISSABasicBlock b : ir.getControlFlowGraph()) { for (int i = b.getFirstInstructionIndex(); i <= b.getLastInstructionIndex(); i++) { IExplodedBasicBlock bb = new ExplodedBasicBlock(i, b); normalNodes.set(i, bb); allNodes.add(bb); } } } public static ExplodedControlFlowGraph make(IR ir) { if (ir == null) { throw new IllegalArgumentException("ir == null"); } return new ExplodedControlFlowGraph(ir); } @Override public IExplodedBasicBlock entry() { return entry; } @Override public IExplodedBasicBlock exit() { return exit; } @Override public IExplodedBasicBlock getBlockForInstruction(int index) { return normalNodes.get(index); } @Override public BitVector getCatchBlocks() { BitVector original = ir.getControlFlowGraph().getCatchBlocks(); BitVector result = new BitVector(); for (int i = 0; i <= original.max(); i++) { if (original.get(i)) { result.set(i + 1); } } return result; } @Override public Collection<IExplodedBasicBlock> getExceptionalPredecessors(IExplodedBasicBlock bb) { ExplodedBasicBlock eb = (ExplodedBasicBlock) bb; assert eb != null; if (eb.equals(entry)) { return Collections.emptySet(); } if (eb.isExitBlock() || eb.instructionIndex == eb.original.getFirstInstructionIndex()) { List<IExplodedBasicBlock> result = new ArrayList<>(); for (ISSABasicBlock s : ir.getControlFlowGraph().getExceptionalPredecessors(eb.original)) { assert normalNodes.get(s.getLastInstructionIndex()) != null; result.add(normalNodes.get(s.getLastInstructionIndex())); } return result; } else { return Collections.emptySet(); } } @Override public List<IExplodedBasicBlock> getExceptionalSuccessors(IExplodedBasicBlock bb) { ExplodedBasicBlock eb = (ExplodedBasicBlock) bb; assert eb != null; if (eb.equals(exit)) { return Collections.emptyList(); } if (eb.isEntryBlock() || eb.instructionIndex == eb.original.getLastInstructionIndex()) { List<IExplodedBasicBlock> result = new ArrayList<>(); ISSABasicBlock orig = eb.original; if (eb.isEntryBlock() && orig == null) { orig = ir.getControlFlowGraph().entry(); } for (ISSABasicBlock s : ir.getControlFlowGraph().getExceptionalSuccessors(orig)) { if (s.equals(ir.getControlFlowGraph().exit())) { result.add(exit()); } else { assert normalNodes.get(s.getFirstInstructionIndex()) != null; result.add(normalNodes.get(s.getFirstInstructionIndex())); } } return result; } else { return Collections.emptyList(); } } @Override public SSAInstruction[] getInstructions() { return ir.getInstructions(); } @Override public IMethod getMethod() throws UnimplementedError { return ir.getMethod(); } @Override public Collection<IExplodedBasicBlock> getNormalPredecessors(IExplodedBasicBlock bb) { ExplodedBasicBlock eb = (ExplodedBasicBlock) bb; assert eb != null; if (eb.equals(entry)) { return Collections.emptySet(); } if (eb.isExitBlock() || eb.instructionIndex == eb.original.getFirstInstructionIndex()) { List<IExplodedBasicBlock> result = new ArrayList<>(); for (ISSABasicBlock s : ir.getControlFlowGraph().getNormalPredecessors(eb.original)) { if (s.equals(ir.getControlFlowGraph().entry())) { if (s.getLastInstructionIndex() >= 0) { assert normalNodes.get(s.getLastInstructionIndex()) != null; result.add(normalNodes.get(s.getLastInstructionIndex())); } else { result.add(entry()); } } else { assert normalNodes.get(s.getLastInstructionIndex()) != null; result.add(normalNodes.get(s.getLastInstructionIndex())); } } return result; } else { assert normalNodes.get(eb.instructionIndex - 1) != null; return Collections.singleton(normalNodes.get(eb.instructionIndex - 1)); } } @Override public Collection<IExplodedBasicBlock> getNormalSuccessors(IExplodedBasicBlock bb) { ExplodedBasicBlock eb = (ExplodedBasicBlock) bb; assert eb != null; if (eb.equals(exit)) { return Collections.emptySet(); } if (eb.isEntryBlock()) { return Collections.singleton(normalNodes.get(0)); } if (eb.instructionIndex == eb.original.getLastInstructionIndex()) { List<IExplodedBasicBlock> result = new ArrayList<>(); for (ISSABasicBlock s : ir.getControlFlowGraph().getNormalSuccessors(eb.original)) { if (s.equals(ir.getControlFlowGraph().exit())) { result.add(exit()); } else { assert normalNodes.get(s.getFirstInstructionIndex()) != null; result.add(normalNodes.get(s.getFirstInstructionIndex())); } } return result; } else { assert normalNodes.get(eb.instructionIndex + 1) != null; return Collections.singleton(normalNodes.get(eb.instructionIndex + 1)); } } @Override public int getProgramCounter(int index) throws UnimplementedError { return ir.getControlFlowGraph().getProgramCounter(index); } @Override public void removeNodeAndEdges(IExplodedBasicBlock N) throws UnsupportedOperationException { throw new UnsupportedOperationException(); } @Override public void addNode(IExplodedBasicBlock n) throws UnsupportedOperationException { throw new UnsupportedOperationException(); } @Override public boolean containsNode(IExplodedBasicBlock N) { return allNodes.contains(N); } @Override public int getNumberOfNodes() { return allNodes.size(); } @Override public Iterator<IExplodedBasicBlock> iterator() { return allNodes.iterator(); } @Override public Stream<IExplodedBasicBlock> stream() { return allNodes.stream(); } @Override public void removeNode(IExplodedBasicBlock n) throws UnsupportedOperationException { throw new UnsupportedOperationException(); } @Override public void addEdge(IExplodedBasicBlock src, IExplodedBasicBlock dst) throws UnsupportedOperationException { throw new UnsupportedOperationException(); } @Override public int getPredNodeCount(IExplodedBasicBlock bb) throws IllegalArgumentException { ExplodedBasicBlock eb = (ExplodedBasicBlock) bb; if (eb == null) { throw new IllegalArgumentException("eb == null"); } if (eb.isEntryBlock()) { return 0; } if (eb.isExitBlock()) { return ir.getControlFlowGraph().getPredNodeCount(ir.getControlFlowGraph().exit()); } if (eb.instructionIndex == eb.original.getFirstInstructionIndex()) { if (eb.original.isEntryBlock()) { return 1; } else { return ir.getControlFlowGraph().getPredNodeCount(eb.original); } } else { return 1; } } @Override public Iterator<IExplodedBasicBlock> getPredNodes(IExplodedBasicBlock bb) throws IllegalArgumentException { ExplodedBasicBlock eb = (ExplodedBasicBlock) bb; if (eb == null) { throw new IllegalArgumentException("eb == null"); } if (eb.isEntryBlock()) { return EmptyIterator.instance(); } ISSABasicBlock original = eb.isExitBlock() ? ir.getControlFlowGraph().exit() : eb.original; if (eb.isExitBlock() || eb.instructionIndex == eb.original.getFirstInstructionIndex()) { List<IExplodedBasicBlock> result = new ArrayList<>(); if (eb.original != null && eb.original.isEntryBlock()) { result.add(entry); } for (ISSABasicBlock s : Iterator2Iterable.make(ir.getControlFlowGraph().getPredNodes(original))) { if (s.isEntryBlock()) { // it's possible for an entry block to have instructions; in this case, add // the exploded basic block for the last instruction in the entry block if (s.getLastInstructionIndex() >= 0) { result.add(normalNodes.get(s.getLastInstructionIndex())); } else { result.add(entry); } } else { assert normalNodes.get(s.getLastInstructionIndex()) != null; result.add(normalNodes.get(s.getLastInstructionIndex())); } } return result.iterator(); } else { assert normalNodes.get(eb.instructionIndex - 1) != null; return NonNullSingletonIterator.make(normalNodes.get(eb.instructionIndex - 1)); } } @Override public int getSuccNodeCount(IExplodedBasicBlock N) throws UnimplementedError { return Iterator2Collection.toSet(getSuccNodes(N)).size(); } /** @see com.ibm.wala.util.graph.EdgeManager#getSuccNodes(java.lang.Object) */ @Override public Iterator<IExplodedBasicBlock> getSuccNodes(IExplodedBasicBlock bb) { ExplodedBasicBlock eb = (ExplodedBasicBlock) bb; assert eb != null; if (eb.isExitBlock()) { return EmptyIterator.instance(); } if (eb.isEntryBlock()) { IExplodedBasicBlock z = normalNodes.get(0); return z == null ? EmptyIterator.<IExplodedBasicBlock>instance() : NonNullSingletonIterator.make(z); } if (eb.instructionIndex == eb.original.getLastInstructionIndex()) { List<IExplodedBasicBlock> result = new ArrayList<>(); for (ISSABasicBlock s : Iterator2Iterable.make(ir.getControlFlowGraph().getSuccNodes(eb.original))) { if (s.equals(ir.getControlFlowGraph().exit())) { result.add(exit()); } else { // there can be a weird corner case where a void method without a // return statement // can have trailing empty basic blocks with no instructions. ignore // these. if (normalNodes.get(s.getFirstInstructionIndex()) != null) { result.add(normalNodes.get(s.getFirstInstructionIndex())); } } } return result.iterator(); } else { assert normalNodes.get(eb.instructionIndex + 1) != null; return NonNullSingletonIterator.make(normalNodes.get(eb.instructionIndex + 1)); } } @Override public boolean hasEdge(IExplodedBasicBlock src, IExplodedBasicBlock dst) throws UnimplementedError { for (IExplodedBasicBlock succ : Iterator2Iterable.make(getSuccNodes(src))) { if (succ == dst) { return true; } } return false; } @Override public void removeAllIncidentEdges(IExplodedBasicBlock node) throws UnsupportedOperationException { throw new UnsupportedOperationException(); } @Override public void removeEdge(IExplodedBasicBlock src, IExplodedBasicBlock dst) throws UnsupportedOperationException { throw new UnsupportedOperationException(); } @Override public void removeIncomingEdges(IExplodedBasicBlock node) throws UnsupportedOperationException { throw new UnsupportedOperationException(); } @Override public void removeOutgoingEdges(IExplodedBasicBlock node) throws UnsupportedOperationException { throw new UnsupportedOperationException(); } @Override public int getMaxNumber() { return getNumberOfNodes() - 1; } @Override public IExplodedBasicBlock getNode(int number) { if (number == 0) { return entry(); } else if (number == getNumberOfNodes() - 1) { return exit(); } else { return normalNodes.get(number - 1); } } @Override public int getNumber(IExplodedBasicBlock n) throws IllegalArgumentException { if (n == null) { throw new IllegalArgumentException("n == null"); } return n.getNumber(); } @Override public Iterator<IExplodedBasicBlock> iterateNodes(IntSet s) throws UnimplementedError { Assertions.UNREACHABLE(); return null; } @Override public IntSet getPredNodeNumbers(IExplodedBasicBlock node) { MutableSparseIntSet result = MutableSparseIntSet.makeEmpty(); for (IExplodedBasicBlock ebb : Iterator2Iterable.make(getPredNodes(node))) { result.add(getNumber(ebb)); } return result; } @Override public IntSet getSuccNodeNumbers(IExplodedBasicBlock node) throws UnimplementedError { Assertions.UNREACHABLE(); return null; } /** * A basic block with exactly one normal instruction (which may be null), corresponding to a * single instruction index in the SSA instruction array. * * <p>The block may also have phis. */ private class ExplodedBasicBlock implements IExplodedBasicBlock { private final int instructionIndex; private final ISSABasicBlock original; public ExplodedBasicBlock(int instructionIndex, ISSABasicBlock original) { this.instructionIndex = instructionIndex; this.original = original; } @SuppressWarnings("unused") public ExplodedControlFlowGraph getExplodedCFG() { return ExplodedControlFlowGraph.this; } @Override public Iterator<TypeReference> getCaughtExceptionTypes() { if (original instanceof ExceptionHandlerBasicBlock) { ExceptionHandlerBasicBlock eb = (ExceptionHandlerBasicBlock) original; return eb.getCaughtExceptionTypes(); } else { return EmptyIterator.instance(); } } @Override public int getFirstInstructionIndex() { return instructionIndex; } @Override public int getLastInstructionIndex() { return instructionIndex; } @Override public IMethod getMethod() { return ExplodedControlFlowGraph.this.getMethod(); } @Override public int getNumber() { if (isEntryBlock()) { return 0; } else if (isExitBlock()) { return getNumberOfNodes() - 1; } else { return instructionIndex + 1; } } @Override public boolean isCatchBlock() { if (original == null) { return false; } return (original.isCatchBlock() && instructionIndex == original.getFirstInstructionIndex()); } @Override public SSAGetCaughtExceptionInstruction getCatchInstruction() { if (!(original instanceof ExceptionHandlerBasicBlock)) { throw new IllegalArgumentException("block does not represent an exception handler"); } ExceptionHandlerBasicBlock e = (ExceptionHandlerBasicBlock) original; return e.getCatchInstruction(); } @Override public boolean isEntryBlock() { return instructionIndex == ENTRY_INDEX; } @Override public boolean isExitBlock() { return instructionIndex == EXIT_INDEX; } @Override public int getGraphNodeId() { return getNumber(); } @Override public void setGraphNodeId(int number) { Assertions.UNREACHABLE(); } @Override public Iterator<SSAInstruction> iterator() { if (isEntryBlock() || isExitBlock() || getInstruction() == null) { return EmptyIterator.instance(); } else { return NonNullSingletonIterator.make(getInstruction()); } } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + instructionIndex; result = prime * result + ((original == null) ? 0 : original.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 ExplodedBasicBlock other = (ExplodedBasicBlock) obj; if (instructionIndex != other.instructionIndex) return false; if (original == null) { if (other.original != null) return false; } else if (!original.equals(other.original)) return false; return true; } @Override public SSAInstruction getInstruction() { if (isEntryBlock() || isExitBlock()) { return null; } else { return ir.getInstructions()[instructionIndex]; } } @Override public SSAInstruction getLastInstruction() { if (getLastInstructionIndex() < 0) { return null; } else { return ir.getInstructions()[getLastInstructionIndex()]; } } @Override public Iterator<SSAPhiInstruction> iteratePhis() { if (isEntryBlock() || isExitBlock() || instructionIndex != original.getFirstInstructionIndex()) { return EmptyIterator.instance(); } else { return original.iteratePhis(); } } @Override public Iterator<SSAPiInstruction> iteratePis() { if (isEntryBlock() || isExitBlock() || instructionIndex != original.getLastInstructionIndex()) { return EmptyIterator.instance(); } else { return original.iteratePis(); } } @Override public String toString() { if (isEntryBlock()) { return "ExplodedBlock[" + getNumber() + "](entry:" + getMethod() + ')'; } if (isExitBlock()) { return "ExplodedBlock[" + getNumber() + "](exit:" + getMethod() + ')'; } return "ExplodedBlock[" + getNumber() + "](original:" + original + ')'; } @Override public int getOriginalNumber() { return original.getNumber(); } } @Override public String toString() { StringBuilder s = new StringBuilder(); for (IExplodedBasicBlock bb : this) { s.append("BB").append(getNumber(bb)).append('\n'); Iterator<? extends IExplodedBasicBlock> succNodes = getSuccNodes(bb); while (succNodes.hasNext()) { s.append(" -> BB").append(getNumber(succNodes.next())).append('\n'); } } return s.toString(); } public IR getIR() { return ir; } }
20,361
29.619549
99
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/ssa/analysis/IExplodedBasicBlock.java
/* * Copyright (c) 2007 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package com.ibm.wala.ssa.analysis; import com.ibm.wala.ssa.ISSABasicBlock; import com.ibm.wala.ssa.SSAGetCaughtExceptionInstruction; import com.ibm.wala.ssa.SSAInstruction; /** * A basic block with exactly one normal instruction (which may be null), corresponding to a single * instruction index in the SSA instruction array. * * <p>The block may also have phis. */ public interface IExplodedBasicBlock extends ISSABasicBlock { /** get the instruction for this block, or null if the block has no instruction */ SSAInstruction getInstruction(); /** * if this represents an exception handler block, return the corresponding {@link * SSAGetCaughtExceptionInstruction} * * @throws IllegalArgumentException if this does not represent an exception handler block */ SSAGetCaughtExceptionInstruction getCatchInstruction(); /** * get the number of the original basic block containing the instruction of this exploded block */ int getOriginalNumber(); }
1,355
32.073171
99
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/types/ClassLoaderReference.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.types; import com.ibm.wala.core.util.strings.Atom; import java.io.Serializable; /** * Defines the meta-information that identifies a class loader. This is effectively a "name" for a * class loader. */ public class ClassLoaderReference implements Serializable { /* Serial version */ private static final long serialVersionUID = -3256390509887654325L; /** Canonical name for the Java language */ public static final Atom Java = Atom.findOrCreateUnicodeAtom("Java"); /** Canonical reference to primordial class loader */ public static final ClassLoaderReference Primordial = new ClassLoaderReference(Atom.findOrCreateUnicodeAtom("Primordial"), Java, null); /** Canonical reference to extension class loader */ public static final ClassLoaderReference Extension = new ClassLoaderReference(Atom.findOrCreateUnicodeAtom("Extension"), Java, Primordial); /** Canonical reference to application class loader */ public static final ClassLoaderReference Application = new ClassLoaderReference(Atom.findOrCreateUnicodeAtom("Application"), Java, Extension); /** A String which identifies this loader */ private final Atom name; /** A String which identifies the language for this loader */ private final Atom language; /** This class loader's parent */ private final ClassLoaderReference parent; public ClassLoaderReference(Atom name, Atom language, ClassLoaderReference parent) { if (name == null) { throw new IllegalArgumentException("name is null"); } this.name = name; this.language = language; this.parent = parent; } /** @return the name of this class loader */ public Atom getName() { return name; } /** @return the name of the language this class loader belongs to */ public Atom getLanguage() { return language; } /** @return the parent of this loader in the loader hierarchy, or null if none */ public ClassLoaderReference getParent() { return parent; } /** Note: names for class loader references must be unique. */ @Override public boolean equals(Object obj) { if (obj == null) { return false; } if (!getClass().equals(obj.getClass())) { return false; } else { ClassLoaderReference o = (ClassLoaderReference) obj; return name.equals(o.name); } } @Override public int hashCode() { return name.hashCode(); } @Override public String toString() { return name + " classloader\n"; } }
2,876
28.659794
98
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/types/Descriptor.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.types; import com.ibm.wala.classLoader.Language; import com.ibm.wala.core.util.strings.ImmutableByteArray; import com.ibm.wala.core.util.strings.StringStuff; import com.ibm.wala.core.util.strings.UTF8Convert; import com.ibm.wala.util.collections.HashMapFactory; import java.util.Map; /** * A method descriptor; something like: (Ljava/langString;)Ljava/lang/Class; * * <p>Descriptors are canonical */ public final class Descriptor { /** A mapping from Key -&gt; Descriptor */ private static final Map<Key, Descriptor> map = HashMapFactory.make(); /** key holds the logical value of this descriptor */ private final Key key; /** * @param parameters the parameters for a descriptor * @param returnType the return type * @return the canonical representative for this descriptor value */ public static Descriptor findOrCreate(TypeName[] parameters, TypeName returnType) { if (returnType == null) { throw new IllegalArgumentException("null returnType"); } if (parameters != null && parameters.length == 0) { parameters = null; } Key k = new Key(returnType, parameters); Descriptor result = map.get(k); if (result == null) { result = new Descriptor(k); map.put(k, result); } return result; } /** * @param b a byte array holding the string representation of this descriptor * @return the canonical representative for this descriptor value */ public static Descriptor findOrCreate(Language l, ImmutableByteArray b) throws IllegalArgumentException { TypeName returnType = StringStuff.parseForReturnTypeName(l, b); TypeName[] parameters = StringStuff.parseForParameterNames(l, b); Key k = new Key(returnType, parameters); Descriptor result = map.get(k); if (result == null) { result = new Descriptor(k); map.put(k, result); } return result; } public static Descriptor findOrCreate(ImmutableByteArray b) throws IllegalArgumentException { return findOrCreate(Language.JAVA, b); } /** * @param s string representation of this descriptor * @return the canonical representative for this descriptor value */ public static Descriptor findOrCreateUTF8(String s) throws IllegalArgumentException { return findOrCreateUTF8(Language.JAVA, s); } /** * @param s string representation of this descriptor * @return the canonical representative for this descriptor value */ public static Descriptor findOrCreateUTF8(Language l, String s) throws IllegalArgumentException { byte[] b = UTF8Convert.toUTF8(s); return findOrCreate(l, new ImmutableByteArray(b)); } /** @param key "value" of this descriptor */ private Descriptor(Key key) { this.key = key; } @Override public boolean equals(Object obj) { return this == obj; } @Override public int hashCode() { return key.hashCode(); } @Override public String toString() { return key.toString(); } /** @return a unicode string representation of this descriptor */ public String toUnicodeString() { return key.toUnicodeString(); } /** @return the name of the return type of this descriptor */ public TypeName getReturnType() { return key.returnType; } /** @return the type names for the parameters in this descriptor */ public TypeName[] getParameters() { return key.parameters; } /** @return number of parameters in this descriptor */ public int getNumberOfParameters() { return key.parameters == null ? 0 : key.parameters.length; } /** value that defines a descriptor: used to canonicalize instances */ private static class Key { private final TypeName returnType; private final TypeName[] parameters; private final int hashCode; // cached for efficiency Key(TypeName returnType, TypeName[] parameters) { this.returnType = returnType; this.parameters = parameters; if (parameters != null) { assert parameters.length > 0; } hashCode = computeHashCode(); } @Override public int hashCode() { return hashCode; } public int computeHashCode() { int result = returnType.hashCode() * 5309; if (parameters != null) { for (int i = 0; i < parameters.length; i++) { result += parameters[i].hashCode() * (5323 ^ i); } } return result; } @Override public boolean equals(Object obj) { assert obj instanceof Key; Key other = (Key) obj; if (!returnType.equals(other.returnType)) { return false; } if (parameters == null) { return (other.parameters == null) ? true : false; } if (other.parameters == null) { return false; } if (parameters.length != other.parameters.length) { return false; } for (int i = 0; i < parameters.length; i++) { if (!parameters[i].equals(other.parameters[i])) { return false; } } return true; } @Override public String toString() { StringBuilder result = new StringBuilder(); result.append('('); if (parameters != null) { for (TypeName p : parameters) { result.append(p); appendSemicolonIfNeeded(result, p); } } result.append(')'); result.append(returnType); appendSemicolonIfNeeded(result, returnType); return result.toString(); } public String toUnicodeString() { StringBuilder result = new StringBuilder(); result.append('('); if (parameters != null) { for (TypeName p : parameters) { result.append(p.toUnicodeString()); appendSemicolonIfNeeded(result, p); } } result.append(')'); result.append(returnType); appendSemicolonIfNeeded(result, returnType); return result.toString(); } private static void appendSemicolonIfNeeded(StringBuilder result, TypeName p) { if (p.isArrayType()) { TypeName e = p.getInnermostElementType(); String x = e.toUnicodeString(); if (x.startsWith("L") || x.startsWith("P")) { result.append(';'); } } else { String x = p.toUnicodeString(); if (x.startsWith("L") || x.startsWith("P")) { result.append(';'); } } } } }
6,752
27.73617
99
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/types/FieldReference.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.types; import com.ibm.wala.core.util.shrike.ShrikeUtil; import com.ibm.wala.core.util.strings.Atom; import com.ibm.wala.util.collections.HashMapFactory; import com.ibm.wala.util.debug.Assertions; import com.ibm.wala.util.debug.UnimplementedError; import java.util.HashMap; /** A class to represent the reference in a class file to a field. */ public final class FieldReference extends MemberReference { private static final boolean DEBUG = false; /** Used to canonicalize MemberReferences a mapping from Key -&gt; MemberReference */ private static final HashMap<Key, FieldReference> dictionary = HashMapFactory.make(); private final TypeReference fieldType; @Override public String getSignature() { return getDeclaringClass().getName() + "." + getName() + ' ' + getFieldType().getName(); } /** * Find or create the canonical MemberReference instance for the given tuple. * * @param mn the name of the member */ public static synchronized FieldReference findOrCreate( TypeReference tref, Atom mn, TypeReference fieldType) { if (tref == null) { throw new IllegalArgumentException("null tref"); } Key key = new Key(tref, mn, fieldType); FieldReference val = dictionary.get(key); if (val != null) { return val; } val = new FieldReference(key, fieldType); dictionary.put(key, val); return val; } /** Find or create the canonical MemberReference instance for the given tuple. */ public static FieldReference findOrCreate( ClassLoaderReference loader, String classType, String fieldName, String fieldType) throws IllegalArgumentException { TypeReference c = ShrikeUtil.makeTypeReference(loader, classType); TypeReference ft = ShrikeUtil.makeTypeReference(loader, fieldType); Atom name = Atom.findOrCreateUnicodeAtom(fieldName); return findOrCreate(c, name, ft); } private FieldReference(Key key, TypeReference fieldType) { super(key.type, key.name, key.hashCode()); this.fieldType = fieldType; if (DEBUG) { if (getName().toString().indexOf('.') > -1) throw new UnimplementedError(); if (fieldType.toString().indexOf('.') > -1) Assertions.UNREACHABLE("Field name: " + fieldType); if (getName().toString().length() == 0) throw new UnimplementedError(); if (fieldType.toString().length() == 0) throw new UnimplementedError(); } } /** @return the descriptor component of this member reference */ public TypeReference getFieldType() { return fieldType; } @Override public String toString() { return "< " + getDeclaringClass().getClassLoader().getName() + ", " + getDeclaringClass().getName() + ", " + getName() + ", " + fieldType + " >"; } /** An identifier/selector for fields. */ protected static class Key { final TypeReference type; final Atom name; private final TypeReference fieldType; Key(TypeReference type, Atom name, TypeReference fieldType) { this.type = type; this.name = name; this.fieldType = fieldType; } @Override public final int hashCode() { return 7487 * type.hashCode() + name.hashCode(); } @Override public final boolean equals(Object other) { assert other != null && this.getClass().equals(other.getClass()); Key that = (Key) other; return type.equals(that.type) && name.equals(that.name) && fieldType.equals(that.fieldType); } } }
3,911
30.296
98
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/types/MemberReference.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.types; import com.ibm.wala.core.util.strings.Atom; /** Abstract superclass of {@link MethodReference} and {@link FieldReference} */ public abstract class MemberReference { /** The type that declares this member */ private final TypeReference declaringClass; /** The member name */ private final Atom name; /** Cached hash code for efficiency */ private final int hash; protected MemberReference(TypeReference type, Atom name, int hash) { this.declaringClass = type; this.name = name; this.hash = hash; } /** @return the member name component of this member reference */ public final Atom getName() { return name; } public abstract String getSignature(); @Override public final int hashCode() { return hash; } @Override public final boolean equals(Object other) { // These are canonical return this == other; } /** @return the type that declared this member */ public TypeReference getDeclaringClass() { if (declaringClass == null) { // fail eagerly throw new NullPointerException(); } return declaringClass; } }
1,513
24.233333
80
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/types/MethodReference.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.types; import com.ibm.wala.classLoader.Language; import com.ibm.wala.core.util.shrike.ShrikeUtil; import com.ibm.wala.core.util.strings.Atom; import com.ibm.wala.util.collections.HashMapFactory; import java.util.HashMap; /** A class to represent the reference in a class file to a method. */ public final class MethodReference extends MemberReference { /** Used to canonicalize MethodReferences a mapping from Key -&gt; MethodReference */ private static final HashMap<Key, MethodReference> dictionary = HashMapFactory.make(); public static final Atom newInstanceAtom = Atom.findOrCreateUnicodeAtom("newInstance"); private static final Descriptor newInstanceDesc = Descriptor.findOrCreateUTF8(Language.JAVA, "()Ljava/lang/Object;"); public static final MethodReference JavaLangClassNewInstance = findOrCreate(TypeReference.JavaLangClass, newInstanceAtom, newInstanceDesc); private static final Atom ctorNewInstanceAtom = Atom.findOrCreateUnicodeAtom("newInstance"); private static final Descriptor ctorNewInstanceDesc = Descriptor.findOrCreateUTF8(Language.JAVA, "([Ljava/lang/Object;)Ljava/lang/Object;"); public static final MemberReference JavaLangReflectCtorNewInstance = findOrCreate( TypeReference.JavaLangReflectConstructor, ctorNewInstanceAtom, ctorNewInstanceDesc); public static final Atom forNameAtom = Atom.findOrCreateUnicodeAtom("forName"); private static final Descriptor forNameDesc = Descriptor.findOrCreateUTF8(Language.JAVA, "(Ljava/lang/String;)Ljava/lang/Class;"); public static final MethodReference JavaLangClassForName = findOrCreate(TypeReference.JavaLangClass, forNameAtom, forNameDesc); public static final Atom initAtom = Atom.findOrCreateUnicodeAtom("<init>"); public static final Descriptor defaultInitDesc = Descriptor.findOrCreateUTF8(Language.JAVA, "()V"); public static final Selector initSelector = new Selector(initAtom, defaultInitDesc); public static final Atom clinitName = Atom.findOrCreateUnicodeAtom("<clinit>"); public static final Selector clinitSelector = new Selector(clinitName, defaultInitDesc); public static final Atom finalizeName = Atom.findOrCreateUnicodeAtom("finalize"); public static final Selector finalizeSelector = new Selector(finalizeName, defaultInitDesc); public static final Atom runAtom = Atom.findOrCreateUnicodeAtom("run"); public static final Descriptor runDesc = Descriptor.findOrCreateUTF8(Language.JAVA, "()Ljava/lang/Object;"); public static final Selector runSelector = new Selector(runAtom, runDesc); public static final Atom equalsAtom = Atom.findOrCreateUnicodeAtom("equals"); public static final Descriptor equalsDesc = Descriptor.findOrCreateUTF8(Language.JAVA, "(Ljava/lang/Object;)Z"); public static final Selector equalsSelector = new Selector(equalsAtom, equalsDesc); public static final MethodReference lambdaMetafactory = findOrCreate( TypeReference.LambdaMetaFactory, Atom.findOrCreateUnicodeAtom("metafactory"), Descriptor.findOrCreateUTF8( "(Ljava/lang/invoke/MethodHandles$Lookup;Ljava/lang/String;Ljava/lang/invoke/MethodType;Ljava/lang/invoke/MethodType;Ljava/lang/invoke/MethodHandle;Ljava/lang/invoke/MethodType;)Ljava/lang/invoke/CallSite;")); /** types of parameters to this method. */ private final TypeReference[] parameterTypes; /** return type. */ private final TypeReference returnType; /** Name and descriptor */ private final Selector selector; /** * Find or create the canonical MethodReference instance for the given tuple. * * @param mn the name of the member * @param md the descriptor of the member */ public static synchronized MethodReference findOrCreate( TypeReference tref, Atom mn, Descriptor md) { if (tref == null) { throw new IllegalArgumentException("null tref"); } Key key = new Key(tref, mn, md); MethodReference val = dictionary.get(key); if (val != null) return val; val = new MethodReference(key); dictionary.put(key, val); return val; } /** * Find or create the canonical MethodReference instance for the given tuple. * * @param tref the type reference * @param selector the selector for the method * @throws IllegalArgumentException if selector is null */ public static synchronized MethodReference findOrCreate(TypeReference tref, Selector selector) { if (selector == null) { throw new IllegalArgumentException("selector is null"); } return findOrCreate(tref, selector.getName(), selector.getDescriptor()); } public static MethodReference findOrCreate(TypeReference t, String methodName, String descriptor) throws IllegalArgumentException { return findOrCreate(Language.JAVA, t, methodName, descriptor); } public static MethodReference findOrCreate( Language l, TypeReference t, String methodName, String descriptor) throws IllegalArgumentException { Descriptor d = Descriptor.findOrCreateUTF8(l, descriptor); return findOrCreate(t, Atom.findOrCreateUnicodeAtom(methodName), d); } public static MethodReference findOrCreate( ClassLoaderReference loader, String methodClass, String methodName, String methodSignature) throws IllegalArgumentException { return findOrCreate(Language.JAVA, loader, methodClass, methodName, methodSignature); } public static MethodReference findOrCreate( Language l, ClassLoaderReference loader, String methodClass, String methodName, String methodSignature) throws IllegalArgumentException { TypeReference t = ShrikeUtil.makeTypeReference(loader, methodClass); Atom name = Atom.findOrCreateUnicodeAtom(methodName); Descriptor d = Descriptor.findOrCreateUTF8(l, methodSignature); return findOrCreate(t, name, d); } /** @return the descriptor component of this member reference */ public Descriptor getDescriptor() { return selector.getDescriptor(); } @Override public String toString() { return "< " + getDeclaringClass().getClassLoader().getName() + ", " + getDeclaringClass().getName() + ", " + selector + " >"; } MethodReference(Key key) { super(key.type, key.name, key.hashCode()); selector = new Selector(key.name, key.descriptor); TypeName[] parameterNames = key.descriptor.getParameters(); if (parameterNames != null) { parameterTypes = new TypeReference[parameterNames.length]; } else { parameterTypes = null; } ClassLoaderReference loader = getDeclaringClass().getClassLoader(); if (parameterNames != null) { for (int i = 0; i < parameterNames.length; i++) { parameterTypes[i] = TypeReference.findOrCreate(loader, parameterNames[i]); } } TypeName r = key.descriptor.getReturnType(); returnType = TypeReference.findOrCreate(getDeclaringClass().getClassLoader(), r); } /** @return return type of the method */ public TypeReference getReturnType() { return returnType; } /** @return ith parameter to the method. This does NOT include the implicit "this" pointer. */ public TypeReference getParameterType(int i) throws IllegalArgumentException { if (parameterTypes == null || i >= parameterTypes.length) { throw new IllegalArgumentException("illegal parameter number " + i + " for " + this); } return parameterTypes[i]; } public boolean isInit() { return getName().equals(MethodReference.initAtom); } /** * @return something like: * com.foo.bar.createLargeOrder(IILjava/lang/String;Ljava/sql/Date;)Ljava/lang/Integer; */ @Override public String getSignature() { // TODO: check that we're not calling this often. String s = getDeclaringClass().getName().toString().substring(1).replace('/', '.') + '.' + getName() + getDescriptor(); return s; } /** * @return something like: * createLargeOrder(IILjava.lang.String;SLjava.sql.Date;)Ljava.lang.Integer; */ public Selector getSelector() { return selector; } /** This method does NOT include the implicit "this" parameter */ public int getNumberOfParameters() { return parameterTypes == null ? 0 : parameterTypes.length; } /** An identifier/selector for methods. */ protected static class Key { private final TypeReference type; private final Atom name; private final Descriptor descriptor; Key(TypeReference type, Atom name, Descriptor descriptor) { this.type = type; this.name = name; this.descriptor = descriptor; } @Override public final int hashCode() { return 7001 * type.hashCode() + 7013 * name.hashCode() + descriptor.hashCode(); } @Override public final boolean equals(Object other) { assert other != null && this.getClass().equals(other.getClass()); Key that = (Key) other; return type.equals(that.type) && name.equals(that.name) && descriptor.equals(that.descriptor); } } }
9,524
34.541045
223
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/types/Selector.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.types; import com.ibm.wala.classLoader.Language; import com.ibm.wala.core.util.strings.Atom; /** * A method selector; something like: foo(Ljava/lang/String;)Ljava/lang/Class; * * <p>TODO: Canonicalize these? */ public final class Selector { private final Atom name; private final Descriptor descriptor; public static Selector make(String selectorStr) { return make(Language.JAVA, selectorStr); } public static Selector make(Language l, String selectorStr) { if (selectorStr == null) { throw new IllegalArgumentException("null selectorStr"); } try { String methodName = selectorStr.substring(0, selectorStr.indexOf('(')); String desc = selectorStr.substring(selectorStr.indexOf('(')); return new Selector( Atom.findOrCreateUnicodeAtom(methodName), Descriptor.findOrCreateUTF8(l, desc)); } catch (StringIndexOutOfBoundsException e) { throw new IllegalArgumentException("invalid selectorStr: " + selectorStr, e); } } public Selector(Atom name, Descriptor descriptor) { this.name = name; this.descriptor = descriptor; if (name == null) { throw new IllegalArgumentException("null name"); } if (descriptor == null) { throw new IllegalArgumentException("null descriptor"); } } @Override public boolean equals(Object obj) { // using instanceof is OK because Selector is final if (obj instanceof Selector) { Selector other = (Selector) obj; return name.equals(other.name) && descriptor.equals(other.descriptor); } else { return false; } } @Override public int hashCode() { return 19 * name.hashCode() + descriptor.hashCode(); } @Override public String toString() { return name.toString() + descriptor; } public Descriptor getDescriptor() { return descriptor; } public Atom getName() { return name; } }
2,297
26.035294
90
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/types/TypeName.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.types; import com.ibm.wala.core.util.strings.Atom; import com.ibm.wala.core.util.strings.ImmutableByteArray; import com.ibm.wala.core.util.strings.StringStuff; import com.ibm.wala.util.collections.HashMapFactory; import com.ibm.wala.util.debug.Assertions; import java.io.Serializable; import java.io.UTFDataFormatException; import java.util.Map; /** * We've introduced this class to canonicalize Atoms that represent package names. * * <p>NB: All package names should use '/' and not '.' as a separator. eg. Ljava/lang/Class */ public final class TypeName implements Serializable { public static final byte ArrayMask = 0x01; public static final byte PointerMask = 0x02; public static final byte ReferenceMask = 0x03; public static final byte PrimitiveMask = 0x04; public static final byte ElementMask = 0x07; public static final byte ElementBits = 3; /* Serial version */ private static final long serialVersionUID = -3256390509887654326L; /** canonical mapping from TypeNameKey -&gt; TypeName */ private static final Map<TypeNameKey, TypeName> map = HashMapFactory.make(); private static synchronized TypeName findOrCreate(TypeNameKey t) { TypeName result = map.get(t); if (result == null) { result = new TypeName(t); map.put(t, result); } return result; } /** The key object holds all the information about a type name */ private final TypeNameKey key; public static TypeName findOrCreate(ImmutableByteArray name, int start, int length) throws IllegalArgumentException { Atom className = Atom.findOrCreate(StringStuff.parseForClass(name, start, length)); ImmutableByteArray p = StringStuff.parseForPackage(name, start, length); Atom packageName = (p == null) ? null : Atom.findOrCreate(p); int dim = StringStuff.parseForArrayDimensionality(name, start, length); boolean innermostPrimitive = StringStuff.classIsPrimitive(name, start, length); if (innermostPrimitive) { if (dim == 0) { dim = -1; } else { dim <<= ElementBits; dim |= PrimitiveMask; } } TypeNameKey t = new TypeNameKey(packageName, className, dim); return findOrCreate(t); } public static TypeName findOrCreate(ImmutableByteArray name) throws IllegalArgumentException { if (name == null) { throw new IllegalArgumentException("name is null"); } return findOrCreate(name, 0, name.length()); } public static TypeName findOrCreate(String name) throws IllegalArgumentException { ImmutableByteArray b = ImmutableByteArray.make(name); return findOrCreate(b); } public static TypeName findOrCreateClass(Atom packageName, Atom className) { if (packageName == null) { throw new IllegalArgumentException("null packageName"); } if (className == null) { throw new IllegalArgumentException("null className"); } TypeNameKey T = new TypeNameKey(packageName, className, 0); return findOrCreate(T); } public static TypeName findOrCreate(Atom packageName, Atom className, int dim) { TypeNameKey T = new TypeNameKey(packageName, className, dim); return findOrCreate(T); } /** This should be the only constructor */ private TypeName(TypeNameKey key) { this.key = key; } @Override public boolean equals(Object obj) { return this == obj; } @Override public int hashCode() { return key.hashCode(); } @Override public String toString() { return key.toString(); } public String toUnicodeString() { return key.toUnicodeString(); } /** * @param s a String like Ljava/lang/Object * @return the corresponding TypeName * @throws IllegalArgumentException if s is null */ public static TypeName string2TypeName(String s) throws IllegalArgumentException { if (s == null) { throw new IllegalArgumentException("s is null"); } byte[] val = s.getBytes(); return findOrCreate(new ImmutableByteArray(val)); } public static TypeName findOrCreateClassName(String packageName, String className) { Atom p = Atom.findOrCreateUnicodeAtom(packageName); Atom c = Atom.findOrCreateUnicodeAtom(className); return findOrCreateClass(p, c); } /** @return the name of the array element type for an array */ public TypeName parseForArrayElementName() { int newDim; if ((key.dim & ElementMask) == PrimitiveMask) { int tmpDim = key.dim >> (2 * ElementBits); if (tmpDim == 0) { newDim = -1; } else { newDim = (tmpDim << ElementBits) | PrimitiveMask; } } else { newDim = key.dim >> ElementBits; } return findOrCreate(key.packageName, key.className, newDim); } /** @return a type name that represents an array of this element type */ private TypeName getDerivedTypeForElementType(byte mask) { int newDim; if (key.dim == -1) { newDim = mask << ElementBits | PrimitiveMask; } else if ((key.dim & ElementMask) == PrimitiveMask) { newDim = (((key.dim & ~ElementMask) | mask) << ElementBits) | PrimitiveMask; } else { newDim = key.dim << ElementBits | mask; } return findOrCreate(key.packageName, key.className, newDim); } public TypeName getArrayTypeForElementType() { return getDerivedTypeForElementType(ArrayMask); } public TypeName getPointerTypeForElementType() { return getDerivedTypeForElementType(PointerMask); } public TypeName getReferenceTypeForElementType() { return getDerivedTypeForElementType(ReferenceMask); } /** * @return the dimensionality of the type. By convention, class types have dimensionality 0, * primitives -1, and arrays the number of [ in their descriptor. */ public int getDerivedMask() { return key.dim; } /** Does 'this' refer to a class? */ public boolean isClassType() { return key.dim == 0; } /** Does 'this' refer to an array? */ public boolean isArrayType() { return key.dim > 0; } /** Does 'this' refer to a primitive type */ public boolean isPrimitiveType() { return key.dim == -1; } /** Return the innermost element type reference for an array */ public TypeName getInnermostElementType() { short newDim = ((key.dim & ElementMask) == PrimitiveMask) ? (short) -1 : 0; return findOrCreate(key.packageName, key.className, newDim); } /** * A key into the dictionary; this is just like a type name, but uses value equality instead of * object equality. */ private static final class TypeNameKey implements Serializable { private static final long serialVersionUID = -8284030936836318929L; /** The package, like "java/lang". null means the unnamed package. */ private final Atom packageName; /** The class name, like "Object" or "Z" */ private final Atom className; /** * Dimensionality: -1 => primitive 0 => class >0 => mask of levels of array, reference, pointer * * <p>When the mask is &gt; 0, it represents levels of type qualifiers (in C terminology) for * array, reference and pointer types. There is also a special mask for when the innermost type * is a primitive. The mask is a bitfield laid out in inverse dimension order. * * <p>For instance, a single-dimension array is simply the value ArrayMask, padded with leading * zeros. A single-dimension array of primitives is ArrayMask<<ElementBits | PrimitiveMask. An * array of pointers to objects would be (ArrayMask<<ElementBits) | PointerMask; an array of * pointers to a primitive type would have the primitive mask on the end: * ((ArrayMask<<ElementBits) | PointerMask)<<ElementBits | PrimitiveMask */ private final int dim; /** This should be the only constructor */ private TypeNameKey(Atom packageName, Atom className, int dim) { this.packageName = packageName; this.className = className; this.dim = dim; } @Override public boolean equals(Object obj) { if (obj instanceof TypeNameKey) { TypeNameKey other = (TypeNameKey) obj; return className == other.className && packageName == other.packageName && dim == other.dim; } else { return false; } } /** TODO: cache for efficiency? */ @Override public int hashCode() { int result = className.hashCode() * 5009 + dim * 5011; if (packageName != null) { result += packageName.hashCode(); } return result; } @Override public String toString() { StringBuilder result = new StringBuilder(); toStringPrefix(result); if (packageName != null) { result.append(packageName); result.append('/'); } result.append(className.toString()); return result.toString(); } private void toStringPrefix(StringBuilder result) { boolean isPrimitive = (dim == -1) || (dim & ElementMask) == PrimitiveMask; if (dim != -1) { for (int d = (dim & ElementMask) == PrimitiveMask ? dim >> ElementBits : dim; d != 0; d >>= ElementBits) { final int masked = d & ElementMask; switch (masked) { case ArrayMask: result.append('['); break; case PointerMask: result.append('*'); break; case ReferenceMask: result.append('&'); break; default: throw new UnsupportedOperationException( "unexpected masked type-name component " + masked); } } } if (!isPrimitive) { result.append('L'); } else if (packageName != null && isPrimitive) { result.append('P'); } } public String toUnicodeString() { try { StringBuilder result = new StringBuilder(); toStringPrefix(result); if (packageName != null) { result.append(packageName.toUnicodeString()); result.append('/'); } result.append(className.toUnicodeString()); return result.toString(); } catch (UTFDataFormatException e) { e.printStackTrace(); Assertions.UNREACHABLE(); return null; } } } /** @return the Atom naming the package for this type. */ public Atom getPackage() { return key.packageName; } /** @return the Atom naming the class for this type (without package) */ public Atom getClassName() { return key.className; } }
10,899
30.412104
100
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/types/TypeReference.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.types; 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.util.collections.HashMapFactory; import java.io.Serializable; import java.util.Map; /** * A class to represent the reference in a class file to some type (class, primitive or array). A * type reference is uniquely defined by * * <ul> * <li>an initiating class loader * <li>a type name * </ul> * * Resolving a TypeReference to a Type can be an expensive operation. Therefore we canonicalize * TypeReference instances and cache the result of resolution. */ public final class TypeReference implements Serializable { /* Serial version */ private static final long serialVersionUID = -3256390509887654327L; /* * NOTE: initialisation order is important! * * <p>TypeReferences are canonical. */ /** Used for fast access to primitives. Primitives appear in the main dictionary also. */ private static final Map<TypeName, TypeReference> primitiveMap = HashMapFactory.make(); /** Used to canonicalize TypeReferences. */ private static final Map<Key, TypeReference> dictionary = HashMapFactory.make(); /* * Primitive Dispatch * */ public static final TypeName BooleanName = TypeName.string2TypeName("Z"); public static final byte BooleanTypeCode = 'Z'; public static final TypeReference Boolean = makePrimitive(BooleanName); public static final TypeName ByteName = TypeName.string2TypeName("B"); public static final byte ByteTypeCode = 'B'; public static final TypeReference Byte = makePrimitive(ByteName); public static final TypeName CharName = TypeName.string2TypeName("C"); public static final byte CharTypeCode = 'C'; public static final TypeReference Char = makePrimitive(CharName); public static final TypeName DoubleName = TypeName.string2TypeName("D"); public static final byte DoubleTypeCode = 'D'; public static final TypeReference Double = makePrimitive(DoubleName); public static final TypeName FloatName = TypeName.string2TypeName("F"); public static final byte FloatTypeCode = 'F'; public static final TypeReference Float = makePrimitive(FloatName); public static final TypeName IntName = TypeName.string2TypeName("I"); public static final byte IntTypeCode = 'I'; public static final TypeReference Int = makePrimitive(IntName); public static final TypeName LongName = TypeName.string2TypeName("J"); public static final byte LongTypeCode = 'J'; public static final TypeReference Long = makePrimitive(LongName); public static final TypeName ShortName = TypeName.string2TypeName("S"); public static final byte ShortTypeCode = 'S'; public static final TypeReference Short = makePrimitive(ShortName); public static final TypeName VoidName = TypeName.string2TypeName("V"); public static final byte VoidTypeCode = 'V'; public static final TypeReference Void = makePrimitive(VoidName); public static final byte OtherPrimitiveTypeCode = 'P'; /* * Primitive Array Dispatch * */ public static final TypeReference BooleanArray = findOrCreateArrayOf(Boolean); public static final TypeReference ByteArray = findOrCreateArrayOf(Byte); public static final TypeReference CharArray = findOrCreateArrayOf(Char); public static final TypeReference DoubleArray = findOrCreateArrayOf(Double); public static final TypeReference FloatArray = findOrCreateArrayOf(Float); public static final TypeReference IntArray = findOrCreateArrayOf(Int); public static final TypeReference LongArray = findOrCreateArrayOf(Long); public static final TypeReference ShortArray = findOrCreateArrayOf(Short); /* * Special object types * */ private static final TypeName JavaLangArithmeticExceptionName = TypeName.string2TypeName("Ljava/lang/ArithmeticException"); public static final TypeReference JavaLangArithmeticException = findOrCreate(ClassLoaderReference.Primordial, JavaLangArithmeticExceptionName); private static final TypeName JavaLangArrayStoreExceptionName = TypeName.string2TypeName("Ljava/lang/ArrayStoreException"); public static final TypeReference JavaLangArrayStoreException = findOrCreate(ClassLoaderReference.Primordial, JavaLangArrayStoreExceptionName); private static final TypeName JavaLangArrayIndexOutOfBoundsExceptionName = TypeName.string2TypeName("Ljava/lang/ArrayIndexOutOfBoundsException"); public static final TypeReference JavaLangArrayIndexOutOfBoundsException = findOrCreate(ClassLoaderReference.Primordial, JavaLangArrayIndexOutOfBoundsExceptionName); private static final TypeName JavaLangClassName = TypeName.string2TypeName("Ljava/lang/Class"); public static final TypeReference JavaLangClass = findOrCreate(ClassLoaderReference.Primordial, JavaLangClassName); private static final TypeName JavaLangInvokeMethodHandleName = TypeName.string2TypeName("Ljava/lang/invoke/MethodHandle"); public static final TypeReference JavaLangInvokeMethodHandle = findOrCreate(ClassLoaderReference.Primordial, JavaLangInvokeMethodHandleName); private static final TypeName JavaLangInvokeMethodHandlesLookupName = TypeName.string2TypeName("Ljava/lang/invoke/MethodHandles$Lookup"); public static final TypeReference JavaLangInvokeMethodHandlesLookup = findOrCreate(ClassLoaderReference.Primordial, JavaLangInvokeMethodHandlesLookupName); private static final TypeName JavaLangInvokeMethodTypeName = TypeName.string2TypeName("Ljava/lang/invoke/MethodType"); public static final TypeReference JavaLangInvokeMethodType = findOrCreate(ClassLoaderReference.Primordial, JavaLangInvokeMethodTypeName); private static final TypeName JavaLangClassCastExceptionName = TypeName.string2TypeName("Ljava/lang/ClassCastException"); public static final TypeReference JavaLangClassCastException = findOrCreate(ClassLoaderReference.Primordial, JavaLangClassCastExceptionName); private static final TypeName JavaLangComparableName = TypeName.string2TypeName("Ljava/lang/Comparable"); public static final TypeReference JavaLangComparable = findOrCreate(ClassLoaderReference.Primordial, JavaLangComparableName); private static final TypeName JavaLangReflectConstructorName = TypeName.string2TypeName("Ljava/lang/reflect/Constructor"); public static final TypeReference JavaLangReflectConstructor = findOrCreate(ClassLoaderReference.Primordial, JavaLangReflectConstructorName); private static final TypeName JavaLangReflectMethodName = TypeName.string2TypeName("Ljava/lang/reflect/Method"); public static final TypeReference JavaLangReflectMethod = findOrCreate(ClassLoaderReference.Primordial, JavaLangReflectMethodName); private static final TypeName JavaLangEnumName = TypeName.string2TypeName("Ljava/lang/Enum"); public static final TypeReference JavaLangEnum = findOrCreate(ClassLoaderReference.Primordial, JavaLangEnumName); private static final TypeName JavaLangErrorName = TypeName.string2TypeName("Ljava/lang/Error"); public static final TypeReference JavaLangError = findOrCreate(ClassLoaderReference.Primordial, JavaLangErrorName); private static final TypeName JavaLangExceptionName = TypeName.string2TypeName("Ljava/lang/Exception"); public static final TypeReference JavaLangException = findOrCreate(ClassLoaderReference.Primordial, JavaLangExceptionName); private static final TypeName JavaLangNegativeArraySizeExceptionName = TypeName.string2TypeName("Ljava/lang/NegativeArraySizeException"); public static final TypeReference JavaLangNegativeArraySizeException = findOrCreate(ClassLoaderReference.Primordial, JavaLangNegativeArraySizeExceptionName); private static final TypeName JavaLangNullPointerExceptionName = TypeName.string2TypeName("Ljava/lang/NullPointerException"); public static final TypeReference JavaLangNullPointerException = findOrCreate(ClassLoaderReference.Primordial, JavaLangNullPointerExceptionName); private static final TypeName JavaLangRuntimeExceptionName = TypeName.string2TypeName("Ljava/lang/RuntimeException"); public static final TypeReference JavaLangRuntimeException = findOrCreate(ClassLoaderReference.Primordial, JavaLangRuntimeExceptionName); private static final TypeName JavaLangClassNotFoundExceptionName = TypeName.string2TypeName("Ljava/lang/ClassNotFoundException"); public static final TypeReference JavaLangClassNotFoundException = findOrCreate(ClassLoaderReference.Primordial, JavaLangClassNotFoundExceptionName); private static final TypeName JavaLangOutOfMemoryErrorName = TypeName.string2TypeName("Ljava/lang/OutOfMemoryError"); public static final TypeReference JavaLangOutOfMemoryError = findOrCreate(ClassLoaderReference.Primordial, JavaLangOutOfMemoryErrorName); private static final TypeName JavaLangExceptionInInitializerErrorName = TypeName.string2TypeName("Ljava/lang/ExceptionInInitializerError"); public static final TypeReference JavaLangExceptionInInitializerError = findOrCreate(ClassLoaderReference.Primordial, JavaLangExceptionInInitializerErrorName); private static final TypeName JavaLangObjectName = TypeName.string2TypeName("Ljava/lang/Object"); public static final TypeReference JavaLangObject = findOrCreate(ClassLoaderReference.Primordial, JavaLangObjectName); private static final TypeName JavaLangStackTraceElementName = TypeName.string2TypeName("Ljava/lang/StackTraceElement"); public static final TypeReference JavaLangStackTraceElement = findOrCreate(ClassLoaderReference.Primordial, JavaLangStackTraceElementName); private static final TypeName JavaLangStringName = TypeName.string2TypeName("Ljava/lang/String"); public static final TypeReference JavaLangString = findOrCreate(ClassLoaderReference.Primordial, JavaLangStringName); private static final TypeName JavaLangStringBufferName = TypeName.string2TypeName("Ljava/lang/StringBuffer"); public static final TypeReference JavaLangStringBuffer = findOrCreate(ClassLoaderReference.Primordial, JavaLangStringBufferName); private static final TypeName JavaLangStringBuilderName = TypeName.string2TypeName("Ljava/lang/StringBuilder"); public static final TypeReference JavaLangStringBuilder = findOrCreate(ClassLoaderReference.Primordial, JavaLangStringBuilderName); private static final TypeName JavaLangThreadName = TypeName.string2TypeName("Ljava/lang/Thread"); public static final TypeReference JavaLangThread = findOrCreate(ClassLoaderReference.Primordial, JavaLangThreadName); private static final TypeName JavaLangThrowableName = TypeName.string2TypeName("Ljava/lang/Throwable"); public static final TypeReference JavaLangThrowable = findOrCreate(ClassLoaderReference.Primordial, JavaLangThrowableName); public static final TypeName JavaLangCloneableName = TypeName.string2TypeName("Ljava/lang/Cloneable"); public static final TypeReference JavaLangCloneable = findOrCreate(ClassLoaderReference.Primordial, JavaLangCloneableName); private static final TypeName JavaLangSystemName = TypeName.string2TypeName("Ljava/lang/System"); public static final TypeReference JavaLangSystem = findOrCreate(ClassLoaderReference.Primordial, JavaLangSystemName); private static final TypeName JavaLangIntegerName = TypeName.string2TypeName("Ljava/lang/Integer"); public static final TypeReference JavaLangInteger = findOrCreate(ClassLoaderReference.Primordial, JavaLangIntegerName); private static final TypeName JavaLangBooleanName = TypeName.string2TypeName("Ljava/lang/Boolean"); public static final TypeReference JavaLangBoolean = findOrCreate(ClassLoaderReference.Primordial, JavaLangBooleanName); private static final TypeName JavaLangDoubleName = TypeName.string2TypeName("Ljava/lang/Double"); public static final TypeReference JavaLangDouble = findOrCreate(ClassLoaderReference.Primordial, JavaLangDoubleName); private static final TypeName JavaLangFloatName = TypeName.string2TypeName("Ljava/lang/Float"); public static final TypeReference JavaLangFloat = findOrCreate(ClassLoaderReference.Primordial, JavaLangFloatName); private static final TypeName JavaLangShortName = TypeName.string2TypeName("Ljava/lang/Short"); public static final TypeReference JavaLangShort = findOrCreate(ClassLoaderReference.Primordial, JavaLangShortName); private static final TypeName JavaLangLongName = TypeName.string2TypeName("Ljava/lang/Long"); public static final TypeReference JavaLangLong = findOrCreate(ClassLoaderReference.Primordial, JavaLangLongName); private static final TypeName JavaLangByteName = TypeName.string2TypeName("Ljava/lang/Byte"); public static final TypeReference JavaLangByte = findOrCreate(ClassLoaderReference.Primordial, JavaLangByteName); private static final TypeName JavaLangCharacterName = TypeName.string2TypeName("Ljava/lang/Character"); public static final TypeReference JavaLangCharacter = findOrCreate(ClassLoaderReference.Primordial, JavaLangCharacterName); public static final TypeName JavaIoSerializableName = TypeName.string2TypeName("Ljava/io/Serializable"); public static final TypeReference JavaIoSerializable = findOrCreate(ClassLoaderReference.Primordial, JavaIoSerializableName); private static final TypeName JavaUtilCollectionName = TypeName.string2TypeName("Ljava/util/Collection"); public static final TypeReference JavaUtilCollection = findOrCreate(ClassLoaderReference.Primordial, JavaUtilCollectionName); private static final TypeName JavaUtilMapName = TypeName.string2TypeName("Ljava/util/Map"); public static final TypeReference JavaUtilMap = findOrCreate(ClassLoaderReference.Primordial, JavaUtilMapName); private static final TypeName JavaUtilHashSetName = TypeName.string2TypeName("Ljava/util/HashSet"); public static final TypeReference JavaUtilHashSet = findOrCreate(ClassLoaderReference.Primordial, JavaUtilHashSetName); private static final TypeName JavaUtilSetName = TypeName.string2TypeName("Ljava/util/Set"); public static final TypeReference JavaUtilSet = findOrCreate(ClassLoaderReference.Primordial, JavaUtilSetName); private static final TypeName JavaUtilEnumName = TypeName.string2TypeName("Ljava/util/Enumeration"); public static final TypeReference JavaUtilEnum = findOrCreate(ClassLoaderReference.Primordial, JavaUtilEnumName); private static final TypeName JavaUtilIteratorName = TypeName.string2TypeName("Ljava/util/Iterator"); public static final TypeReference JavaUtilIterator = findOrCreate(ClassLoaderReference.Primordial, JavaUtilIteratorName); private static final TypeName JavaUtilVectorName = TypeName.string2TypeName("Ljava/util/Vector"); public static final TypeReference JavaUtilVector = findOrCreate(ClassLoaderReference.Primordial, JavaUtilVectorName); public static final byte ClassTypeCode = 'L'; public static final byte ArrayTypeCode = '['; public static final byte PointerTypeCode = '*'; public static final byte ReferenceTypeCode = '&'; // TODO! the following two are unsound hacks; kill them. static final TypeName NullName = TypeName.string2TypeName("null"); public static final TypeReference Null = findOrCreate(ClassLoaderReference.Primordial, NullName); // TODO: is the following necessary. Used only by ShrikeBT. static final TypeName UnknownName = TypeName.string2TypeName("?unknown?"); public static final TypeReference Unknown = findOrCreate(ClassLoaderReference.Primordial, UnknownName); public static final TypeReference LambdaMetaFactory = findOrCreate(ClassLoaderReference.Primordial, "Ljava/lang/invoke/LambdaMetafactory"); private static TypeReference makePrimitive(TypeName n) { return makePrimitive(ClassLoaderReference.Primordial, n); } public static TypeReference makePrimitive(ClassLoaderReference cl, TypeName n) { TypeReference t = new TypeReference(cl, n); primitiveMap.put(t.name, t); return t; } /** Could name a represent a primitive type? */ public static boolean isPrimitiveType(TypeName name) { return name.isPrimitiveType(); } /** The initiating class loader */ private final ClassLoaderReference classloader; /** The type name */ private final TypeName name; /** * Find or create the canonical TypeReference instance for the given pair. * * @param cl the classloader (defining/initiating depending on usage) */ public static synchronized TypeReference findOrCreate( ClassLoaderReference cl, TypeName typeName) { if (cl == null) { throw new IllegalArgumentException("null cl"); } TypeReference p = primitiveMap.get(typeName); if (p != null) { return p; } // Next actually findOrCreate the type reference using the proper // classloader. // [This is the only allocation site for TypeReference] if (typeName.isArrayType()) { TypeName e = typeName.getInnermostElementType(); if (e.isPrimitiveType()) { cl = ClassLoaderReference.Primordial; } } Key key = new Key(cl, typeName); TypeReference val = dictionary.get(key); if (val == null) { val = new TypeReference(cl, typeName); dictionary.put(key, val); } return val; } /** * Find or create the canonical {@code TypeReference} instance for the given pair. * * @param cl the classloader (defining/initiating depending on usage) * @param typeName something like "Ljava/util/Arrays" */ public static synchronized TypeReference findOrCreate(ClassLoaderReference cl, String typeName) { return findOrCreate(cl, TypeName.string2TypeName(typeName)); } public static synchronized TypeReference find(ClassLoaderReference cl, String typeName) { return find(cl, TypeName.string2TypeName(typeName)); } /** * Find the canonical TypeReference instance for the given pair. May return null. * * @param cl the classloader (defining/initiating depending on usage) */ public static synchronized TypeReference find(ClassLoaderReference cl, TypeName typeName) { if (cl == null) { throw new IllegalArgumentException("null cl"); } TypeReference p = primitiveMap.get(typeName); if (p != null) { return p; } // Next actually findOrCreate the type reference using the proper // classloader. // [This is the only allocation site for TypeReference] if (typeName.isArrayType()) { TypeName e = typeName.getInnermostElementType(); if (e.isPrimitiveType()) { cl = ClassLoaderReference.Primordial; } } Key key = new Key(cl, typeName); TypeReference val = dictionary.get(key); return val; } public static TypeReference findOrCreateArrayOf(TypeReference t) { if (t == null) { throw new IllegalArgumentException("t is null"); } TypeName name = t.getName(); if (t.isPrimitiveType()) { return findOrCreate(ClassLoaderReference.Primordial, name.getArrayTypeForElementType()); } else { return findOrCreate(t.getClassLoader(), name.getArrayTypeForElementType()); } } public static TypeReference findOrCreateReferenceTo(TypeReference t) { if (t == null) { throw new IllegalArgumentException("t is null"); } TypeName name = t.getName(); if (t.isPrimitiveType()) { return findOrCreate(ClassLoaderReference.Primordial, name.getReferenceTypeForElementType()); } else { return findOrCreate(t.getClassLoader(), name.getReferenceTypeForElementType()); } } public static TypeReference findOrCreatePointerTo(TypeReference t) { if (t == null) { throw new IllegalArgumentException("t is null"); } TypeName name = t.getName(); if (t.isPrimitiveType()) { return findOrCreate(ClassLoaderReference.Primordial, name.getPointerTypeForElementType()); } else { return findOrCreate(t.getClassLoader(), name.getPointerTypeForElementType()); } } /** * NB: All type names should use '/' and not '.' as a separator. eg. Ljava/lang/Class * * @param cl the classloader * @param tn the type name */ private TypeReference(ClassLoaderReference cl, TypeName tn) { classloader = cl; name = tn; } /** @return the classloader component of this type reference */ public ClassLoaderReference getClassLoader() { return classloader; } /** @return the type name component of this type reference */ public TypeName getName() { return name; } /** * TODO: specialized form of TypeReference for arrays, please. Get the element type of for this * array type. */ public TypeReference getArrayElementType() { TypeName element = name.parseForArrayElementName(); return findOrCreate(classloader, element); } /** Get array type corresponding to "this" array element type. */ public TypeReference getArrayTypeForElementType() { return findOrCreate(classloader, name.getArrayTypeForElementType()); } /** * Return the dimensionality of the type. By convention, class types have dimensionality 0, * primitives -1, and arrays the number of [ in their descriptor. */ public int getDerivedMask() { return name.getDerivedMask(); } /** Return the innermost element type reference for an array */ public TypeReference getInnermostElementType() { return findOrCreate(classloader, name.getInnermostElementType()); } /** Does 'this' refer to a class? */ public boolean isClassType() { return !isArrayType() && !isPrimitiveType(); } /** Does 'this' refer to an array? */ public boolean isArrayType() { return name.isArrayType(); } /** Does 'this' refer to a primitive type */ public boolean isPrimitiveType() { return isPrimitiveType(name); } /** Does 'this' refer to a reference type */ public boolean isReferenceType() { return !isPrimitiveType(); } @Override public int hashCode() { return name.hashCode(); } /** * TypeReferences are canonical. However, note that two TypeReferences can be non-equal, yet still * represent the same IClass. * * <p>For example, the there can be two TypeReferences &lt;Application,java.lang.Object&gt; and * &lt;Primordial,java.lang.Object&gt;. These two TypeReference are <b>NOT</b> equal(), but they * both represent the IClass which is named &lt;Primordial,java.lang.Object&gt; */ @Override public boolean equals(Object other) { return (this == other); } @Override public String toString() { return "<" + classloader.getName() + ',' + name + '>'; } public static TypeReference findOrCreateClass( ClassLoaderReference loader, String packageName, String className) { TypeName tn = TypeName.findOrCreateClassName(packageName, className); return findOrCreate(loader, tn); } private static class Key { /** The initiating class loader */ private final ClassLoaderReference classloader; /** The type name */ private final TypeName name; Key(ClassLoaderReference classloader, TypeName name) { this.classloader = classloader; this.name = name; } @Override public final int hashCode() { return name.hashCode(); } @Override public final boolean equals(Object other) { assert other != null && other instanceof Key; Key that = (Key) other; return (name.equals(that.name) && classloader.equals(that.classloader)); } } public int getDimensionality() { assert isArrayType(); int mask = getDerivedMask(); if ((mask & PrimitiveMask) == PrimitiveMask) { mask >>= ElementBits; } int dims = 0; while ((mask & ArrayMask) == ArrayMask) { mask >>= ElementBits; dims++; } assert dims > 0; return dims; } }
24,559
34.959004
100
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/types/annotations/Annotation.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.types.annotations; import com.ibm.wala.shrike.shrikeCT.AnnotationsReader; import com.ibm.wala.shrike.shrikeCT.AnnotationsReader.AnnotationAttribute; import com.ibm.wala.shrike.shrikeCT.AnnotationsReader.ElementValue; import com.ibm.wala.shrike.shrikeCT.InvalidClassFileException; import com.ibm.wala.types.ClassLoaderReference; import com.ibm.wala.types.TypeReference; import com.ibm.wala.util.collections.HashSetFactory; import com.ibm.wala.util.collections.Pair; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Map; import java.util.TreeMap; /** Represents a member annotation, e.g., Java 5.0 class file annotations */ public class Annotation { private final TypeReference type; /** * named arguments to the annotation, represented as a mapping from name to value. Note that for * Java annotation arguments, the values are always Strings, independent of their actual type in * the bytecode. */ private final Map<String, ElementValue> namedArguments; /** * unnamed arguments to the annotation (e.g., constructor arguments for C# attributes), * represented as an array of pairs (T,V), where T is the argument type and V is the value. The * array preserves the order in which the arguments were passed. If null, there are no unnamed * arguments. */ private final Pair<TypeReference, Object>[] unnamedArguments; private Annotation( TypeReference type, Map<String, ElementValue> namedArguments, Pair<TypeReference, Object>[] unnamedArguments) { this.type = type; if (namedArguments == null) { throw new IllegalArgumentException("namedArguments is null"); } this.namedArguments = namedArguments; this.unnamedArguments = unnamedArguments; } public static Annotation makeUnnamedAndNamed( TypeReference t, Map<String, ElementValue> namedArguments, Pair<TypeReference, Object>[] unnamedArguments) { return new Annotation(t, namedArguments, unnamedArguments); } public static Annotation makeWithUnnamed( TypeReference t, Pair<TypeReference, Object>[] unnamedArguments) { return new Annotation(t, Collections.<String, ElementValue>emptyMap(), unnamedArguments); } public static Annotation make(TypeReference t) { return new Annotation(t, Collections.<String, ElementValue>emptyMap(), null); } public static Annotation makeWithNamed( TypeReference t, Map<String, ElementValue> namedArguments) { return new Annotation(t, namedArguments, null); } public static Collection<Annotation> getAnnotationsFromReader( AnnotationsReader r, ClassLoaderReference clRef) throws InvalidClassFileException { if (r != null) { AnnotationAttribute[] allAnnotations = r.getAllAnnotations(); Collection<Annotation> result = convertToAnnotations(clRef, allAnnotations); return result; } else { return Collections.emptySet(); } } /** * If r != null, return parameter annotations as an array with length equal to number of * annotatable parameters. Otherwise, return null. */ @SuppressWarnings("unchecked") public static Collection<Annotation>[] getParameterAnnotationsFromReader( AnnotationsReader r, ClassLoaderReference clRef) throws InvalidClassFileException { if (r != null) { AnnotationAttribute[][] allAnnots = r.getAllParameterAnnotations(); Collection<Annotation>[] result = new Collection[allAnnots.length]; Arrays.setAll(result, i -> convertToAnnotations(clRef, allAnnots[i])); return result; } else { return null; } } protected static Collection<Annotation> convertToAnnotations( ClassLoaderReference clRef, AnnotationAttribute[] allAnnotations) { Collection<Annotation> result = HashSetFactory.make(); for (AnnotationAttribute annot : allAnnotations) { String type = annot.type; type = type.replaceAll(";", ""); TypeReference t = TypeReference.findOrCreate(clRef, type); result.add(makeWithNamed(t, annot.elementValues)); } return result; } @Override public String toString() { StringBuilder sb = new StringBuilder("Annotation type " + type); if (unnamedArguments != null) { sb.append('['); for (Pair<TypeReference, Object> arg : unnamedArguments) { sb.append(' ').append(arg.fst.getName().getClassName()).append(':').append(arg.snd); } sb.append(" ]"); } if (!namedArguments.isEmpty()) { sb.append(' ').append(new TreeMap<>(namedArguments)); } return sb.toString(); } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((namedArguments == null) ? 0 : namedArguments.hashCode()); result = prime * result + ((type == null) ? 0 : type.hashCode()); result = prime * result + Arrays.hashCode(unnamedArguments); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Annotation other = (Annotation) obj; if (namedArguments == null) { if (other.namedArguments != null) return false; } else if (!namedArguments.equals(other.namedArguments)) return false; if (type == null) { if (other.type != null) return false; } else if (!type.equals(other.type)) return false; if (!Arrays.equals(unnamedArguments, other.unnamedArguments)) return false; return true; } /** * Get the unnamed arguments to the annotation (e.g., constructor arguments for C# attributes), * represented as an array of pairs (T,V), where T is the argument type and V is the value. The * array preserves the order in which the arguments were passed. If null, there are no unnamed * arguments. */ public Pair<TypeReference, Object>[] getUnnamedArguments() { return unnamedArguments; } /** Get the named arguments to the annotation, represented as a mapping from name to value */ public Map<String, ElementValue> getNamedArguments() { return namedArguments; } /** Get the type of the annotation */ public TypeReference getType() { return type; } }
6,614
35.346154
98
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/types/annotations/Annotations.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.types.annotations; import com.ibm.wala.classLoader.FieldImpl; import com.ibm.wala.classLoader.IClass; import com.ibm.wala.classLoader.IField; import com.ibm.wala.classLoader.IMethod; import com.ibm.wala.classLoader.ShrikeCTMethod; import com.ibm.wala.classLoader.ShrikeClass; import com.ibm.wala.shrike.shrikeCT.InvalidClassFileException; import com.ibm.wala.types.TypeName; import com.ibm.wala.util.debug.Assertions; import java.util.Collection; public class Annotations { public static final TypeName INTERNAL = TypeName.findOrCreateClassName("com/ibm/wala/annotations", "Internal"); public static final TypeName NONNULL = TypeName.findOrCreateClassName("com/ibm/wala/annotations", "NonNull"); /** Does a particular method have a particular annotation? */ public static boolean hasAnnotation(IMethod m, TypeName type) { if (m instanceof ShrikeCTMethod) { Collection<Annotation> annotations = null; try { annotations = ((ShrikeCTMethod) m).getRuntimeInvisibleAnnotations(); } catch (InvalidClassFileException e) { e.printStackTrace(); Assertions.UNREACHABLE(); } for (Annotation a : annotations) { if (a.getType().getName().equals(type)) { return true; } } } return false; } /** Does a particular class have a particular annotation? */ public static boolean hasAnnotation(IClass c, TypeName type) { if (c instanceof ShrikeClass) { Collection<Annotation> annotations = null; try { annotations = ((ShrikeClass) c).getRuntimeInvisibleAnnotations(); } catch (InvalidClassFileException e) { e.printStackTrace(); Assertions.UNREACHABLE(); } for (Annotation a : annotations) { if (a.getType().getName().equals(type)) { return true; } } } return false; } public static boolean hasAnnotation(IField field, TypeName type) { if (field instanceof FieldImpl) { FieldImpl f = (FieldImpl) field; Collection<Annotation> annotations = f.getAnnotations(); if (annotations != null) { for (Annotation a : annotations) { if (a.getType().getName().equals(type)) { return true; } } } } return false; } }
2,689
31.02381
77
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/types/annotations/TypeAnnotation.java
/* * Copyright (c) 2016 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Martin Hecker, KIT - initial implementation */ package com.ibm.wala.types.annotations; import com.ibm.wala.classLoader.FieldImpl; import com.ibm.wala.classLoader.IBytecodeMethod; import com.ibm.wala.classLoader.ShrikeCTMethod; import com.ibm.wala.classLoader.ShrikeClass; import com.ibm.wala.shrike.shrikeCT.AnnotationsReader.AnnotationAttribute; import com.ibm.wala.shrike.shrikeCT.InvalidClassFileException; import com.ibm.wala.shrike.shrikeCT.TypeAnnotationsReader; import com.ibm.wala.shrike.shrikeCT.TypeAnnotationsReader.TargetInfo; import com.ibm.wala.shrike.shrikeCT.TypeAnnotationsReader.TargetType; import com.ibm.wala.shrike.shrikeCT.TypeAnnotationsReader.TypeAnnotationAttribute; import com.ibm.wala.shrike.shrikeCT.TypeAnnotationsReader.TypeAnnotationLocation; import com.ibm.wala.shrike.shrikeCT.TypeAnnotationsReader.TypeAnnotationTargetVisitor; import com.ibm.wala.shrike.shrikeCT.TypeAnnotationsReader.TypePathKind; import com.ibm.wala.types.ClassLoaderReference; import com.ibm.wala.types.TypeReference; import com.ibm.wala.util.collections.Pair; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.List; /** * A {@link TypeAnnotation} represents a JSR 308 Java Type Annotation. * * @author Martin Hecker martin.hecker@kit.edu * @see Annotation * @see TypeAnnotationTarget * @see <a href="https://docs.oracle.com/javase/specs/jvms/se8/html/jvms-4.html#jvms-4.7.20">JLS * (SE8), 4.7.20</a> * @see <a href="https://jcp.org/en/jsr/detail?id=308">JSR 308: Annotations on Java Types</a> * @see <a href="http://types.cs.washington.edu/jsr308/">Type Annotations (JSR 308) and the Checker * Framework</a> */ public class TypeAnnotation { private final Annotation annotation; private final List<Pair<TypePathKind, Integer>> typePath; private final TypeAnnotationTarget typeAnnotationTarget; private final TargetType targetType; private TypeAnnotation( Annotation annotation, List<Pair<TypePathKind, Integer>> typePath, TypeAnnotationTarget typeAnnotationTarget, TargetType targetType) { this.annotation = annotation; this.typePath = Collections.unmodifiableList(typePath); this.typeAnnotationTarget = typeAnnotationTarget; this.targetType = targetType; } @Override public String toString() { return "TypeAnnotation" + "{ annotation = " + annotation + ", path = " + typePath + ", target = " + typeAnnotationTarget + '}'; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((annotation == null) ? 0 : annotation.hashCode()); result = prime * result + ((typeAnnotationTarget == null) ? 0 : typeAnnotationTarget.hashCode()); result = prime * result + ((typePath == null) ? 0 : typePath.hashCode()); result = prime * result + ((targetType == null) ? 0 : targetType.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; TypeAnnotation other = (TypeAnnotation) obj; if (annotation == null) { if (other.annotation != null) return false; } else if (!annotation.equals(other.annotation)) return false; if (typeAnnotationTarget == null) { if (other.typeAnnotationTarget != null) return false; } else if (!typeAnnotationTarget.equals(other.typeAnnotationTarget)) return false; if (typePath == null) { if (other.typePath != null) return false; } else if (!typePath.equals(other.typePath)) return false; if (targetType == null) { if (other.targetType != null) return false; } else if (!targetType.equals(other.targetType)) return false; return true; } public static Collection<TypeAnnotation> getTypeAnnotationsFromReader( TypeAnnotationsReader r, TypeAnnotationTargetConverter converter, ClassLoaderReference clRef) throws InvalidClassFileException { if (r != null) { TypeAnnotationAttribute[] allTypeAnnotations = r.getAllTypeAnnotations(); Collection<TypeAnnotation> result = new ArrayList<>(allTypeAnnotations.length); for (TypeAnnotationAttribute tatt : allTypeAnnotations) { final Collection<Annotation> annotations = Annotation.convertToAnnotations( clRef, new AnnotationAttribute[] {tatt.annotationAttribute}); assert annotations.size() == 1; final Annotation annotation = annotations.iterator().next(); result.add( new TypeAnnotation( annotation, tatt.typePath, tatt.annotationTarget.acceptVisitor(converter), tatt.targetType)); } return result; } else { return Collections.emptySet(); } } /** * This method is intended to be used in testing only. * * <p>Otherwise, obtain TypeAnnotations from * * <ul> * <li>{@link ShrikeCTMethod#getTypeAnnotationsAtCode(boolean)} * <li>{@link ShrikeCTMethod#getTypeAnnotationsAtMethodInfo(boolean)} * <li>{@link FieldImpl#getTypeAnnotations()} * <li>{@link ShrikeClass#getTypeAnnotations(boolean)} * </ul> * * @return A {@code TypeAnnotation} comprised of annotation, typePath and targetType */ public static TypeAnnotation make( Annotation annotation, List<Pair<TypePathKind, Integer>> typePath, TypeAnnotationTarget typeAnnotationTarget, TargetType targetType) { return new TypeAnnotation(annotation, typePath, typeAnnotationTarget, targetType); } /** * This method is intended to be used in testing only. * * <p>Otherwise, obtain TypeAnnotations from * * <ul> * <li>{@link ShrikeCTMethod#getTypeAnnotationsAtCode(boolean)} * <li>{@link ShrikeCTMethod#getTypeAnnotationsAtMethodInfo(boolean)} * <li>{@link FieldImpl#getTypeAnnotations()} * <li>{@link ShrikeClass#getTypeAnnotations(boolean)} * </ul> * * @return A {@code TypeAnnotation} comprised of annotation, an empty typePath, and targetType */ public static TypeAnnotation make( Annotation annotation, TypeAnnotationTarget typeAnnotationTarget, TargetType targetType) { return new TypeAnnotation( annotation, TypeAnnotationsReader.TYPEPATH_EMPTY, typeAnnotationTarget, targetType); } /** * A {@link TypeAnnotationTarget} represents the "target" of a Type Annotation. * * <p>In contrast to {@link * com.ibm.wala.shrike.shrikeCT.TypeAnnotationsReader.TypeAnnotationTarget}, subclasses of {@link * TypeAnnotationTarget} usually have already resolved bytecode-specific data (such as bcIndices) * to their WALA counterparts. * * @author Martin Hecker martin.hecker@kit.edu */ public abstract static class TypeAnnotationTarget { public static final int INSTRUCTION_INDEX_UNAVAILABLE = -1; } public static class TypeParameterTarget extends TypeAnnotationTarget { private final int type_parameter_index; public TypeParameterTarget(int type_parameter_index) { this.type_parameter_index = type_parameter_index; } public int getIndex() { return type_parameter_index; } @Override public String toString() { return "TypeParameterTarget" + "{ type_parameter_index = " + type_parameter_index + '}'; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + type_parameter_index; return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; TypeParameterTarget other = (TypeParameterTarget) obj; if (type_parameter_index != other.type_parameter_index) return false; return true; } } public static class SuperTypeTarget extends TypeAnnotationTarget { private final TypeReference superType; public SuperTypeTarget(TypeReference superType) { this.superType = superType; } public TypeReference getSuperType() { return superType; } @Override public String toString() { return "SuperTypeTarget{ superType = " + superType + '}'; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((superType == null) ? 0 : superType.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; SuperTypeTarget other = (SuperTypeTarget) obj; if (superType == null) { if (other.superType != null) return false; } else if (!superType.equals(other.superType)) return false; return true; } } public static class TypeParameterBoundTarget extends TypeAnnotationTarget { private final int type_parameter_index; private final int bound_index; public TypeParameterBoundTarget(int type_parameter_index, int bound_index) { this.type_parameter_index = type_parameter_index; this.bound_index = bound_index; } @Override public String toString() { return "TypeParameterBoundTarget{ type_parameter_index = " + type_parameter_index + ", bound_index = " + bound_index + '}'; } public int getParameterIndex() { return type_parameter_index; } public int getBoundIndex() { return bound_index; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + bound_index; result = prime * result + type_parameter_index; return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; TypeParameterBoundTarget other = (TypeParameterBoundTarget) obj; if (bound_index != other.bound_index) return false; if (type_parameter_index != other.type_parameter_index) return false; return true; } } public static class EmptyTarget extends TypeAnnotationTarget { public EmptyTarget() {} @Override public String toString() { return "EmptyTarget"; } @Override public int hashCode() { return 1; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; return true; } } public static class FormalParameterTarget extends TypeAnnotationTarget { private final int formal_parameter_index; public FormalParameterTarget(int index) { this.formal_parameter_index = index; } public int getIndex() { return formal_parameter_index; } @Override public String toString() { return "FormalParameterTarget" + "{ formal_parameter_index = " + formal_parameter_index + '}'; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + formal_parameter_index; return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; FormalParameterTarget other = (FormalParameterTarget) obj; if (formal_parameter_index != other.formal_parameter_index) return false; return true; } } public static class ThrowsTarget extends TypeAnnotationTarget { private final TypeReference throwType; public ThrowsTarget(TypeReference throwType) { this.throwType = throwType; } public TypeReference getThrowType() { return throwType; } @Override public String toString() { return "ThrowsTarget{ throwType = " + throwType + '}'; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((throwType == null) ? 0 : throwType.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; ThrowsTarget other = (ThrowsTarget) obj; if (throwType == null) { if (other.throwType != null) return false; } else if (!throwType.equals(other.throwType)) return false; return true; } } public static class LocalVarTarget extends TypeAnnotationTarget { // TODO: we might want to relate bytecode-ranges to ranges in the // IInstruction[] array returned by IBytecodeMethod.getInstructions(), // but is this even meaningful? private final int varIindex; private final String name; public LocalVarTarget(int varIindex, String name) { this.varIindex = varIindex; this.name = name; } @Override public String toString() { return "LocalVarTarget{ varIindex = " + varIindex + ", name = " + name + '}'; } public int getIndex() { return varIindex; } /** * @return the name of the local Variable, or null if it could not be determined (for example, * if the LocalVariableTable in the corresponding class file is missing). */ public String getName() { return name; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((name == null) ? 0 : name.hashCode()); result = prime * result + varIindex; return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; LocalVarTarget other = (LocalVarTarget) obj; if (name == null) { if (other.name != null) return false; } else if (!name.equals(other.name)) return false; if (varIindex != other.varIindex) return false; return true; } } public static class CatchTarget extends TypeAnnotationTarget { // TODO: as per LocalVarTarget, can we record a meaningful range in terms // of IInstriction[] or SSAInstruction[] indices?!?! this is currently missing.. private final int catchIIndex; private final TypeReference catchType; // TODO: or should this be TypeReference.JavaLangThrowable? public static final TypeReference ALL_EXCEPTIONS = null; public CatchTarget(int catchIIndex, TypeReference catchType) { this.catchIIndex = catchIIndex; this.catchType = catchType; } /** @return the handlers type, or {@link CatchTarget#ALL_EXCEPTIONS} */ public TypeReference getCatchType() { return catchType; } /** * @return the handlers instruction index (if available), or {@link * TypeAnnotationTarget#INSTRUCTION_INDEX_UNAVAILABLE} otherwise. */ public int getCatchIIndex() { return catchIIndex; } @Override public String toString() { return "CatchTarget{ catchIIndex = " + catchIIndex + ", catchType = " + catchType + '}'; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + catchIIndex; result = prime * result + ((catchType == null) ? 0 : catchType.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; CatchTarget other = (CatchTarget) obj; if (catchIIndex != other.catchIIndex) return false; if (catchType == null) { if (other.catchType != null) return false; } else if (!catchType.equals(other.catchType)) return false; return true; } } public static class OffsetTarget extends TypeAnnotationTarget { private final int iindex; public OffsetTarget(int iindex) { this.iindex = iindex; } /** * @return the targets instruction index (if available), or {@link * TypeAnnotationTarget#INSTRUCTION_INDEX_UNAVAILABLE} otherwise. */ public int getIIndex() { return iindex; } @Override public String toString() { return "OffsetTarget{ iindex = " + iindex + '}'; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + 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; OffsetTarget other = (OffsetTarget) obj; if (iindex != other.iindex) return false; return true; } } public static class TypeArgumentTarget extends TypeAnnotationTarget { private final int iindex; private final int type_argument_index; public TypeArgumentTarget(int iindex, int type_argument_index) { this.iindex = iindex; this.type_argument_index = type_argument_index; } public int getOffset() { return iindex; } public int getTypeArgumentIndex() { return type_argument_index; } @Override public String toString() { return "TypeArgumentTarget{ iindex = " + iindex + ", type_argument_index = " + type_argument_index + '}'; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + iindex; result = prime * result + type_argument_index; return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; TypeArgumentTarget other = (TypeArgumentTarget) obj; if (iindex != other.iindex) return false; if (type_argument_index != other.type_argument_index) return false; return true; } } private static TypeReference fromString(ClassLoaderReference clRef, String typeName) { // TODO: should we not use some lookup that try to (recursively) find a TypeReference in clRefs // parents, // and only create a new TypeReference in clRef if this fails? I can't find a such a utility // method, though..?!?! return TypeReference.findOrCreate(clRef, 'L' + typeName.replaceAll(";", "")); } private static boolean mayAppearIn(TargetInfo info, TypeAnnotationLocation location) { for (TargetType targetType : TargetType.values()) { if (targetType.target_info == info && targetType.location == location) return true; } return false; } /** * A @{TypeAnnotationTargetConverter} takes "unresolved" instances of {@link * com.ibm.wala.shrike.shrikeCT.TypeAnnotationsReader.TypeAnnotationTarget}, resolves some * byte-code specific data, and returns instances of the corresponding {@link * TypeAnnotationTarget} subclass. * * @author Martin Hecker martin.hecker@kit.edu */ public interface TypeAnnotationTargetConverter extends TypeAnnotationTargetVisitor<TypeAnnotationTarget> {} public static TypeAnnotationTargetConverter targetConverterAtCode( final ClassLoaderReference clRef, final IBytecodeMethod<?> method) { return new TypeAnnotationTargetConverter() { @Override public TypeAnnotationTarget visitTypeParameterTarget( com.ibm.wala.shrike.shrikeCT.TypeAnnotationsReader.TypeParameterTarget target) { assert !mayAppearIn(target.getTargetInfo(), TypeAnnotationLocation.Code); throw new UnsupportedOperationException(); } @Override public TypeAnnotationTarget visitSuperTypeTarget( com.ibm.wala.shrike.shrikeCT.TypeAnnotationsReader.SuperTypeTarget target) { assert !mayAppearIn(target.getTargetInfo(), TypeAnnotationLocation.Code); throw new UnsupportedOperationException(); } @Override public TypeAnnotationTarget visitTypeParameterBoundTarget( com.ibm.wala.shrike.shrikeCT.TypeAnnotationsReader.TypeParameterBoundTarget target) { assert !mayAppearIn(target.getTargetInfo(), TypeAnnotationLocation.Code); throw new UnsupportedOperationException(); } @Override public TypeAnnotationTarget visitEmptyTarget( com.ibm.wala.shrike.shrikeCT.TypeAnnotationsReader.EmptyTarget target) { assert !mayAppearIn(target.getTargetInfo(), TypeAnnotationLocation.Code); throw new UnsupportedOperationException(); } @Override public TypeAnnotationTarget visitFormalParameterTarget( com.ibm.wala.shrike.shrikeCT.TypeAnnotationsReader.FormalParameterTarget target) { assert !mayAppearIn(target.getTargetInfo(), TypeAnnotationLocation.Code); throw new UnsupportedOperationException(); } @Override public TypeAnnotationTarget visitThrowsTarget( com.ibm.wala.shrike.shrikeCT.TypeAnnotationsReader.ThrowsTarget target) { assert !mayAppearIn(target.getTargetInfo(), TypeAnnotationLocation.Code); throw new UnsupportedOperationException(); } @Override public TypeAnnotationTarget visitLocalVarTarget( com.ibm.wala.shrike.shrikeCT.TypeAnnotationsReader.LocalVarTarget target) { assert mayAppearIn(target.getTargetInfo(), TypeAnnotationLocation.Code); // TODO: is this even allowed? Should we have thrown an exception earlier? if (target.getNrOfRanges() == 0) return new LocalVarTarget(-1, null); final int varIndex = target.getIndex(0); final String name = method.getLocalVariableName(target.getStartPc(0), target.getIndex(0)); if (name == null) { return new LocalVarTarget(varIndex, null); } for (int i = 0; i < target.getNrOfRanges(); i++) { if (target.getIndex(i) != varIndex) throw new IllegalArgumentException(); if (!method.getLocalVariableName(target.getStartPc(0), target.getIndex(0)).equals(name)) { throw new IllegalArgumentException(); } } return new LocalVarTarget(varIndex, name); } @Override public TypeAnnotationTarget visitCatchTarget( com.ibm.wala.shrike.shrikeCT.TypeAnnotationsReader.CatchTarget target) { assert mayAppearIn(target.getTargetInfo(), TypeAnnotationLocation.Code); final TypeReference catchType; if (target.getCatchType() == com.ibm.wala.shrike.shrikeCT.TypeAnnotationsReader.CatchTarget.ALL_EXCEPTIONS) { catchType = CatchTarget.ALL_EXCEPTIONS; } else { catchType = fromString(clRef, target.getCatchType()); } // well this is awkward.. try { final int catchIIndex = method.getInstructionIndex(target.getCatchPC()); return new CatchTarget(catchIIndex, catchType); } catch (InvalidClassFileException e) { return new CatchTarget(TypeAnnotationTarget.INSTRUCTION_INDEX_UNAVAILABLE, catchType); } } @Override public TypeAnnotationTarget visitOffsetTarget( com.ibm.wala.shrike.shrikeCT.TypeAnnotationsReader.OffsetTarget target) { assert mayAppearIn(target.getTargetInfo(), TypeAnnotationLocation.Code); try { final int iindex = method.getInstructionIndex(target.getOffset()); return new OffsetTarget(iindex); } catch (InvalidClassFileException e) { return new OffsetTarget(TypeAnnotationTarget.INSTRUCTION_INDEX_UNAVAILABLE); } } @Override public TypeAnnotationTarget visitTypeArgumentTarget( com.ibm.wala.shrike.shrikeCT.TypeAnnotationsReader.TypeArgumentTarget target) { assert mayAppearIn(target.getTargetInfo(), TypeAnnotationLocation.Code); try { final int iindex = method.getInstructionIndex(target.getOffset()); return new TypeArgumentTarget(iindex, target.getTypeArgumentIndex()); } catch (InvalidClassFileException e) { return new TypeArgumentTarget( TypeAnnotationTarget.INSTRUCTION_INDEX_UNAVAILABLE, target.getTypeArgumentIndex()); } } }; } // TODO: method is currently unused, but we may want to use it if we decide to resolve generic // signature indices here public static TypeAnnotationTargetConverter targetConverterAtMethodInfo( final ClassLoaderReference clRef) { return new TypeAnnotationTargetConverter() { @Override public TypeAnnotationTarget visitTypeParameterTarget( com.ibm.wala.shrike.shrikeCT.TypeAnnotationsReader.TypeParameterTarget target) { assert mayAppearIn(target.getTargetInfo(), TypeAnnotationLocation.method_info); return new TypeParameterTarget(target.getIndex()); } @Override public TypeAnnotationTarget visitSuperTypeTarget( com.ibm.wala.shrike.shrikeCT.TypeAnnotationsReader.SuperTypeTarget target) { assert !mayAppearIn(target.getTargetInfo(), TypeAnnotationLocation.method_info); throw new UnsupportedOperationException(); } @Override public TypeAnnotationTarget visitTypeParameterBoundTarget( com.ibm.wala.shrike.shrikeCT.TypeAnnotationsReader.TypeParameterBoundTarget target) { assert mayAppearIn(target.getTargetInfo(), TypeAnnotationLocation.method_info); return new TypeParameterBoundTarget(target.getParameterIndex(), target.getBoundIndex()); } @Override public TypeAnnotationTarget visitEmptyTarget( com.ibm.wala.shrike.shrikeCT.TypeAnnotationsReader.EmptyTarget target) { assert mayAppearIn(target.getTargetInfo(), TypeAnnotationLocation.method_info); return new EmptyTarget(); } @Override public TypeAnnotationTarget visitFormalParameterTarget( com.ibm.wala.shrike.shrikeCT.TypeAnnotationsReader.FormalParameterTarget target) { assert mayAppearIn(target.getTargetInfo(), TypeAnnotationLocation.method_info); return new FormalParameterTarget(target.getIndex()); } @Override public TypeAnnotationTarget visitThrowsTarget( com.ibm.wala.shrike.shrikeCT.TypeAnnotationsReader.ThrowsTarget target) { assert mayAppearIn(target.getTargetInfo(), TypeAnnotationLocation.method_info); return new ThrowsTarget(fromString(clRef, target.getThrowType())); } @Override public TypeAnnotationTarget visitLocalVarTarget( com.ibm.wala.shrike.shrikeCT.TypeAnnotationsReader.LocalVarTarget target) { assert !mayAppearIn(target.getTargetInfo(), TypeAnnotationLocation.method_info); throw new UnsupportedOperationException(); } @Override public TypeAnnotationTarget visitCatchTarget( com.ibm.wala.shrike.shrikeCT.TypeAnnotationsReader.CatchTarget target) { assert !mayAppearIn(target.getTargetInfo(), TypeAnnotationLocation.method_info); throw new UnsupportedOperationException(); } @Override public TypeAnnotationTarget visitOffsetTarget( com.ibm.wala.shrike.shrikeCT.TypeAnnotationsReader.OffsetTarget target) { assert !mayAppearIn(target.getTargetInfo(), TypeAnnotationLocation.method_info); throw new UnsupportedOperationException(); } @Override public TypeAnnotationTarget visitTypeArgumentTarget( com.ibm.wala.shrike.shrikeCT.TypeAnnotationsReader.TypeArgumentTarget target) { assert !mayAppearIn(target.getTargetInfo(), TypeAnnotationLocation.method_info); throw new UnsupportedOperationException(); } }; } public static TypeAnnotationTargetConverter targetConverterAtClassFile( final ClassLoaderReference clRef) { return new TypeAnnotationTargetConverter() { @Override public TypeAnnotationTarget visitTypeParameterTarget( com.ibm.wala.shrike.shrikeCT.TypeAnnotationsReader.TypeParameterTarget target) { assert mayAppearIn(target.getTargetInfo(), TypeAnnotationLocation.ClassFile); return new TypeParameterTarget(target.getIndex()); } @Override public TypeAnnotationTarget visitSuperTypeTarget( com.ibm.wala.shrike.shrikeCT.TypeAnnotationsReader.SuperTypeTarget target) { assert mayAppearIn(target.getTargetInfo(), TypeAnnotationLocation.ClassFile); return new SuperTypeTarget(fromString(clRef, target.getSuperType())); } @Override public TypeAnnotationTarget visitTypeParameterBoundTarget( com.ibm.wala.shrike.shrikeCT.TypeAnnotationsReader.TypeParameterBoundTarget target) { assert mayAppearIn(target.getTargetInfo(), TypeAnnotationLocation.ClassFile); return new TypeParameterBoundTarget(target.getParameterIndex(), target.getBoundIndex()); } @Override public TypeAnnotationTarget visitEmptyTarget( com.ibm.wala.shrike.shrikeCT.TypeAnnotationsReader.EmptyTarget target) { assert !mayAppearIn(target.getTargetInfo(), TypeAnnotationLocation.ClassFile); throw new UnsupportedOperationException(); } @Override public TypeAnnotationTarget visitFormalParameterTarget( com.ibm.wala.shrike.shrikeCT.TypeAnnotationsReader.FormalParameterTarget target) { assert !mayAppearIn(target.getTargetInfo(), TypeAnnotationLocation.ClassFile); throw new UnsupportedOperationException(); } @Override public TypeAnnotationTarget visitThrowsTarget( com.ibm.wala.shrike.shrikeCT.TypeAnnotationsReader.ThrowsTarget target) { assert !mayAppearIn(target.getTargetInfo(), TypeAnnotationLocation.ClassFile); throw new UnsupportedOperationException(); } @Override public TypeAnnotationTarget visitLocalVarTarget( com.ibm.wala.shrike.shrikeCT.TypeAnnotationsReader.LocalVarTarget target) { assert !mayAppearIn(target.getTargetInfo(), TypeAnnotationLocation.ClassFile); throw new UnsupportedOperationException(); } @Override public TypeAnnotationTarget visitCatchTarget( com.ibm.wala.shrike.shrikeCT.TypeAnnotationsReader.CatchTarget target) { assert !mayAppearIn(target.getTargetInfo(), TypeAnnotationLocation.ClassFile); throw new UnsupportedOperationException(); } @Override public TypeAnnotationTarget visitOffsetTarget( com.ibm.wala.shrike.shrikeCT.TypeAnnotationsReader.OffsetTarget target) { assert !mayAppearIn(target.getTargetInfo(), TypeAnnotationLocation.ClassFile); throw new UnsupportedOperationException(); } @Override public TypeAnnotationTarget visitTypeArgumentTarget( com.ibm.wala.shrike.shrikeCT.TypeAnnotationsReader.TypeArgumentTarget target) { assert !mayAppearIn(target.getTargetInfo(), TypeAnnotationLocation.ClassFile); throw new UnsupportedOperationException(); } }; } public static TypeAnnotationTargetConverter targetConverterAtFieldInfo() { return new TypeAnnotationTargetConverter() { @Override public TypeAnnotationTarget visitTypeParameterTarget( com.ibm.wala.shrike.shrikeCT.TypeAnnotationsReader.TypeParameterTarget target) { assert !mayAppearIn(target.getTargetInfo(), TypeAnnotationLocation.field_info); throw new UnsupportedOperationException(); } @Override public TypeAnnotationTarget visitSuperTypeTarget( com.ibm.wala.shrike.shrikeCT.TypeAnnotationsReader.SuperTypeTarget target) { assert !mayAppearIn(target.getTargetInfo(), TypeAnnotationLocation.field_info); throw new UnsupportedOperationException(); } @Override public TypeAnnotationTarget visitTypeParameterBoundTarget( com.ibm.wala.shrike.shrikeCT.TypeAnnotationsReader.TypeParameterBoundTarget target) { assert !mayAppearIn(target.getTargetInfo(), TypeAnnotationLocation.field_info); throw new UnsupportedOperationException(); } @Override public TypeAnnotationTarget visitEmptyTarget( com.ibm.wala.shrike.shrikeCT.TypeAnnotationsReader.EmptyTarget target) { assert mayAppearIn(target.getTargetInfo(), TypeAnnotationLocation.field_info); return new EmptyTarget(); } @Override public TypeAnnotationTarget visitFormalParameterTarget( com.ibm.wala.shrike.shrikeCT.TypeAnnotationsReader.FormalParameterTarget target) { assert !mayAppearIn(target.getTargetInfo(), TypeAnnotationLocation.field_info); throw new UnsupportedOperationException(); } @Override public TypeAnnotationTarget visitThrowsTarget( com.ibm.wala.shrike.shrikeCT.TypeAnnotationsReader.ThrowsTarget target) { assert !mayAppearIn(target.getTargetInfo(), TypeAnnotationLocation.field_info); throw new UnsupportedOperationException(); } @Override public TypeAnnotationTarget visitLocalVarTarget( com.ibm.wala.shrike.shrikeCT.TypeAnnotationsReader.LocalVarTarget target) { assert !mayAppearIn(target.getTargetInfo(), TypeAnnotationLocation.field_info); throw new UnsupportedOperationException(); } @Override public TypeAnnotationTarget visitCatchTarget( com.ibm.wala.shrike.shrikeCT.TypeAnnotationsReader.CatchTarget target) { assert !mayAppearIn(target.getTargetInfo(), TypeAnnotationLocation.field_info); throw new UnsupportedOperationException(); } @Override public TypeAnnotationTarget visitOffsetTarget( com.ibm.wala.shrike.shrikeCT.TypeAnnotationsReader.OffsetTarget target) { assert !mayAppearIn(target.getTargetInfo(), TypeAnnotationLocation.field_info); throw new UnsupportedOperationException(); } @Override public TypeAnnotationTarget visitTypeArgumentTarget( com.ibm.wala.shrike.shrikeCT.TypeAnnotationsReader.TypeArgumentTarget target) { assert !mayAppearIn(target.getTargetInfo(), TypeAnnotationLocation.field_info); throw new UnsupportedOperationException(); } }; } /** @return the {@link Annotation} of this {@code TypeAnnotation} */ public Annotation getAnnotation() { return annotation; } /** * @return the typePath of this {@code TypeAnnotation} * @see <a href="https://docs.oracle.com/javase/specs/jvms/se8/html/jvms-4.html#jvms-4.7.20.2">JLS * (SE8), 4.7.20.2</a> */ public List<Pair<TypePathKind, Integer>> getTypePath() { return typePath; } /** @return the {@link TypeAnnotationTarget} of this {@code TypeAnnotation} */ public TypeAnnotationTarget getTypeAnnotationTarget() { return typeAnnotationTarget; } /** @return the {@link TargetType} of this {@code TypeAnnotation} */ public TargetType getTargetType() { return targetType; } }
35,614
34.902218
100
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/types/generics/ArrayTypeSignature.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.types.generics; public class ArrayTypeSignature extends TypeSignature { ArrayTypeSignature(String s) throws IllegalArgumentException { super(s); if (s.length() == 0) { throw new IllegalArgumentException(); } if (s.charAt(0) != '[') { throw new IllegalArgumentException(); } } @Override public boolean isClassTypeSignature() { return false; } @Override public boolean isTypeVariable() { return false; } public static ArrayTypeSignature make(String s) throws IllegalArgumentException { if (s == null) { throw new IllegalArgumentException("s is null"); } return new ArrayTypeSignature(s); } @Override public boolean isArrayTypeSignature() { return true; } public TypeSignature getContents() { return TypeSignature.make(rawString().substring(1)); } @Override public boolean isBaseType() { return false; } }
1,306
22.339286
83
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/types/generics/BaseType.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.types.generics; import com.ibm.wala.types.TypeReference; public class BaseType extends TypeSignature { private final TypeReference t; static final BaseType BOOLEAN = new BaseType(TypeReference.BooleanName.toString(), TypeReference.Boolean); static final BaseType BYTE = new BaseType(TypeReference.ByteName.toString(), TypeReference.Byte); static final BaseType SHORT = new BaseType(TypeReference.ShortName.toString(), TypeReference.Short); static final BaseType INT = new BaseType(TypeReference.IntName.toString(), TypeReference.Int); static final BaseType LONG = new BaseType(TypeReference.LongName.toString(), TypeReference.Long); static final BaseType FLOAT = new BaseType(TypeReference.FloatName.toString(), TypeReference.Float); static final BaseType DOUBLE = new BaseType(TypeReference.DoubleName.toString(), TypeReference.Double); static final BaseType CHAR = new BaseType(TypeReference.CharName.toString(), TypeReference.Char); static final BaseType VOID = new BaseType(TypeReference.VoidName.toString(), TypeReference.Void); private BaseType(String s, TypeReference t) { super(s); this.t = t; } @Override public boolean isClassTypeSignature() { return false; } @Override public boolean isTypeVariable() { return false; } public TypeReference getType() { return t; } @Override public boolean isArrayTypeSignature() { return false; } @Override public boolean isBaseType() { return true; } }
1,901
29.677419
99
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/types/generics/ClassSignature.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.types.generics; import com.ibm.wala.classLoader.IClass; import com.ibm.wala.classLoader.ShrikeClass; import com.ibm.wala.shrike.shrikeCT.InvalidClassFileException; import java.util.ArrayList; /** * Under construction. * * <p>ClassSignature: (&lt;FormalTypeParameter+&gt;)? SuperclassSignature SuperinterfaceSignature* * * <p>SuperclassSignature: ClassTypeSignature * * <p>SuperinterfaceSignature: ClassTypeSignature * * @author sjfink */ public class ClassSignature extends Signature { private ClassSignature(String sig) { super(sig); } public static ClassSignature make(String sig) { if (sig == null || sig.length() == 0) { throw new IllegalArgumentException("empty or null sig"); } return new ClassSignature(sig); } /** @return the formal type parameters, or null if none */ public FormalTypeParameter[] getFormalTypeParameters() { if (rawString().charAt(0) != '<') { // no formal type parameters return null; } int index = endOfFormalTypeParameters(); String[] args = FormalTypeParameter.parseForFormalTypeParameters(rawString().substring(0, index)); FormalTypeParameter[] result = new FormalTypeParameter[args.length]; for (int i = 0; i < args.length; i++) { result[i] = FormalTypeParameter.make(args[i]); } return result; } public ClassTypeSignature getSuperclassSignature() throws IllegalArgumentException { return ClassTypeSignature.makeClassTypeSig( rawString() .substring( endOfFormalTypeParameters(), endOfClassTypeSig(endOfFormalTypeParameters()))); } private int endOfClassTypeSig(int start) throws IllegalArgumentException { String s = rawString().substring(start); if (s.charAt(0) != 'L') { throw new IllegalArgumentException("malformed ClassSignature " + rawString()); } int i = 1; int depth = 0; while (depth > 0 || s.charAt(i) != ';') { if (s.charAt(i) == '<') { depth++; } if (s.charAt(i) == '>') { depth--; } i++; } return start + i + 1; } public ClassTypeSignature[] getSuperinterfaceSignatures() throws IllegalArgumentException { int start = endOfClassTypeSig(endOfFormalTypeParameters()); ArrayList<ClassTypeSignature> result = new ArrayList<>(); while (start < rawString().length() - 1) { int end = endOfClassTypeSig(start); result.add(ClassTypeSignature.makeClassTypeSig(rawString().substring(start, end))); start = end; } if (result.size() == 0) { return null; } ClassTypeSignature[] arr = new ClassTypeSignature[result.size()]; return result.toArray(arr); } private int endOfFormalTypeParameters() { if (rawString().charAt(0) != '<') { return 0; } int i = 1; int depth = 1; while (depth > 0) { if (rawString().charAt(i) == '>') { depth--; } if (rawString().charAt(i) == '<') { depth++; } i++; } return i; } /** @return the class signature, or null if none */ public static ClassSignature getClassSignature(IClass klass) throws InvalidClassFileException { if (klass instanceof ShrikeClass) { ShrikeClass sc = (ShrikeClass) klass; return sc.getClassSignature(); } else { return null; } } }
3,729
28.370079
98
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/types/generics/ClassTypeSignature.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.types.generics; import com.ibm.wala.classLoader.IClass; import com.ibm.wala.ipa.cha.IClassHierarchy; import com.ibm.wala.types.ClassLoaderReference; import com.ibm.wala.types.TypeName; import com.ibm.wala.types.TypeReference; import java.util.StringTokenizer; /** * Under construction. * * <p>ClassTypeSignature: L PackageSpecifier* SimpleClassTypeSignature ClassTypeSignatureSuffix* ; * * <p>SimpleClassTypeSignature: Identifier TypeArguments? * * <p>TypeArguments: &lt;TypeArguments+&gt; * * @author sjfink */ public class ClassTypeSignature extends TypeSignature { ClassTypeSignature(String s) throws IllegalArgumentException { super(s); if (s.length() == 0) { throw new IllegalArgumentException(); } if (s.charAt(0) != 'L') { throw new IllegalArgumentException(s); } if (s.charAt(s.length() - 1) != ';') { throw new IllegalArgumentException(s); } } public static ClassTypeSignature makeClassTypeSig(String s) throws IllegalArgumentException { if (s == null) { throw new IllegalArgumentException("s is null"); } return new ClassTypeSignature(s); } @Override public boolean isTypeVariable() { return false; } @Override public boolean isClassTypeSignature() { return true; } @Override public boolean isArrayTypeSignature() { return false; } /** Return the name of the raw type for this signature */ public TypeName getRawName() { // note: need to handle type arguments for raw signatures like the following: // Ljava/util/IdentityHashMap<TK;TV;>.IdentityHashMapIterator<TV;>; StringBuilder s = new StringBuilder(); StringTokenizer t = new StringTokenizer(rawString(), "."); while (t.hasMoreTokens()) { String x = t.nextToken(); s.append(x.replaceAll("<.*>", "").replace(";", "")); if (t.hasMoreElements()) { // note that '$' is the canonical separator for inner class names s.append('$'); } } return TypeName.string2TypeName(s.toString()); } public TypeArgument[] getTypeArguments() { // note: need to handle type arguments for raw signatures like the following: // Ljava/util/IdentityHashMap<TK;TV;>.IdentityHashMapIterator<TV;>; int lastDot = rawString().lastIndexOf('.'); if (rawString().indexOf('<', lastDot) == -1) { return null; } else { int start = rawString().indexOf('<', lastDot); int end = endOfTypeArguments(); return TypeArgument.make(rawString().substring(start, end)); } } private int endOfTypeArguments() { // note: need to handle type arguments for raw signatures like the following: // Ljava/util/IdentityHashMap<TK;TV;>.IdentityHashMapIterator<TV;>; int lastDot = rawString().lastIndexOf('.'); int i = rawString().indexOf('<', lastDot) + 1; assert (i > 0); int depth = 1; while (depth > 0) { if (rawString().charAt(i) == '>') { depth--; } if (rawString().charAt(i) == '<') { depth++; } i++; } return i; } @Override public boolean isBaseType() { return false; } public static IClass lookupClass(IClassHierarchy cha, ClassTypeSignature sig) { if (sig == null) { throw new IllegalArgumentException("sig is null"); } if (cha == null) { throw new IllegalArgumentException("cha is null"); } TypeReference t = TypeReference.findOrCreate(ClassLoaderReference.Application, sig.getRawName()); return cha.lookupClass(t); } }
3,917
28.238806
98
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/types/generics/FormalTypeParameter.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.types.generics; 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.shrike.shrikeCT.InvalidClassFileException; import com.ibm.wala.types.TypeReference; import java.util.ArrayList; import java.util.List; /** * Under construction. * * <p>FormalTypeParameter: Identifier ClassBound InterfaceBound* * * <p>ClassBound: : FieldTypeSignature? * * <p>InterfaceBound : FieldTypeSignature * * <p>FieldTypeSignature: ClassTypeSignature ArrayTypeSignature TypeVariableSignature */ public class FormalTypeParameter extends Signature { private final String id; private final TypeSignature classBound; private final TypeSignature[] interfaceBounds; private FormalTypeParameter(String s) throws IllegalArgumentException { super(s); id = parseForId(s); classBound = parseForClassBound(s); interfaceBounds = parseForInterfaceBounds(s); } private static TypeSignature parseForClassBound(String s) { int start = s.indexOf(':'); if (start == s.length() - 1) { return null; } int end = s.indexOf(':', start + 1); if (end == start + 1) { return null; } if (end == -1) { return TypeSignature.make(s.substring(start + 1)); } else { return TypeSignature.make(s.substring(start + 1, end)); } } private static TypeSignature[] parseForInterfaceBounds(String s) { List<TypeSignature> list = new ArrayList<>(); int start = s.indexOf(':'); if (start == s.length() - 1) { return null; } start = s.indexOf(':', start + 1); while (start != -1) { int end = s.indexOf(':', start + 1); if (end == -1) { list.add(TypeSignature.make(s.substring(start + 1))); } else { list.add(TypeSignature.make(s.substring(start + 1, end))); } start = s.indexOf(':', start + 1); } TypeSignature[] result = new TypeSignature[list.size()]; return list.toArray(result); } private static String parseForId(String s) throws IllegalArgumentException { if (s.indexOf(':') == -1) { throw new IllegalArgumentException(s); } return s.substring(0, s.indexOf(':')); } public static FormalTypeParameter make(String string) throws IllegalArgumentException { if (string == null) { throw new IllegalArgumentException("string is null"); } return new FormalTypeParameter(string); } public TypeSignature getClassBound() { return classBound; } public String getIdentifier() { return id; } /** * @param s a string that holds a sequence of formal type parameters beginning at index begin * @return the index where the next formal type parameter ends (actually, end +1) */ static int formalTypeParameterEnds(String s, int begin) { int result = begin; while (s.charAt(result) != ':') { result++; } do { assert (s.charAt(result) == ':'); switch (s.charAt(++result)) { case TypeReference.ClassTypeCode: { int depth = 0; while (s.charAt(result) != ';' || depth > 0) { if (s.charAt(result) == '<') { depth++; } if (s.charAt(result) == '>') { depth--; } result++; } result++; break; } case ':': break; default: assert false : "bad type signature list " + s + ' ' + (result - 1); } } while (s.charAt(result) == ':'); return result; } static String[] parseForFormalTypeParameters(String s) { ArrayList<String> sigs = new ArrayList<>(10); int beginToken = 1; while (s.charAt(beginToken) != '>') { int endToken = FormalTypeParameter.formalTypeParameterEnds(s, beginToken); sigs.add(s.substring(beginToken, endToken)); beginToken = endToken; } return sigs.toArray(new String[0]); } public TypeSignature[] getInterfaceBounds() { return interfaceBounds; } /** @return the formal type parameters, or null if none */ public static FormalTypeParameter[] getTypeParameters(IClass klass) throws InvalidClassFileException { if (klass instanceof ShrikeClass) { ShrikeClass sc = (ShrikeClass) klass; if (sc.getClassSignature() == null) { return null; } else { return sc.getClassSignature().getFormalTypeParameters(); } } else { return null; } } public static FormalTypeParameter[] getTypeParameters(IMethod method) throws InvalidClassFileException { if (method instanceof ShrikeCTMethod) { ShrikeCTMethod sm = (ShrikeCTMethod) method; if (sm.getMethodTypeSignature() == null) { return null; } else { return sm.getMethodTypeSignature().getFormalTypeParameters(); } } else { return null; } } }
5,372
27.579787
95
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/types/generics/MethodTypeSignature.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.types.generics; import com.ibm.wala.classLoader.IMethod; import com.ibm.wala.classLoader.ShrikeCTMethod; import com.ibm.wala.shrike.shrikeCT.InvalidClassFileException; /** * UNDER CONSTRUCTION. * * <p>MethodTypeSignature: FormalTypeParameters? (TypeSignature*) ReturnType ThrowsSignature* * * <p>ReturnType: TypeSignature * * @author sjfink */ public class MethodTypeSignature extends Signature { private MethodTypeSignature(String s) { super(s); } public static MethodTypeSignature make(String genericsSignature) throws IllegalArgumentException { if (genericsSignature == null) { throw new IllegalArgumentException("genericsSignature is null"); } if (genericsSignature.length() == 0) { throw new IllegalArgumentException(); } return new MethodTypeSignature(genericsSignature); } /** @return null if no arguments */ public TypeSignature[] getArguments() { String typeSig = rawString().replaceAll(".*\\(", "\\(").replaceAll("\\).*", "\\)"); String[] args = TypeSignature.parseForTypeSignatures(typeSig); if (args == null) { return null; } TypeSignature[] result = new TypeSignature[args.length]; for (int i = 0; i < args.length; i++) { result[i] = TypeSignature.make(args[i]); } return result; } public TypeSignature getReturnType() { String rtString = rawString().substring(rawString().indexOf(')') + 1); return TypeSignature.make(rtString); } public FormalTypeParameter[] getFormalTypeParameters() { if (rawString().charAt(0) != '<') { // no formal type parameters return null; } int index = endOfFormalTypeParameters(); String[] args = FormalTypeParameter.parseForFormalTypeParameters(rawString().substring(0, index)); FormalTypeParameter[] result = new FormalTypeParameter[args.length]; for (int i = 0; i < args.length; i++) { result[i] = FormalTypeParameter.make(args[i]); } return result; } private int endOfFormalTypeParameters() { if (rawString().charAt(0) != '<') { return 0; } int i = 1; int depth = 1; while (depth > 0) { if (rawString().charAt(i) == '>') { depth--; } if (rawString().charAt(i) == '<') { depth++; } i++; } return i; } /** @return {@link TypeSignature} for arguments, which includes information about generic types */ public static TypeSignature[] getArguments(IMethod method) throws InvalidClassFileException { if (method instanceof ShrikeCTMethod) { ShrikeCTMethod sm = (ShrikeCTMethod) method; if (sm.getMethodTypeSignature() == null) { return null; } else { return sm.getMethodTypeSignature().getArguments(); } } else { return null; } } public static MethodTypeSignature getMethodTypeSignature(IMethod method) throws InvalidClassFileException { if (method instanceof ShrikeCTMethod) { ShrikeCTMethod sm = (ShrikeCTMethod) method; return sm.getMethodTypeSignature(); } else { return null; } } }
3,487
28.559322
100
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/types/generics/Signature.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.types.generics; /** * Base class for wrappers around Strings that represent Signature annotations according to Java 5.0 * JVM spec enhancements. * * @author sjfink */ public abstract class Signature { private final String s; public Signature(final String s) { super(); if (s == null) { throw new IllegalArgumentException("s cannot be null"); } this.s = s; } @Override public String toString() { return s; } @Override public int hashCode() { final int PRIME = 31; int result = 1; result = PRIME * result + ((s == null) ? 0 : s.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 Signature other = (Signature) obj; if (s == null) { if (other.s != null) return false; } else if (!s.equals(other.s)) return false; return true; } protected String rawString() { return s; } }
1,418
22.65
100
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/types/generics/TypeArgument.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.types.generics; import com.ibm.wala.types.TypeReference; import java.util.ArrayList; import java.util.Arrays; import java.util.Iterator; /** * UNDER CONSTRUCTION * * <pre> TypeArgument: WildcardIndicator? FieldTypeSignature * * * WildcardIndicator: + - * * * </pre> * * @author sjfink */ public class TypeArgument extends Signature { private final TypeSignature sig; private final WildcardIndicator w; private enum WildcardIndicator { PLUS, MINUS } private static final TypeArgument WILDCARD = new TypeArgument("*") { @Override public boolean isWildcard() { return true; } @Override public String toString() { return "*"; } }; private TypeArgument(String s) { super(s); sig = null; w = null; } private TypeArgument(TypeSignature sig, WildcardIndicator w) { super(sig.rawString()); this.sig = sig; this.w = w; } public boolean isWildcard() { return false; } public static TypeArgument[] make(String s) throws IllegalArgumentException { if (s == null) { throw new IllegalArgumentException("s is null"); } if (s.length() == 0 || s.charAt(0) != '<') { throw new IllegalArgumentException(s); } if (s.charAt(s.length() - 1) != '>') { throw new IllegalArgumentException(s); } String[] args = parseForTypeArguments(s); TypeArgument[] result = new TypeArgument[args.length]; Arrays.setAll(result, i -> makeTypeArgument(args[i])); return result; } private static TypeArgument makeTypeArgument(String s) { switch (s.charAt(0)) { case '*': return WILDCARD; case '+': { TypeSignature sig = TypeSignature.make(s.substring(1)); return new TypeArgument(sig, WildcardIndicator.PLUS); } case '-': { TypeSignature sig = TypeSignature.make(s.substring(1)); return new TypeArgument(sig, WildcardIndicator.MINUS); } default: TypeSignature sig = TypeSignature.make(s); return new TypeArgument(sig, null); } } /** * @param typeArgs TypeSignature* * @return tokenize it */ static String[] parseForTypeArguments(String typeArgs) { ArrayList<String> args = new ArrayList<>(10); int i = 1; while (true) { switch (typeArgs.charAt(i++)) { case TypeReference.ClassTypeCode: { int off = i - 1; int depth = 0; while (typeArgs.charAt(i++) != ';' || depth > 0) { if (typeArgs.charAt(i - 1) == '<') { depth++; } if (typeArgs.charAt(i - 1) == '>') { depth--; } } args.add(typeArgs.substring(off, i)); continue; } case TypeReference.ArrayTypeCode: { int off = i - 1; while (typeArgs.charAt(i) == TypeReference.ArrayTypeCode) { ++i; } if (typeArgs.charAt(i) == TypeReference.ClassTypeCode) { while (typeArgs.charAt(i++) != ';') ; } else if (typeArgs.charAt(i++) == (byte) 'T') { while (typeArgs.charAt(i++) != ';') ; } args.add(typeArgs.substring(off, i)); continue; } case (byte) '-': case (byte) '+': case (byte) 'T': { // type variable int off = i - 1; while (typeArgs.charAt(i++) != ';') ; args.add(typeArgs.substring(off, i)); continue; } case (byte) '*': { // a wildcard args.add("*"); continue; } case (byte) '>': // end of argument list int size = args.size(); if (size == 0) { return null; } Iterator<String> it = args.iterator(); String[] result = new String[size]; for (int j = 0; j < size; j++) { result[j] = it.next(); } return result; default: assert false : "bad type argument list " + typeArgs; } } } public TypeSignature getFieldTypeSignature() { return sig; } @Override public String toString() { if (w == null) { return sig.toString(); } else if (w.equals(WildcardIndicator.PLUS)) { return '+' + sig.toString(); } else { return '-' + sig.toString(); } } }
4,915
24.604167
79
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/types/generics/TypeSignature.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.types.generics; import com.ibm.wala.types.TypeReference; import com.ibm.wala.util.debug.Assertions; import java.util.ArrayList; import java.util.Iterator; /** * UNDER CONSTRUCTION. * * <pre> TypeSignature: FieldTypeSignature BaseType (code for a primitive) * * FieldTypeSignature: ClassTypeSignature ArrayTypeSignature TypeVariableSignature * * TypeVariableSignature: T identifier ; * * </pre> * * @author sjfink */ public abstract class TypeSignature extends Signature { TypeSignature(String s) { super(s); } public static TypeSignature make(String s) throws IllegalArgumentException { if (s == null) { throw new IllegalArgumentException("s is null"); } if (s.length() == 0) { throw new IllegalArgumentException("illegal empty string s"); } assert (s.length() > 0); switch (s.charAt(0)) { case TypeReference.VoidTypeCode: Assertions.UNREACHABLE(); return null; case TypeReference.BooleanTypeCode: return BaseType.BOOLEAN; case TypeReference.ByteTypeCode: return BaseType.BYTE; case TypeReference.ShortTypeCode: return BaseType.SHORT; case TypeReference.IntTypeCode: return BaseType.INT; case TypeReference.LongTypeCode: return BaseType.LONG; case TypeReference.FloatTypeCode: return BaseType.FLOAT; case TypeReference.DoubleTypeCode: return BaseType.DOUBLE; case TypeReference.CharTypeCode: return BaseType.CHAR; case 'L': return ClassTypeSignature.makeClassTypeSig(s); case 'T': return TypeVariableSignature.make(s); case TypeReference.ArrayTypeCode: return ArrayTypeSignature.make(s); default: throw new IllegalArgumentException("malformed TypeSignature string:" + s); } } public abstract boolean isTypeVariable(); public abstract boolean isClassTypeSignature(); public abstract boolean isArrayTypeSignature(); public abstract boolean isBaseType(); /** * @param typeSigs TypeSignature* * @return tokenize it */ static String[] parseForTypeSignatures(String typeSigs) throws IllegalArgumentException { ArrayList<String> sigs = new ArrayList<>(10); if (typeSigs.length() < 2) { // TODO: check this? throw new IllegalArgumentException("illegal string of TypeSignature " + typeSigs); } int i = 1; while (true) { switch (typeSigs.charAt(i++)) { case TypeReference.VoidTypeCode: sigs.add(TypeReference.VoidName.toString()); continue; case TypeReference.BooleanTypeCode: sigs.add(TypeReference.BooleanName.toString()); continue; case TypeReference.ByteTypeCode: sigs.add(TypeReference.ByteName.toString()); continue; case TypeReference.ShortTypeCode: sigs.add(TypeReference.ShortName.toString()); continue; case TypeReference.IntTypeCode: sigs.add(TypeReference.IntName.toString()); continue; case TypeReference.LongTypeCode: sigs.add(TypeReference.LongName.toString()); continue; case TypeReference.FloatTypeCode: sigs.add(TypeReference.FloatName.toString()); continue; case TypeReference.DoubleTypeCode: sigs.add(TypeReference.DoubleName.toString()); continue; case TypeReference.CharTypeCode: sigs.add(TypeReference.CharName.toString()); continue; case TypeReference.ClassTypeCode: { int off = i - 1; int depth = 0; while (typeSigs.charAt(i++) != ';' || depth > 0) { if (typeSigs.charAt(i - 1) == '<') { depth++; } if (typeSigs.charAt(i - 1) == '>') { depth--; } } sigs.add(typeSigs.substring(off, i)); continue; } case TypeReference.ArrayTypeCode: { switch (typeSigs.charAt(i)) { case TypeReference.BooleanTypeCode: case TypeReference.ByteTypeCode: case TypeReference.IntTypeCode: sigs.add(typeSigs.substring(i - 1, i + 1)); break; case 'T': case TypeReference.ClassTypeCode: int off = i - 1; i++; int depth = 0; while (typeSigs.charAt(i++) != ';' || depth > 0) { if (typeSigs.charAt(i - 1) == '<') { depth++; } if (typeSigs.charAt(i - 1) == '>') { depth--; } } sigs.add(typeSigs.substring(off, i)); break; default: Assertions.UNREACHABLE("BANG " + typeSigs.charAt(i)); } continue; } case (byte) 'T': { // type variable int off = i - 1; while (typeSigs.charAt(i++) != ';') ; sigs.add(typeSigs.substring(off, i)); continue; } case (byte) ')': // end of parameter list int size = sigs.size(); if (size == 0) { return null; } Iterator<String> it = sigs.iterator(); String[] result = new String[size]; for (int j = 0; j < size; j++) { result[j] = it.next(); } return result; default: assert false : "bad type signature list " + typeSigs; } } } }
6,032
30.421875
91
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/types/generics/TypeVariableSignature.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.types.generics; import com.ibm.wala.classLoader.ShrikeClass; import com.ibm.wala.shrike.shrikeCT.InvalidClassFileException; import com.ibm.wala.util.debug.Assertions; /** * TypeVariableSignature: T identifier ; * * @author sjfink */ public class TypeVariableSignature extends TypeSignature { private TypeVariableSignature(String s) throws IllegalArgumentException { super(s); if (s.length() == 0) { throw new IllegalArgumentException(); } if (s.charAt(s.length() - 1) != ';') { throw new IllegalArgumentException(s); } } public static TypeVariableSignature make(String s) throws IllegalArgumentException { if (s == null) { throw new IllegalArgumentException("s is null"); } return new TypeVariableSignature(s); } @Override public boolean isClassTypeSignature() { return false; } @Override public boolean isTypeVariable() { return true; } @Override public boolean isArrayTypeSignature() { return false; } public String getIdentifier() { return rawString().substring(1, rawString().length() - 1); } @Override public boolean isBaseType() { return false; } /** @return -1 if there is no match */ public static int getTypeVariablePosition(TypeVariableSignature v, ShrikeClass klass) throws IllegalArgumentException { if (klass == null) { throw new IllegalArgumentException("klass cannot be null"); } try { ClassSignature sig = klass.getClassSignature(); if (sig == null) { return -1; } FormalTypeParameter[] fp = sig.getFormalTypeParameters(); if (fp == null) { return -1; } for (int i = 0; i < fp.length; i++) { FormalTypeParameter f = fp[i]; if (f.getIdentifier().equals(v.getIdentifier())) { return i; } } // System.err.println("sig : " + sig); // System.err.println("fp : " + fp.length); // for (FormalTypeParameter f : fp) { // System.err.println(f); // } // Assertions.UNREACHABLE("did not find " + v + " in " + klass ); return -1; } catch (InvalidClassFileException e) { e.printStackTrace(); Assertions.UNREACHABLE(); return -1; } } }
2,675
25.49505
87
java
WALA
WALA-master/core/src/test/java/com/ibm/wala/core/tests/arraybounds/ArrayboundsAnalysisTest.java
package com.ibm.wala.core.tests.arraybounds; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.not; import com.ibm.wala.analysis.arraybounds.ArrayOutOfBoundsAnalysis; import com.ibm.wala.analysis.arraybounds.ArrayOutOfBoundsAnalysis.UnnecessaryCheck; import com.ibm.wala.classLoader.IClass; import com.ibm.wala.classLoader.IMethod; import com.ibm.wala.core.tests.util.TestConstants; import com.ibm.wala.core.util.config.AnalysisScopeReader; import com.ibm.wala.ipa.callgraph.AnalysisOptions; import com.ibm.wala.ipa.callgraph.AnalysisScope; import com.ibm.wala.ipa.callgraph.impl.Everywhere; import com.ibm.wala.ipa.cha.ClassHierarchy; import com.ibm.wala.ipa.cha.ClassHierarchyException; import com.ibm.wala.ipa.cha.ClassHierarchyFactory; import com.ibm.wala.ssa.AllIntegerDueToBranchePiPolicy; import com.ibm.wala.ssa.DefaultIRFactory; import com.ibm.wala.ssa.IR; import com.ibm.wala.ssa.IRFactory; import com.ibm.wala.ssa.ISSABasicBlock; import com.ibm.wala.ssa.SSAArrayReferenceInstruction; import com.ibm.wala.ssa.SSAInstruction; import com.ibm.wala.types.TypeReference; import java.io.IOException; import org.hamcrest.Matcher; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ErrorCollector; /** * The test data should be grouped, according to the behavior of the analysis. All array accesses of * a class are to be detected as "in bound" or all are to be detected as "not in bound". * * <p>This test will only check if all found accesses behave accordingly and if the number of array * accesses is as expected. * * <p>So there is no explicit check for specific lines. * * @author Stephan Gocht {@code <stephan@gobro.de>} */ public class ArrayboundsAnalysisTest { private static final ClassLoader CLASS_LOADER = ArrayboundsAnalysisTest.class.getClassLoader(); private static final String DETECTABLE_TESTDATA = "Larraybounds/Detectable"; private static final int DETECTABLE_NUMBER_OF_ARRAY_ACCESS = 34; private static final String NOT_DETECTABLE_TESTDATA = "Larraybounds/NotDetectable"; private static final int NOT_DETECTABLE_NUMBER_OF_ARRAY_ACCESS = 10; private static final String NOT_IN_BOUND_TESTDATA = "Larraybounds/NotInBound"; private static final int NOT_IN_BOUND_TESTDATA_NUMBER_OF_ARRAY_ACCESS = 8; private static IRFactory<IMethod> irFactory; private static AnalysisOptions options; private static AnalysisScope scope; private static ClassHierarchy cha; @Rule public ErrorCollector collector = new ErrorCollector(); @BeforeClass public static void init() throws IOException, ClassHierarchyException { scope = AnalysisScopeReader.instance.readJavaScope(TestConstants.WALA_TESTDATA, null, CLASS_LOADER); cha = ClassHierarchyFactory.make(scope); irFactory = new DefaultIRFactory(); options = new AnalysisOptions(); options.getSSAOptions().setPiNodePolicy(new AllIntegerDueToBranchePiPolicy()); } public static IR getIr(IMethod method) { return irFactory.makeIR(method, Everywhere.EVERYWHERE, options.getSSAOptions()); } public static IClass getIClass(String name) { final TypeReference typeRef = TypeReference.findOrCreate(scope.getApplicationLoader(), name); return cha.lookupClass(typeRef); } @Test public void detectable() { IClass iClass = getIClass(DETECTABLE_TESTDATA); assertAllSameNecessity( iClass, DETECTABLE_NUMBER_OF_ARRAY_ACCESS, equalTo(UnnecessaryCheck.BOTH)); } @Test public void notDetectable() { IClass iClass = getIClass(NOT_DETECTABLE_TESTDATA); assertAllSameNecessity( iClass, NOT_DETECTABLE_NUMBER_OF_ARRAY_ACCESS, not(equalTo(UnnecessaryCheck.BOTH))); } @Test public void notInBound() { IClass iClass = getIClass(NOT_IN_BOUND_TESTDATA); assertAllSameNecessity( iClass, NOT_IN_BOUND_TESTDATA_NUMBER_OF_ARRAY_ACCESS, not(equalTo(UnnecessaryCheck.BOTH))); } public void assertAllSameNecessity( IClass iClass, int expectedNumberOfArrayAccesses, Matcher<UnnecessaryCheck> matcher) { int numberOfArrayAccesses = 0; for (IMethod method : iClass.getAllMethods()) { if (method.getDeclaringClass().equals(iClass)) { IR ir = getIr(method); StringBuilder builder = new StringBuilder(); for (ISSABasicBlock block : ir.getControlFlowGraph()) { for (SSAInstruction instruction : block) { builder.append(instruction); builder.append('\n'); } } String identifyer = method.getDeclaringClass().getName().toString() + "#" + method.getName().toString(); ArrayOutOfBoundsAnalysis analysis = new ArrayOutOfBoundsAnalysis(ir); for (SSAArrayReferenceInstruction key : analysis.getBoundsCheckNecessary().keySet()) { numberOfArrayAccesses++; UnnecessaryCheck unnecessary = analysis.getBoundsCheckNecessary().get(key); collector.checkThat( "Unexpected necessity for bounds check in " + identifyer + ":" + method.getLineNumber(key.iIndex()), unnecessary, matcher); } } } /* * Possible reasons for this to fail are: * * * *_NUMBER_OF_ARRAY_ACCESS is not set to the correct value (maybe the test * data has changed). * * Not all methods of the class analyzed. * * There is a bug, so not all array accesses are found. */ collector.checkThat( "Number of found array accesses is not as expected for " + iClass.getName().toString(), numberOfArrayAccesses, equalTo(expectedNumberOfArrayAccesses)); } @AfterClass public static void free() { scope = null; cha = null; irFactory = null; options = null; } }
5,881
35.308642
100
java
WALA
WALA-master/core/src/test/java/com/ibm/wala/core/tests/arraybounds/PruneArrayOutOfBoundExceptionEdge.java
package com.ibm.wala.core.tests.arraybounds; import static org.hamcrest.CoreMatchers.anyOf; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.everyItem; import static org.hamcrest.CoreMatchers.hasItem; import com.ibm.wala.analysis.arraybounds.ArrayOutOfBoundsAnalysis; import com.ibm.wala.analysis.nullpointer.IntraproceduralNullPointerAnalysis; import com.ibm.wala.classLoader.IClass; import com.ibm.wala.classLoader.IMethod; import com.ibm.wala.core.tests.util.TestConstants; import com.ibm.wala.core.util.config.AnalysisScopeReader; import com.ibm.wala.ipa.callgraph.AnalysisOptions; import com.ibm.wala.ipa.callgraph.AnalysisScope; import com.ibm.wala.ipa.callgraph.impl.Everywhere; import com.ibm.wala.ipa.cfg.PrunedCFG; import com.ibm.wala.ipa.cfg.exceptionpruning.ExceptionFilter2EdgeFilter; import com.ibm.wala.ipa.cfg.exceptionpruning.filter.ArrayOutOfBoundFilter; import com.ibm.wala.ipa.cfg.exceptionpruning.filter.CombinedExceptionFilter; import com.ibm.wala.ipa.cfg.exceptionpruning.filter.NullPointerExceptionFilter; import com.ibm.wala.ipa.cha.ClassHierarchy; import com.ibm.wala.ipa.cha.ClassHierarchyException; import com.ibm.wala.ipa.cha.ClassHierarchyFactory; import com.ibm.wala.ssa.AllIntegerDueToBranchePiPolicy; import com.ibm.wala.ssa.DefaultIRFactory; import com.ibm.wala.ssa.IR; import com.ibm.wala.ssa.IRFactory; import com.ibm.wala.ssa.ISSABasicBlock; import com.ibm.wala.ssa.SSACFG; import com.ibm.wala.ssa.SSAInstruction; import com.ibm.wala.types.TypeReference; import com.ibm.wala.util.collections.Pair; import java.io.IOException; import java.util.LinkedHashSet; import org.hamcrest.Matcher; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ErrorCollector; /** * This test will check that: * * <ul> * <li>no normal edge is removed * <li>in case of an exceptional edge being removed, the instruction causing the edge is an * instruction that is able to throw a NullpointerException or an * ArrayIndexOutOfBoundException and no other exception may be thrown by this instruction. * <li>the number of removed edges is as expected * </ul> * * So there is no explicit check for specific lines. * * <p>For an example how to use the exception pruning see {@link * PruneArrayOutOfBoundExceptionEdge#computeCfgAndPrunedCFG(IMethod)} * * @author Stephan Gocht {@code <stephan@gobro.de>} */ public class PruneArrayOutOfBoundExceptionEdge { private static final ClassLoader CLASS_LOADER = PruneArrayOutOfBoundExceptionEdge.class.getClassLoader(); private static final String DETECTABLE_TESTDATA = "Larraybounds/Detectable"; /** * The number of Basic Blocks, which have an exception edge, that should be removed. (#[array * access] + #[other]) */ private static final int DETECTABLE_EXPECTED_COUNT = 34 + 2; private static final String NOT_DETECTABLE_TESTDATA = "Larraybounds/NotDetectable"; /** * The number of Basic Blocks, which have an exception edge, that should be removed. (#[array * access] + #[other]) */ private static final int NOT_DETECTABLE_EXPECTED_COUNT = 0 + 3; private static final String NOT_IN_BOUND_TESTDATA = "Larraybounds/NotInBound"; /** * The number of Basic Blocks, which have an exception edge, that should be removed. (#[array * access] + #[other]) */ private static final int NOT_IN_BOUND_EXPECTED_COUNT = 0 + 1; private static IRFactory<IMethod> irFactory; private static AnalysisOptions options; private static AnalysisScope scope; private static ClassHierarchy cha; @Rule public ErrorCollector collector = new ErrorCollector(); @BeforeClass public static void init() throws IOException, ClassHierarchyException { scope = AnalysisScopeReader.instance.readJavaScope(TestConstants.WALA_TESTDATA, null, CLASS_LOADER); cha = ClassHierarchyFactory.make(scope); irFactory = new DefaultIRFactory(); options = new AnalysisOptions(); options.getSSAOptions().setPiNodePolicy(new AllIntegerDueToBranchePiPolicy()); } private static IR getIr(IMethod method) { return irFactory.makeIR(method, Everywhere.EVERYWHERE, options.getSSAOptions()); } public static Pair<SSACFG, PrunedCFG<SSAInstruction, ISSABasicBlock>> computeCfgAndPrunedCFG( IMethod method) { IR ir = getIr(method); SSACFG cfg = ir.getControlFlowGraph(); ArrayOutOfBoundsAnalysis arrayBoundsAnalysis = new ArrayOutOfBoundsAnalysis(ir); IntraproceduralNullPointerAnalysis nullPointerAnalysis = new IntraproceduralNullPointerAnalysis(ir); CombinedExceptionFilter<SSAInstruction> filter = new CombinedExceptionFilter<>(); filter.add(new ArrayOutOfBoundFilter(arrayBoundsAnalysis)); filter.add(new NullPointerExceptionFilter(nullPointerAnalysis)); ExceptionFilter2EdgeFilter<ISSABasicBlock> edgeFilter = new ExceptionFilter2EdgeFilter<>(filter, cha, cfg); PrunedCFG<SSAInstruction, ISSABasicBlock> prunedCfg = PrunedCFG.make(cfg, edgeFilter); return Pair.make(cfg, prunedCfg); } private static IClass getIClass(String name) { final TypeReference typeRef = TypeReference.findOrCreate(scope.getApplicationLoader(), name); return cha.lookupClass(typeRef); } @Test public void detectable() { IClass iClass = getIClass(DETECTABLE_TESTDATA); checkRemovedEdges(iClass, DETECTABLE_EXPECTED_COUNT); } @Test public void notDetectable() { IClass iClass = getIClass(NOT_DETECTABLE_TESTDATA); checkRemovedEdges(iClass, NOT_DETECTABLE_EXPECTED_COUNT); } @Test public void notInBound() { IClass iClass = getIClass(NOT_IN_BOUND_TESTDATA); checkRemovedEdges(iClass, NOT_IN_BOUND_EXPECTED_COUNT); } private void checkRemovedEdges(IClass iClass, int expectedNumberOfArrayAccesses) { int numberOfDeletedExceptionEdges = 0; for (IMethod method : iClass.getAllMethods()) { if (method.getDeclaringClass().equals(iClass)) { String identifyer = method.getDeclaringClass().getName().toString() + "#" + method.getName().toString(); Pair<SSACFG, PrunedCFG<SSAInstruction, ISSABasicBlock>> cfgs = computeCfgAndPrunedCFG(method); SSACFG cfg = cfgs.fst; PrunedCFG<SSAInstruction, ISSABasicBlock> prunedCfg = cfgs.snd; for (ISSABasicBlock block : cfg) { checkNormalSuccessors(cfg, prunedCfg, block); boolean isEdgeRemoved = checkExceptionalSuccessors(block, cfg, prunedCfg, method, identifyer); numberOfDeletedExceptionEdges += isEdgeRemoved ? 1 : 0; } } } /* * Possible reasons for this to fail are: * * * *_NUMBER_OF_BB_WITHOUT_EXCEPTION is not set to the correct value (maybe * the test data has changed). * * Not all methods of the class analyzed. * * There is a bug, so not all edges are deleted. */ collector.checkThat( "Number of deleted edges is not as expected for " + iClass.getName().toString(), numberOfDeletedExceptionEdges, equalTo(expectedNumberOfArrayAccesses)); } /** * Check in case of an exceptional edge being removed, the instruction causing the edge is an * instruction that is able to throw a NullpointerException or an ArrayIndexOutOfBoundException * and no other exception may be thrown by this instruction. * * @return if an edge of block was removed */ private boolean checkExceptionalSuccessors( ISSABasicBlock block, SSACFG cfg, PrunedCFG<SSAInstruction, ISSABasicBlock> prunedCfg, IMethod method, String identifyer) { boolean isEdgeRemoved = false; LinkedHashSet<ISSABasicBlock> exceptionalSuccessorCfg = new LinkedHashSet<>(cfg.getExceptionalSuccessors(block)); LinkedHashSet<ISSABasicBlock> exceptionalSuccessorPruned = new LinkedHashSet<>(prunedCfg.getExceptionalSuccessors(block)); if (!exceptionalSuccessorCfg.equals(exceptionalSuccessorPruned)) { isEdgeRemoved = true; if (block.getLastInstructionIndex() >= 0) { SSAInstruction lastInstruction = block.getLastInstruction(); lastInstruction.getExceptionTypes(); final Matcher<TypeReference> isJLNPE = equalTo(TypeReference.JavaLangNullPointerException); final Matcher<TypeReference> isJLAIOOBE = equalTo(TypeReference.JavaLangArrayIndexOutOfBoundsException); final Matcher<Iterable<? super TypeReference>> hasJLNPE = hasItem(isJLNPE); final Matcher<Iterable<? super TypeReference>> hasJLAIOOBE = hasItem(isJLAIOOBE); final Matcher<Iterable<? super TypeReference>> matcher1 = anyOf(hasJLNPE, hasJLAIOOBE); collector.checkThat( "Edge deleted but cause instruction can't throw NullPointerException" + "nor ArrayIndexOutOfBoundsException: " + identifyer + ":" + method.getLineNumber(lastInstruction.iIndex()), lastInstruction.getExceptionTypes(), matcher1); final Matcher<TypeReference> itemMatcher = anyOf(isJLNPE, isJLAIOOBE); collector.checkThat( "Edge deleted but cause instruction throws other exceptions as NullPointerException" + "and ArrayIndexOutOfBoundsException: " + identifyer + ":" + method.getLineNumber(lastInstruction.iIndex()), lastInstruction.getExceptionTypes(), everyItem(itemMatcher)); } else { collector.addError( new Throwable( "Exceptional edge deleted, but no instruction as cause. - No last instruction.")); } } return isEdgeRemoved; } private void checkNormalSuccessors( SSACFG cfg, PrunedCFG<SSAInstruction, ISSABasicBlock> prunedCfg, ISSABasicBlock block) { LinkedHashSet<ISSABasicBlock> normalSuccessorCfg = new LinkedHashSet<>(cfg.getNormalSuccessors(block)); LinkedHashSet<ISSABasicBlock> normalSuccessorPruned = new LinkedHashSet<>(prunedCfg.getNormalSuccessors(block)); collector.checkThat("", normalSuccessorPruned, equalTo(normalSuccessorCfg)); } @AfterClass public static void free() { scope = null; cha = null; irFactory = null; options = null; } }
10,373
38
100
java
WALA
WALA-master/core/src/test/java/com/ibm/wala/core/tests/basic/ExtensionGraphTest.java
/* * Copyright (c) 2002 - 2014 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package com.ibm.wala.core.tests.basic; import com.ibm.wala.util.collections.IteratorUtil; import com.ibm.wala.util.graph.NumberedGraph; import com.ibm.wala.util.graph.impl.ExtensionGraph; import com.ibm.wala.util.graph.impl.SlowSparseNumberedGraph; import com.ibm.wala.util.graph.traverse.SCCIterator; import org.junit.Assert; import org.junit.Test; public class ExtensionGraphTest { private static NumberedGraph<String> makeBaseGraph() { NumberedGraph<String> base = SlowSparseNumberedGraph.make(); base.addNode("A"); base.addNode("B"); base.addNode("C"); base.addNode("D"); base.addNode("E"); base.addNode("F"); base.addNode("G"); base.addNode("H"); base.addEdge("A", "B"); base.addEdge("B", "C"); base.addEdge("A", "D"); base.addEdge("D", "E"); base.addEdge("A", "F"); base.addEdge("F", "G"); base.addEdge("C", "H"); base.addEdge("E", "H"); base.addEdge("G", "H"); return base; } private static void augmentA(NumberedGraph<String> base) { base.addEdge("C", "B"); base.addEdge("E", "D"); base.addEdge("G", "F"); } private static void augmentB(NumberedGraph<String> base) { base.addNode("I"); base.addNode("J"); base.addEdge("I", "J"); base.addEdge("A", "I"); base.addEdge("H", "J"); } private static void augmentC(NumberedGraph<String> base) { base.addEdge("H", "A"); } @Test public void testAugment() { NumberedGraph<String> base = makeBaseGraph(); Assert.assertEquals("base has 8 SCCs", 8, IteratorUtil.count(new SCCIterator<>(base))); NumberedGraph<String> x = new ExtensionGraph<>(base); augmentA(x); Assert.assertEquals("base+A has 5 SCCs", 5, IteratorUtil.count(new SCCIterator<>(x))); Assert.assertEquals("base has 8 SCCs", 8, IteratorUtil.count(new SCCIterator<>(base))); NumberedGraph<String> y = new ExtensionGraph<>(x); augmentB(y); Assert.assertEquals("base+A+B has 7 SCCs", 7, IteratorUtil.count(new SCCIterator<>(y))); Assert.assertEquals("base+A has 5 SCCs", 5, IteratorUtil.count(new SCCIterator<>(x))); Assert.assertEquals("base has 8 SCCs", 8, IteratorUtil.count(new SCCIterator<>(base))); NumberedGraph<String> z = new ExtensionGraph<>(y); augmentC(z); Assert.assertEquals("base+A+B+C has 3 SCCs", 3, IteratorUtil.count(new SCCIterator<>(z))); Assert.assertEquals("base+A+B has 7 SCCs", 7, IteratorUtil.count(new SCCIterator<>(y))); Assert.assertEquals("base+A has 5 SCCs", 5, IteratorUtil.count(new SCCIterator<>(x))); Assert.assertEquals("base has 8 SCCs", 8, IteratorUtil.count(new SCCIterator<>(base))); } }
3,025
31.891304
94
java
WALA
WALA-master/core/src/test/java/com/ibm/wala/core/tests/basic/FloydWarshallTest.java
/* * Copyright (c) 2002 - 2010 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package com.ibm.wala.core.tests.basic; import static org.junit.Assert.assertEquals; import com.ibm.wala.core.tests.util.WalaTestCase; import com.ibm.wala.util.graph.INodeWithNumberedEdges; import com.ibm.wala.util.graph.NumberedGraph; import com.ibm.wala.util.graph.impl.DelegatingNumberedGraph; import com.ibm.wala.util.graph.traverse.FloydWarshall; import com.ibm.wala.util.graph.traverse.FloydWarshall.GetPath; import com.ibm.wala.util.graph.traverse.FloydWarshall.GetPaths; import com.ibm.wala.util.intset.IntSet; import com.ibm.wala.util.intset.IntSetUtil; import com.ibm.wala.util.intset.MutableIntSet; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Set; import org.junit.Assert; import org.junit.Test; public class FloydWarshallTest extends WalaTestCase { public static class Node implements INodeWithNumberedEdges { private final int number; private final MutableIntSet preds = IntSetUtil.make(); private final MutableIntSet succs = IntSetUtil.make(); @Override public int getGraphNodeId() { return number; } public Node(int number) { this.number = number; } @Override public void setGraphNodeId(int number) { throw new UnsupportedOperationException(); } @Override public IntSet getSuccNumbers() { return succs; } @Override public IntSet getPredNumbers() { return preds; } @Override public void addSucc(int n) { succs.add(n); } @Override public void addPred(int n) { preds.add(n); } @Override public void removeAllIncidentEdges() { throw new UnsupportedOperationException(); } @Override public void removeIncomingEdges() { throw new UnsupportedOperationException(); } @Override public void removeOutgoingEdges() { throw new UnsupportedOperationException(); } @Override public String toString() { return "<" + number + ">"; } } public static NumberedGraph<Node> makeGraph() { NumberedGraph<Node> G = new DelegatingNumberedGraph<>(); for (int i = 0; i <= 8; i++) { G.addNode(new Node(i)); } G.addEdge(G.getNode(1), G.getNode(2)); G.addEdge(G.getNode(2), G.getNode(3)); G.addEdge(G.getNode(3), G.getNode(4)); G.addEdge(G.getNode(3), G.getNode(5)); G.addEdge(G.getNode(4), G.getNode(6)); G.addEdge(G.getNode(5), G.getNode(7)); G.addEdge(G.getNode(6), G.getNode(8)); G.addEdge(G.getNode(7), G.getNode(8)); G.addEdge(G.getNode(6), G.getNode(4)); G.addEdge(G.getNode(6), G.getNode(2)); return G; } private final NumberedGraph<Node> G = makeGraph(); private final int[][] shortestPaths = new int[][] { { Integer.MAX_VALUE, Integer.MAX_VALUE, Integer.MAX_VALUE, Integer.MAX_VALUE, Integer.MAX_VALUE, Integer.MAX_VALUE, Integer.MAX_VALUE, Integer.MAX_VALUE, Integer.MAX_VALUE }, {Integer.MAX_VALUE, Integer.MAX_VALUE, 1, 2, 3, 3, 4, 4, 5}, {Integer.MAX_VALUE, Integer.MAX_VALUE, 4, 1, 2, 2, 3, 3, 4}, {Integer.MAX_VALUE, Integer.MAX_VALUE, 3, 4, 1, 1, 2, 2, 3}, {Integer.MAX_VALUE, Integer.MAX_VALUE, 2, 3, 2, 4, 1, 5, 2}, { Integer.MAX_VALUE, Integer.MAX_VALUE, Integer.MAX_VALUE, Integer.MAX_VALUE, Integer.MAX_VALUE, Integer.MAX_VALUE, Integer.MAX_VALUE, 1, 2 }, {Integer.MAX_VALUE, Integer.MAX_VALUE, 1, 2, 1, 3, 2, 4, 1}, { Integer.MAX_VALUE, Integer.MAX_VALUE, Integer.MAX_VALUE, Integer.MAX_VALUE, Integer.MAX_VALUE, Integer.MAX_VALUE, Integer.MAX_VALUE, Integer.MAX_VALUE, 1 }, { Integer.MAX_VALUE, Integer.MAX_VALUE, Integer.MAX_VALUE, Integer.MAX_VALUE, Integer.MAX_VALUE, Integer.MAX_VALUE, Integer.MAX_VALUE, Integer.MAX_VALUE, Integer.MAX_VALUE } }; @Test public void TestPathLengths() { int[][] result = FloydWarshall.shortestPathLengths(G); assertEquals(result.length, shortestPaths.length); for (int i = 0; i < result.length; i++) { assertEquals(result[i].length, shortestPaths[i].length); for (int j = 0; j < result[i].length; j++) { assertEquals(result[i][j], shortestPaths[i][j]); } } } @Test public void TestShortestPath() { GetPath<Node> result = FloydWarshall.allPairsShortestPath(G); assertEquals( result.getPath(G.getNode(1), G.getNode(3)), Collections.singletonList(G.getNode(2))); assertEquals( result.getPath(G.getNode(5), G.getNode(8)), Collections.singletonList(G.getNode(7))); assertEquals( result.getPath(G.getNode(1), G.getNode(7)), Arrays.asList(G.getNode(2), G.getNode(3), G.getNode(5))); assertEquals( result.getPath(G.getNode(1), G.getNode(6)), Arrays.asList(G.getNode(2), G.getNode(3), G.getNode(4))); } @Test public void TestShortestPaths() { GetPaths<Node> result = FloydWarshall.allPairsShortestPaths(G); Set<List<Node>> expectedPaths = expectedPaths(G); Set<List<Node>> resultPaths = result.getPaths(G.getNode(1), G.getNode(8)); assertEquals(resultPaths.size(), expectedPaths.size()); for (List<Node> rp : resultPaths) { Assert.assertTrue(expectedPaths.contains(rp)); } } public static Set<List<Node>> expectedPaths(NumberedGraph<Node> G) { Set<List<Node>> paths = new HashSet<>(); paths.add( new ArrayList<>(Arrays.asList(G.getNode(2), G.getNode(3), G.getNode(4), G.getNode(6)))); paths.add( new ArrayList<>(Arrays.asList(G.getNode(2), G.getNode(3), G.getNode(5), G.getNode(7)))); return paths; } }
6,394
27.806306
96
java
WALA
WALA-master/core/src/test/java/com/ibm/wala/core/tests/basic/GraphDataflowTest.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.basic; import com.ibm.wala.core.tests.util.WalaTestCase; import com.ibm.wala.dataflow.graph.AbstractMeetOperator; import com.ibm.wala.dataflow.graph.BitVectorFilter; import com.ibm.wala.dataflow.graph.BitVectorFramework; import com.ibm.wala.dataflow.graph.BitVectorIdentity; import com.ibm.wala.dataflow.graph.BitVectorSolver; import com.ibm.wala.dataflow.graph.BitVectorUnion; import com.ibm.wala.dataflow.graph.BitVectorUnionConstant; import com.ibm.wala.dataflow.graph.ITransferFunctionProvider; import com.ibm.wala.fixpoint.BitVectorVariable; import com.ibm.wala.fixpoint.UnaryOperator; import com.ibm.wala.util.CancelException; import com.ibm.wala.util.debug.Assertions; import com.ibm.wala.util.graph.Graph; import com.ibm.wala.util.graph.impl.SlowSparseNumberedGraph; import com.ibm.wala.util.intset.BitVector; import com.ibm.wala.util.intset.MutableMapping; import com.ibm.wala.util.intset.OrdinalSetMapping; import org.junit.Assert; import org.junit.Test; /** Simple Regression test for a graph-based dataflow problem. */ public class GraphDataflowTest extends WalaTestCase { public static final String nodeNames = "ABCDEFGH"; protected static final String[] nodes = new String[nodeNames.length()]; private static BitVector zero() { BitVector b = new BitVector(); b.set(0); return b; } private static BitVector one() { BitVector b = new BitVector(); b.set(1); return b; } /** A simple test of the GraphBitVectorDataflow system */ @Test public void testSolverNodeEdge() throws CancelException { Graph<String> G = buildGraph(); String result = solveNodeEdge(G); System.err.println(result); if (!result.equals(expectedStringNodeEdge())) { System.err.println("Uh oh."); System.err.println(expectedStringNodeEdge()); } Assert.assertEquals(expectedStringNodeEdge(), result); } @Test public void testSolverNodeOnly() throws CancelException { Graph<String> G = buildGraph(); String result = solveNodeOnly(G); System.err.println(result); Assert.assertEquals(expectedStringNodeOnly(), result); } /** @return the expected dataflow result as a String */ public static String expectedStringNodeOnly() { return "------\n" + "Node A(0) = { 0 }\n" + "Node B(1) = { 0 1 }\n" + "Node C(2) = { 0 1 2 }\n" + "Node D(3) = { 0 1 3 }\n" + "Node E(4) = { 0 1 2 3 4 }\n" + "Node F(5) = { 0 1 2 3 4 5 }\n" + "Node G(6) = { 6 }\n" + "Node H(7) = { 7 }\n"; } public static String expectedStringNodeEdge() { return "------\n" + "Node A(0) = { 0 }\n" + "Node B(1) = { 0 1 }\n" + "Node C(2) = { 0 2 }\n" + "Node D(3) = { 1 3 }\n" + "Node E(4) = { 0 1 2 3 4 }\n" + "Node F(5) = { 0 1 2 3 4 5 }\n" + "Node G(6) = { 6 }\n" + "Node H(7) = { 7 }\n"; } /** @return a graph with the expected structure */ public static Graph<String> buildGraph() { Graph<String> G = SlowSparseNumberedGraph.make(); for (int i = 0; i < nodeNames.length(); i++) { String n = nodeNames.substring(i, i + 1); G.addNode(n); nodes[i] = n; } G.addEdge(nodes[0], nodes[1]); G.addEdge(nodes[1], nodes[2]); G.addEdge(nodes[1], nodes[3]); G.addEdge(nodes[2], nodes[4]); G.addEdge(nodes[3], nodes[4]); G.addEdge(nodes[4], nodes[5]); return G; } /** Solve the dataflow system and return the result as a string */ public static String solveNodeOnly(Graph<String> G) throws CancelException { final OrdinalSetMapping<String> values = new MutableMapping<>(nodes); ITransferFunctionProvider<String, BitVectorVariable> functions = new ITransferFunctionProvider<>() { @Override public UnaryOperator<BitVectorVariable> getNodeTransferFunction(String node) { return new BitVectorUnionConstant(values.getMappedIndex(node)); } @Override public boolean hasNodeTransferFunctions() { return true; } @Override public UnaryOperator<BitVectorVariable> getEdgeTransferFunction(String from, String to) { Assertions.UNREACHABLE(); return null; } @Override public boolean hasEdgeTransferFunctions() { return false; } @Override public AbstractMeetOperator<BitVectorVariable> getMeetOperator() { return BitVectorUnion.instance(); } }; BitVectorFramework<String, String> F = new BitVectorFramework<>(G, functions, values); BitVectorSolver<String> s = new BitVectorSolver<>(F); s.solve(null); return result2String(s); } public static String solveNodeEdge(Graph<String> G) throws CancelException { final OrdinalSetMapping<String> values = new MutableMapping<>(nodes); ITransferFunctionProvider<String, BitVectorVariable> functions = new ITransferFunctionProvider<>() { @Override public UnaryOperator<BitVectorVariable> getNodeTransferFunction(String node) { return new BitVectorUnionConstant(values.getMappedIndex(node)); } @Override public boolean hasNodeTransferFunctions() { return true; } @Override public UnaryOperator<BitVectorVariable> getEdgeTransferFunction(String from, String to) { if (from == nodes[1] && to == nodes[3]) return new BitVectorFilter(zero()); else if (from == nodes[1] && to == nodes[2]) return new BitVectorFilter(one()); else { return BitVectorIdentity.instance(); } } @Override public boolean hasEdgeTransferFunctions() { return true; } @Override public AbstractMeetOperator<BitVectorVariable> getMeetOperator() { return BitVectorUnion.instance(); } }; BitVectorFramework<String, String> F = new BitVectorFramework<>(G, functions, values); BitVectorSolver<String> s = new BitVectorSolver<>(F); s.solve(null); return result2String(s); } public static String result2String(BitVectorSolver<String> solver) { StringBuilder result = new StringBuilder("------\n"); for (int i = 0; i < nodes.length; i++) { String n = nodes[i]; BitVectorVariable varI = solver.getOut(n); String s = varI.toString(); result.append("Node ").append(n).append('(').append(i).append(") = ").append(s).append('\n'); } return result.toString(); } }
7,021
33.087379
99
java
WALA
WALA-master/core/src/test/java/com/ibm/wala/core/tests/basic/OrdinalSetTest.java
/* * Copyright (c) 2008 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package com.ibm.wala.core.tests.basic; import com.ibm.wala.core.tests.util.WalaTestCase; import com.ibm.wala.util.intset.OrdinalSet; import org.junit.Test; /** JUnit tests for some {@link OrdinalSet} operations. */ public class OrdinalSetTest extends WalaTestCase { @Test public void test1() { OrdinalSet.unify(OrdinalSet.empty(), OrdinalSet.empty()); } }
737
28.52
72
java
WALA
WALA-master/core/src/test/java/com/ibm/wala/core/tests/basic/PathFinderTest.java
/* * Copyright (c) 2013 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package com.ibm.wala.core.tests.basic; import com.ibm.wala.util.graph.Graph; import com.ibm.wala.util.graph.impl.SlowSparseNumberedGraph; import com.ibm.wala.util.graph.traverse.DFSAllPathsFinder; import java.util.List; import org.junit.Assert; import org.junit.Test; public class PathFinderTest { private static Graph<String> createGraph(String edges) { Graph<String> g = SlowSparseNumberedGraph.make(); for (int i = 0; i < edges.length(); i += 2) { String from = edges.substring(i, i + 1); if (!g.containsNode(from)) { g.addNode(from); } String to = edges.substring(i + 1, i + 2); if (!g.containsNode(to)) { g.addNode(to); } g.addEdge(from, to); } return g; } private static DFSAllPathsFinder<String> makeFinder( Graph<String> g, String start, final String end) { return new DFSAllPathsFinder<>(g, start, end::equals); } private static void checkPaths(DFSAllPathsFinder<String> paths, int expectedCount) { int count = 0; List<String> path; while ((path = paths.find()) != null) { System.err.println(path); count++; } Assert.assertEquals(expectedCount, count); } private static final String edges1 = "ABBCBDCECFDGDHEIFIGJHJJKIKKL"; @Test public void testPaths1() { Graph<String> g = createGraph(edges1); DFSAllPathsFinder<String> paths = makeFinder(g, "A", "L"); checkPaths(paths, 4); } private static final String edges2 = "ABBCBDCECFDGDHEIFIGJHJJKIKKCKL"; @Test public void testPaths2() { Graph<String> g = createGraph(edges2); DFSAllPathsFinder<String> paths = makeFinder(g, "A", "L"); checkPaths(paths, 4); } private static final String edges3 = "ABBHBCBDCECFDGDHEIFIGJHJJKIKKCKL"; @Test public void testPaths3() { Graph<String> g = createGraph(edges3); DFSAllPathsFinder<String> paths = makeFinder(g, "A", "L"); checkPaths(paths, 5); } private static final String edges4 = "ABACADAEBABCBDBECACBCDCEDADBDCDEEAEBECED"; @Test public void testPaths4() { Graph<String> g = createGraph(edges4); DFSAllPathsFinder<String> paths = makeFinder(g, "A", "E"); checkPaths(paths, 1 + 3 + 6 + 6); } }
2,583
27.395604
86
java
WALA
WALA-master/core/src/test/java/com/ibm/wala/core/tests/basic/PrimitivesTest.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.basic; import com.ibm.wala.core.tests.util.WalaTestCase; import com.ibm.wala.util.collections.BimodalMap; import com.ibm.wala.util.collections.HashSetFactory; import com.ibm.wala.util.collections.Iterator2Collection; import com.ibm.wala.util.collections.Iterator2Iterable; import com.ibm.wala.util.collections.SmallMap; import com.ibm.wala.util.graph.Graph; import com.ibm.wala.util.graph.NumberedGraph; import com.ibm.wala.util.graph.dominators.Dominators; import com.ibm.wala.util.graph.impl.SlowSparseNumberedGraph; import com.ibm.wala.util.graph.traverse.BFSPathFinder; import com.ibm.wala.util.graph.traverse.BoundedBFSIterator; import com.ibm.wala.util.intset.BasicNaturalRelation; import com.ibm.wala.util.intset.BimodalMutableIntSetFactory; import com.ibm.wala.util.intset.BitVector; import com.ibm.wala.util.intset.BitVectorBase; import com.ibm.wala.util.intset.BitVectorIntSetFactory; import com.ibm.wala.util.intset.IBinaryNaturalRelation; import com.ibm.wala.util.intset.IntPair; import com.ibm.wala.util.intset.IntSet; import com.ibm.wala.util.intset.IntSetUtil; import com.ibm.wala.util.intset.IntegerUnionFind; import com.ibm.wala.util.intset.LongSet; import com.ibm.wala.util.intset.LongSetUtil; import com.ibm.wala.util.intset.MutableIntSet; import com.ibm.wala.util.intset.MutableIntSetFactory; import com.ibm.wala.util.intset.MutableLongSet; import com.ibm.wala.util.intset.MutableLongSetFactory; import com.ibm.wala.util.intset.MutableSharedBitVectorIntSetFactory; import com.ibm.wala.util.intset.MutableSparseIntSetFactory; import com.ibm.wala.util.intset.MutableSparseLongSetFactory; import com.ibm.wala.util.intset.OffsetBitVector; import com.ibm.wala.util.intset.SemiSparseMutableIntSet; import com.ibm.wala.util.intset.SemiSparseMutableIntSetFactory; import com.ibm.wala.util.intset.SparseIntSet; import com.ibm.wala.util.intset.SparseLongSet; import java.util.Collection; import java.util.HashSet; import java.util.List; import java.util.Map; import org.junit.Assert; import org.junit.Test; /** JUnit tests for some primitive operations. */ @SuppressWarnings("UnnecessaryBoxing") public class PrimitivesTest extends WalaTestCase { /** Test the MutableSparseIntSet implementation */ private static void doMutableIntSet(MutableIntSetFactory<?> factory) { MutableIntSet v = factory.parse("{9,17}"); MutableIntSet w = factory.make(new int[] {}); MutableIntSet x = factory.make(new int[] {7, 4, 2, 4, 2, 2}); MutableIntSet y = factory.make(new int[] {7, 7, 7, 2, 7, 1}); MutableIntSet z = factory.parse("{ 9 }"); System.err.println(w); // { } System.err.println(x); // { 2 4 7 } System.err.println(y); // { 1 2 7 } System.err.println(z); // { 9 } MutableIntSet temp = factory.makeCopy(x); temp.intersectWith(y); System.err.println(temp); // { 2 7 } temp.copySet(x); temp.addAll(y); System.err.println(temp); // { 1 2 4 7 } temp.copySet(x); System.err.println(IntSetUtil.diff(x, y, factory)); // { 4 } System.err.println(IntSetUtil.diff(v, z, factory)); // { 17 } System.err.println(IntSetUtil.diff(z, v, factory)); // { } // Assert.assertTrue(x.union(z).intersection(y.union(z)).equals(x.intersection(y).union(z))); MutableIntSet temp1 = factory.makeCopy(x); MutableIntSet temp2 = factory.makeCopy(x); MutableIntSet tempY = factory.makeCopy(y); temp1.addAll(z); tempY.addAll(z); temp1.intersectWith(tempY); temp2.intersectWith(y); temp2.addAll(z); Assert.assertTrue(temp1.sameValue(temp2)); // Assert.assertTrue(x.union(z).diff(z).equals(x)); Assert.assertTrue(w.isEmpty()); Assert.assertTrue(IntSetUtil.diff(x, x, factory).isEmpty()); Assert.assertTrue(IntSetUtil.diff(z, v, factory).isEmpty()); Assert.assertTrue(IntSetUtil.diff(v, z, factory).sameValue(SparseIntSet.singleton(17))); Assert.assertTrue(IntSetUtil.diff(z, v, factory).isEmpty()); Assert.assertTrue(z.isSubset(v)); temp = factory.make(); temp.add(4); System.err.println(temp); // { 4 } temp.add(7); System.err.println(temp); // { 4 7 } temp.add(2); System.err.println(temp); // { 2 4 7 } System.err.println(x); // { 2 4 7 } Assert.assertTrue(temp.sameValue(x)); MutableIntSet a = factory.parse( "{1,3,5,7,9,11,13,15,17,19,21,23,25,27,29,31,33,35,37,39,41,43,45,47,49,51,53,55,57,59}"); System.err.println(a); // { 1 3 5 7 9 11 13 15 17 19 21 23 25 27 29 31 33 // 35 // 37 39 41 43 45 47 49 51 53 55 57 59 } Assert.assertTrue(a.sameValue(a)); IntSet i = a.intersection(temp); Assert.assertTrue(i.sameValue(SparseIntSet.singleton(7))); a.add(100); Assert.assertTrue(a.sameValue(a)); MutableIntSet b = factory.parse( "{1,3,5,7,9,11,13,15,17,19,21,23,25,27,29,31,33,35,37,39,41,43,45,47,49,51,53,55,57,59,100}"); Assert.assertTrue(a.sameValue(b)); Assert.assertTrue(a.isSubset(b)); IntSet f = IntSetUtil.diff(b, factory.parse("{7,8,9}"), factory); System.err.println(f); Assert.assertFalse(f.contains(7)); Assert.assertFalse(f.contains(8)); Assert.assertFalse(f.contains(9)); Assert.assertFalse(f.sameValue(b)); Assert.assertTrue(f.isSubset(b)); IntSet tmp = factory.parse( "{2,4,6,8,10,12,14,16,18,20,22,24,26,28,30,32,34,36,38,40,42,44,46,48,50,51,53,55,57,59,61,63}"); f = IntSetUtil.diff(b, tmp, factory); System.err.println(f); Assert.assertFalse(f.sameValue(b)); Assert.assertTrue(f.isSubset(b)); Assert.assertFalse(f.contains(51)); Assert.assertFalse(f.contains(53)); Assert.assertFalse(f.contains(55)); Assert.assertFalse(f.contains(57)); Assert.assertFalse(f.contains(59)); Assert.assertTrue(f.contains(100)); tmp = factory.parse( "{2,4,6,8,10,12,14,16,18,20,22,24,26,28,30,32,34,36,38,40,42,44,46,48,50,51,53,55,57,59,61,63,100}"); f = IntSetUtil.diff(b, tmp, factory); System.err.println(f); Assert.assertFalse(f.sameValue(b)); Assert.assertTrue(f.isSubset(b)); Assert.assertFalse(f.contains(51)); Assert.assertFalse(f.contains(53)); Assert.assertFalse(f.contains(55)); Assert.assertFalse(f.contains(57)); Assert.assertFalse(f.contains(59)); Assert.assertFalse(f.contains(100)); b = factory.makeCopy(a); Assert.assertTrue(a.sameValue(b)); b.remove(1); b.add(0); Assert.assertFalse(a.sameValue(b)); a = factory.parse("{1}"); Assert.assertFalse(a.isSubset(b)); b.remove(0); Assert.assertFalse(a.isSubset(b)); a.remove(1); Assert.assertTrue(a.isEmpty()); IntSet ignored = a.intersection(temp); Assert.assertTrue(a.isEmpty()); temp2 = factory.make(); Assert.assertTrue(temp2.sameValue(a)); a = factory.parse( "{2,4,6,8,10,12,14,16,18,20,22,24,26,28,30,32,34,36,38,40,42,44,46,48,50,51,53,55,57,59,61,63}"); b = factory.parse( "{2,4,6,8,10,12,14,16,18,20,22,24,26,28,30,32,34,36,38,40,42,44,46,48,50,52,54,56,58,60,62}"); MutableIntSet c = factory.parse("{2,4,6,8,10,12,14,16,18,20,22,24,26,28,30,32,34,36,38,40,42,44,46,48,50}"); MutableIntSet d = factory.parse("{2,4,6,8,10,12,14,16,18,20,22,24,26,28,30,32,34,36,38,40,42,44,46,48,50}"); MutableIntSet e = factory.parse("{2,4,6,8,10,12,14,16,18,20,22,24,26,28,30,32,34}"); Assert.assertTrue(e.isSubset(d)); e.addAll(d); Assert.assertTrue(e.isSubset(d)); e.remove(12); Assert.assertTrue(e.isSubset(d)); e.add(105); Assert.assertFalse(e.isSubset(d)); Assert.assertFalse(b.isSubset(a)); b.add(53); Assert.assertFalse(b.isSubset(a)); a.add(52); a.remove(52); Assert.assertFalse(b.isSubset(a)); c.add(55); Assert.assertFalse(c.isSubset(b)); d.add(53); Assert.assertTrue(d.isSubset(b)); d = factory.make(); d.copySet(c); Assert.assertFalse(d.isSubset(b)); a = factory.parse("{2,4,6,8,10,12,14,16,18,20,22,24,26,28,30,32,34,36,38,40,42,44,46,48,50}"); b = factory.parse("{2,4,6,8,10,12,14,16,18,20,22,24,26,28,30,32,34,36,38,40,42,44,46,48}"); Assert.assertFalse(a.sameValue(b)); b.add(50); Assert.assertTrue(a.sameValue(b)); a.add(11); b.add(11); Assert.assertTrue(a.sameValue(b)); a = factory.parse("{2,4,6,8,10,12,14,16,18,20,50}"); b = factory.parse("{24,26,28,30,32,34,36,38,40,42,44,46,48}"); c = factory.parse("{2,4,6,8,10,12,14,16,18,20,22,24,26,28,30,32,34,36,38,40,42,44,46,48,50}"); a.addAll(b); a.add(22); Assert.assertTrue(a.sameValue(c)); a = factory.parse("{2,4,6,8,10,12,14,16,18,20,50}"); b = factory.parse("{24,26,28,30,32,34,36,38,40,42,44,46,48}"); c = factory.parse("{2,4,6,8,10,12,14,16,18,20,22,24,26,28,30,32,34,36,38,40,42,44,46,48,50}"); b.addAll(factory.parse("{22}")); a.addAll(b); Assert.assertTrue(a.sameValue(c)); a = factory.parse("{2,4,6,8,10,12,14,16,18,20}"); b = factory.parse("{22,24,26,28,30,32,34,36,38,40,42,44,46,48}"); c = factory.parse("{2,4,6,8,10,12,14,16,18,20,22,24,26,28,30,32,34,36,38,40,42,44,46,48,50}"); c.remove(22); a.addAll(b); Assert.assertFalse(a.sameValue(c)); a = factory.parse( "{1,3,5,7,9,11,13,15,17,19,21,23,25,27,29,31,33,35,37,39,41,43,45,47,49,51,53,55,57,59}"); System.err.println(a); // { 1 3 5 7 9 11 13 15 17 19 21 23 25 27 29 31 33 // 35 // 37 39 41 43 45 47 49 51 53 55 57 59 } Assert.assertTrue(a.sameValue(a)); i = a.intersection(temp); Assert.assertTrue(i.sameValue(SparseIntSet.singleton(7))); a.add(100); Assert.assertTrue(a.sameValue(a)); b = factory.parse( "{1,3,5,7,9,11,13,15,17,19,21,23,25,27,29,31,33,35,37,39,41,43,45,47,49,51,53,55,57,59,100}"); Assert.assertTrue(a.sameValue(b)); Assert.assertTrue(a.isSubset(b)); b = factory.makeCopy(a); Assert.assertTrue(a.sameValue(b)); b.remove(1); b.add(0); Assert.assertFalse(a.sameValue(b)); a.clear(); Assert.assertTrue(a.isEmpty()); a = factory.parse("{1}"); Assert.assertFalse(a.isSubset(b)); b.remove(0); Assert.assertFalse(a.isSubset(b)); a.remove(1); Assert.assertTrue(a.isEmpty()); ignored = a.intersection(temp); Assert.assertTrue(a.isEmpty()); temp2 = factory.make(); Assert.assertTrue(temp2.sameValue(a)); for (int idx = 500; idx < 550; ) { for (int xx = 0; xx < 50; xx++, idx++) { temp2.add(idx); } System.err.println(temp2); } for (int idx = 3000; idx < 3200; ) { for (int xx = 0; xx < 50; xx++, idx++) { temp2.add(idx); } System.err.println(temp2); } temp2.clear(); Assert.assertTrue(temp2.isEmpty()); temp2 = factory.make(); Assert.assertTrue(temp2.sameValue(a)); for (int idx = 500; idx < 550; ) { for (int xx = 0; xx < 50; xx++, idx++) { temp2.add(idx); } System.err.println(temp2); } for (int idx = 0; idx < 25; idx++) { temp2.add(idx); System.err.println(temp2); } temp2.clear(); Assert.assertTrue(temp2.isEmpty()); } /** Test the MutableSharedBitVectorIntSet implementation */ @Test public void testMutableSharedBitVectorIntSet() { doMutableIntSet(new MutableSharedBitVectorIntSetFactory()); } /** Test the MutableSparseIntSet implementation */ @Test public void testMutableSparseIntSet() { doMutableIntSet(new MutableSparseIntSetFactory()); } /** Test the BimodalMutableSparseIntSet implementation */ @Test public void testBimodalMutableSparseIntSet() { doMutableIntSet(new BimodalMutableIntSetFactory()); } /** Test the BitVectorIntSet implementation */ @Test public void testBitVectorIntSet() { doMutableIntSet(new BitVectorIntSetFactory()); } /** Test the SemiSparseMutableIntSet implementation */ @Test public void testSemiSparseMutableIntSet() { doMutableIntSet(new SemiSparseMutableIntSetFactory()); } /** Test the MutableSparseIntSet implementation */ private static void doMutableLongSet(MutableLongSetFactory factory) { MutableLongSet v = factory.parse("{9,17}"); MutableLongSet w = factory.make(new long[] {}); MutableLongSet x = factory.make(new long[] {7, 4, 2, 4, 2, 2}); MutableLongSet y = factory.make(new long[] {7, 7, 7, 2, 7, 1}); MutableLongSet z = factory.parse("{ 9 }"); System.err.println(w); // { } System.err.println(x); // { 2 4 7 } System.err.println(y); // { 1 2 7 } System.err.println(z); // { 9 } MutableLongSet temp = factory.makeCopy(x); temp.intersectWith(y); System.err.println(temp); // { 2 7 } temp.copySet(x); temp.addAll(y); System.err.println(temp); // { 1 2 4 7 } temp.copySet(x); System.err.println(LongSetUtil.diff(x, y, factory)); // { 4 } System.err.println(LongSetUtil.diff(v, z, factory)); // { 17 } System.err.println(LongSetUtil.diff(z, v, factory)); // { } // Assert.assertTrue(x.union(z).intersection(y.union(z)).equals(x.intersection(y).union(z))); MutableLongSet temp1 = factory.makeCopy(x); MutableLongSet temp2 = factory.makeCopy(x); MutableLongSet tempY = factory.makeCopy(y); temp1.addAll(z); tempY.addAll(z); temp1.intersectWith(tempY); temp2.intersectWith(y); temp2.addAll(z); Assert.assertTrue(temp1.sameValue(temp2)); // Assert.assertTrue(x.union(z).diff(z).equals(x)); Assert.assertTrue(w.isEmpty()); Assert.assertTrue(LongSetUtil.diff(x, x, factory).isEmpty()); Assert.assertTrue(LongSetUtil.diff(z, v, factory).isEmpty()); Assert.assertTrue(LongSetUtil.diff(v, z, factory).sameValue(SparseLongSet.singleton(17))); Assert.assertTrue(LongSetUtil.diff(z, v, factory).isEmpty()); Assert.assertTrue(z.isSubset(v)); temp = factory.make(); temp.add(4); System.err.println(temp); // { 4 } temp.add(7); System.err.println(temp); // { 4 7 } temp.add(2); System.err.println(temp); // { 2 4 7 } System.err.println(x); // { 2 4 7 } Assert.assertTrue(temp.sameValue(x)); MutableLongSet a = factory.parse( "{1,3,5,7,9,11,13,15,17,19,21,23,25,27,29,31,33,35,37,39,41,43,45,47,49,51,53,55,57,59}"); System.err.println(a); // { 1 3 5 7 9 11 13 15 17 19 21 23 25 27 29 31 33 // 35 // 37 39 41 43 45 47 49 51 53 55 57 59 } Assert.assertTrue(a.sameValue(a)); LongSet i = a.intersection(temp); Assert.assertTrue(i.sameValue(SparseLongSet.singleton(7))); a.add(100); Assert.assertTrue(a.sameValue(a)); MutableLongSet b = factory.parse( "{1,3,5,7,9,11,13,15,17,19,21,23,25,27,29,31,33,35,37,39,41,43,45,47,49,51,53,55,57,59,100}"); Assert.assertTrue(a.sameValue(b)); Assert.assertTrue(a.isSubset(b)); LongSet f = LongSetUtil.diff(b, factory.parse("{7,8,9}"), factory); System.err.println(f); Assert.assertFalse(f.contains(7)); Assert.assertFalse(f.contains(8)); Assert.assertFalse(f.contains(9)); Assert.assertFalse(f.sameValue(b)); Assert.assertTrue(f.isSubset(b)); LongSet tmp = factory.parse( "{2,4,6,8,10,12,14,16,18,20,22,24,26,28,30,32,34,36,38,40,42,44,46,48,50,51,53,55,57,59,61,63}"); f = LongSetUtil.diff(b, tmp, factory); System.err.println(f); Assert.assertFalse(f.sameValue(b)); Assert.assertTrue(f.isSubset(b)); Assert.assertFalse(f.contains(51)); Assert.assertFalse(f.contains(53)); Assert.assertFalse(f.contains(55)); Assert.assertFalse(f.contains(57)); Assert.assertFalse(f.contains(59)); Assert.assertTrue(f.contains(100)); tmp = factory.parse( "{2,4,6,8,10,12,14,16,18,20,22,24,26,28,30,32,34,36,38,40,42,44,46,48,50,51,53,55,57,59,61,63,100}"); f = LongSetUtil.diff(b, tmp, factory); System.err.println(f); Assert.assertFalse(f.sameValue(b)); Assert.assertTrue(f.isSubset(b)); Assert.assertFalse(f.contains(51)); Assert.assertFalse(f.contains(53)); Assert.assertFalse(f.contains(55)); Assert.assertFalse(f.contains(57)); Assert.assertFalse(f.contains(59)); Assert.assertFalse(f.contains(100)); b = factory.makeCopy(a); Assert.assertTrue(a.sameValue(b)); b.remove(1); b.add(0); Assert.assertFalse(a.sameValue(b)); a = factory.parse("{1}"); Assert.assertFalse(a.isSubset(b)); b.remove(0); Assert.assertFalse(a.isSubset(b)); a.remove(1); Assert.assertTrue(a.isEmpty()); LongSet ignored = a.intersection(temp); Assert.assertTrue(a.isEmpty()); temp2 = factory.make(); Assert.assertTrue(temp2.sameValue(a)); a = factory.parse( "{2,4,6,8,10,12,14,16,18,20,22,24,26,28,30,32,34,36,38,40,42,44,46,48,50,51,53,55,57,59,61,63}"); b = factory.parse( "{2,4,6,8,10,12,14,16,18,20,22,24,26,28,30,32,34,36,38,40,42,44,46,48,50,52,54,56,58,60,62}"); MutableLongSet c = factory.parse("{2,4,6,8,10,12,14,16,18,20,22,24,26,28,30,32,34,36,38,40,42,44,46,48,50}"); MutableLongSet d = factory.parse("{2,4,6,8,10,12,14,16,18,20,22,24,26,28,30,32,34,36,38,40,42,44,46,48,50}"); MutableLongSet e = factory.parse("{2,4,6,8,10,12,14,16,18,20,22,24,26,28,30,32,34}"); Assert.assertTrue(e.isSubset(d)); e.addAll(d); Assert.assertTrue(e.isSubset(d)); e.remove(12); Assert.assertTrue(e.isSubset(d)); e.add(105); Assert.assertFalse(e.isSubset(d)); Assert.assertFalse(b.isSubset(a)); b.add(53); Assert.assertFalse(b.isSubset(a)); a.add(52); a.remove(52); Assert.assertFalse(b.isSubset(a)); c.add(55); Assert.assertFalse(c.isSubset(b)); d.add(53); Assert.assertTrue(d.isSubset(b)); d = factory.make(); d.copySet(c); Assert.assertFalse(d.isSubset(b)); a = factory.parse("{2,4,6,8,10,12,14,16,18,20,22,24,26,28,30,32,34,36,38,40,42,44,46,48,50}"); b = factory.parse("{2,4,6,8,10,12,14,16,18,20,22,24,26,28,30,32,34,36,38,40,42,44,46,48}"); Assert.assertFalse(a.sameValue(b)); b.add(50); Assert.assertTrue(a.sameValue(b)); a.add(11); b.add(11); Assert.assertTrue(a.sameValue(b)); a = factory.parse("{2,4,6,8,10,12,14,16,18,20,50}"); b = factory.parse("{24,26,28,30,32,34,36,38,40,42,44,46,48}"); c = factory.parse("{2,4,6,8,10,12,14,16,18,20,22,24,26,28,30,32,34,36,38,40,42,44,46,48,50}"); a.addAll(b); a.add(22); Assert.assertTrue(a.sameValue(c)); a = factory.parse("{2,4,6,8,10,12,14,16,18,20,50}"); b = factory.parse("{24,26,28,30,32,34,36,38,40,42,44,46,48}"); c = factory.parse("{2,4,6,8,10,12,14,16,18,20,22,24,26,28,30,32,34,36,38,40,42,44,46,48,50}"); b.addAll(factory.parse("{22}")); a.addAll(b); Assert.assertTrue(a.sameValue(c)); a = factory.parse("{2,4,6,8,10,12,14,16,18,20}"); b = factory.parse("{22,24,26,28,30,32,34,36,38,40,42,44,46,48}"); c = factory.parse("{2,4,6,8,10,12,14,16,18,20,22,24,26,28,30,32,34,36,38,40,42,44,46,48,50}"); c.remove(22); a.addAll(b); Assert.assertFalse(a.sameValue(c)); a = factory.parse( "{1,3,5,7,9,11,13,15,17,19,21,23,25,27,29,31,33,35,37,39,41,43,45,47,49,51,53,55,57,59}"); System.err.println(a); // { 1 3 5 7 9 11 13 15 17 19 21 23 25 27 29 31 33 // 35 // 37 39 41 43 45 47 49 51 53 55 57 59 } Assert.assertTrue(a.sameValue(a)); i = a.intersection(temp); Assert.assertTrue(i.sameValue(SparseLongSet.singleton(7))); a.add(100); Assert.assertTrue(a.sameValue(a)); b = factory.parse( "{1,3,5,7,9,11,13,15,17,19,21,23,25,27,29,31,33,35,37,39,41,43,45,47,49,51,53,55,57,59,100}"); Assert.assertTrue(a.sameValue(b)); Assert.assertTrue(a.isSubset(b)); b = factory.makeCopy(a); Assert.assertTrue(a.sameValue(b)); b.remove(1); b.add(0); Assert.assertFalse(a.sameValue(b)); a = factory.parse("{1}"); Assert.assertFalse(a.isSubset(b)); b.remove(0); Assert.assertFalse(a.isSubset(b)); a.remove(1); Assert.assertTrue(a.isEmpty()); ignored = a.intersection(temp); Assert.assertTrue(a.isEmpty()); temp2 = factory.make(); Assert.assertTrue(temp2.sameValue(a)); for (int idx = 500; idx < 550; ) { for (int xx = 0; xx < 50; xx++, idx++) { temp2.add(idx); } System.err.println(temp2); } for (int idx = 3000; idx < 3200; ) { for (int xx = 0; xx < 50; xx++, idx++) { temp2.add(idx); } System.err.println(temp2); } temp2 = factory.make(); Assert.assertTrue(temp2.sameValue(a)); for (int idx = 500; idx < 550; ) { for (int xx = 0; xx < 50; xx++, idx++) { temp2.add(idx); } System.err.println(temp2); } for (int idx = 0; idx < 25; idx++) { temp2.add(idx); System.err.println(temp2); } } /** Test the MutableSparseLongSet implementation */ @Test public void testMutableSparseLongSet() { doMutableLongSet(new MutableSparseLongSetFactory()); } @Test public void testSmallMap() { SmallMap<Integer, Integer> M = new SmallMap<>(); Integer I1 = Integer.valueOf(1); Integer I2 = Integer.valueOf(2); Integer I3 = Integer.valueOf(3); M.put(I1, I1); M.put(I2, I2); M.put(I3, I3); Integer I = M.get(Integer.valueOf(2)); Assert.assertNotNull(I); Assert.assertEquals(I, I2); I = M.get(Integer.valueOf(4)); Assert.assertNull(I); I = M.put(Integer.valueOf(2), Integer.valueOf(3)); Assert.assertEquals(I, I2); I = M.get(I2); Assert.assertEquals(I, I3); } @Test public void testBimodalMap() { Map<Integer, Integer> M = new BimodalMap<>(3); Integer I1 = Integer.valueOf(1); Integer I2 = Integer.valueOf(2); Integer I3 = Integer.valueOf(3); Integer I4 = Integer.valueOf(4); Integer I5 = Integer.valueOf(5); Integer I6 = Integer.valueOf(6); M.put(I1, I1); M.put(I2, I2); M.put(I3, I3); Integer I = M.get(Integer.valueOf(2)); Assert.assertNotNull(I); Assert.assertEquals(I, I2); I = M.get(Integer.valueOf(4)); Assert.assertNull(I); I = M.put(Integer.valueOf(2), Integer.valueOf(3)); Assert.assertEquals(I, I2); I = M.get(I2); Assert.assertEquals(I, I3); M.put(I4, I4); M.put(I5, I5); M.put(I6, I6); I = M.get(Integer.valueOf(4)); Assert.assertNotNull(I); Assert.assertEquals(I, I4); I = M.get(Integer.valueOf(7)); Assert.assertNull(I); I = M.put(Integer.valueOf(2), Integer.valueOf(6)); Assert.assertEquals(I, I3); I = M.get(I2); Assert.assertEquals(I, I6); } @Test public void testBFSPathFinder() { NumberedGraph<Integer> G = makeBFSTestGraph(); // path from 0 to 8 BFSPathFinder<Integer> pf = new BFSPathFinder<>(G, G.getNode(0), G.getNode(8)); List<Integer> p = pf.find(); // path should be 8, 6, 4, 2, 0 System.err.println("Path is " + p); for (int i = 0; i < p.size(); i++) { Assert.assertEquals((int) p.get(i), new int[] {8, 6, 4, 2, 0}[i]); } } @Test public void testBoundedBFS() { NumberedGraph<Integer> G = makeBFSTestGraph(); BoundedBFSIterator<Integer> bfs = new BoundedBFSIterator<>(G, G.getNode(0), 0); Collection<Integer> c = Iterator2Collection.toSet(bfs); Assert.assertEquals(1, c.size()); bfs = new BoundedBFSIterator<>(G, G.getNode(0), 1); c = Iterator2Collection.toSet(bfs); Assert.assertEquals(3, c.size()); bfs = new BoundedBFSIterator<>(G, G.getNode(0), 2); c = Iterator2Collection.toSet(bfs); Assert.assertEquals(5, c.size()); bfs = new BoundedBFSIterator<>(G, G.getNode(0), 3); c = Iterator2Collection.toSet(bfs); Assert.assertEquals(7, c.size()); bfs = new BoundedBFSIterator<>(G, G.getNode(0), 4); c = Iterator2Collection.toSet(bfs); Assert.assertEquals(9, c.size()); bfs = new BoundedBFSIterator<>(G, G.getNode(0), 5); c = Iterator2Collection.toSet(bfs); Assert.assertEquals(10, c.size()); bfs = new BoundedBFSIterator<>(G, G.getNode(0), 500); c = Iterator2Collection.toSet(bfs); Assert.assertEquals(10, c.size()); } private static NumberedGraph<Integer> makeBFSTestGraph() { // test graph NumberedGraph<Integer> G = SlowSparseNumberedGraph.make(); // add 10 nodes Integer[] nodes = new Integer[10]; for (int i = 0; i < nodes.length; i++) G.addNode(nodes[i] = Integer.valueOf(i)); // edges to i-1, i+1, i+2 for (int i = 0; i < nodes.length; i++) { if (i > 0) { G.addEdge(nodes[i], nodes[i - 1]); } if (i < nodes.length - 1) { G.addEdge(nodes[i], nodes[i + 1]); if (i < nodes.length - 2) { G.addEdge(nodes[i], nodes[i + 2]); } } } return G; } @Test public void testDominatorsA() { // test graph Graph<Object> G = SlowSparseNumberedGraph.make(); // add nodes Object[] nodes = new Object[11]; for (int i = 0; i < nodes.length; i++) G.addNode(nodes[i] = Integer.valueOf(i)); // add edges G.addEdge(nodes[10], nodes[0]); G.addEdge(nodes[10], nodes[1]); G.addEdge(nodes[0], nodes[2]); G.addEdge(nodes[1], nodes[3]); G.addEdge(nodes[2], nodes[5]); G.addEdge(nodes[3], nodes[5]); G.addEdge(nodes[4], nodes[2]); G.addEdge(nodes[5], nodes[8]); G.addEdge(nodes[6], nodes[3]); G.addEdge(nodes[7], nodes[4]); G.addEdge(nodes[8], nodes[7]); G.addEdge(nodes[8], nodes[9]); G.addEdge(nodes[9], nodes[6]); // compute dominators Dominators<Object> D = Dominators.make(G, nodes[10]); // Assert.assertions int i = 0; Object[] desired4 = new Object[] {nodes[4], nodes[7], nodes[8], nodes[5], nodes[10]}; for (Object d4 : Iterator2Iterable.make(D.dominators(nodes[4]))) Assert.assertSame(d4, desired4[i++]); int j = 0; Object[] desired5 = new Object[] {nodes[8]}; for (Object o4 : Iterator2Iterable.make(D.dominatorTree().getSuccNodes(nodes[5]))) { Object d = desired5[j++]; boolean ok = o4.equals(d); if (!ok) { System.err.println("O4: " + o4); System.err.println("desired " + d); Assert.assertEquals(o4, d); } } Assert.assertEquals(5, D.dominatorTree().getSuccNodeCount(nodes[10])); } @Test public void testBinaryIntegerRelation() { byte[] impl = new byte[] { BasicNaturalRelation.SIMPLE, BasicNaturalRelation.TWO_LEVEL, BasicNaturalRelation.SIMPLE }; IBinaryNaturalRelation R = new BasicNaturalRelation(impl, BasicNaturalRelation.TWO_LEVEL); R.add(3, 5); R.add(3, 7); R.add(3, 9); R.add(3, 11); R.add(5, 1); int count = 0; for (IntPair intPair : R) { System.err.println(intPair); count++; } Assert.assertEquals(5, count); IntSet x = R.getRelated(3); Assert.assertEquals(4, x.size()); x = R.getRelated(5); Assert.assertEquals(1, x.size()); R.remove(5, 1); x = R.getRelated(5); Assert.assertNull(x); R.add(2, 1); R.add(2, 2); R.remove(2, 1); x = R.getRelated(2); Assert.assertEquals(1, x.size()); R.removeAll(3); x = R.getRelated(3); Assert.assertNull(x); x = R.getRelated(0); Assert.assertNull(x); for (int i = 0; i < 100; i++) { R.add(1, i); } Assert.assertEquals(100, R.getRelated(1).size()); R.remove(1, 1); Assert.assertEquals(99, R.getRelated(1).size()); } @Test public void testUnionFind() { int SIZE = 10000; IntegerUnionFind uf = new IntegerUnionFind(SIZE); int count = countEquivalenceClasses(uf); Assert.assertEquals("Got count " + count, count, SIZE); uf.union(3, 7); Assert.assertEquals(uf.find(3), uf.find(7)); Assert.assertTrue("Got uf.find(3)=" + uf.find(3), uf.find(3) == 3 || uf.find(3) == 7); uf.union(7, SIZE - 1); Assert.assertEquals(uf.find(3), uf.find(SIZE - 1)); Assert.assertTrue( "Got uf.find(3)=" + uf.find(3), uf.find(3) == 3 || uf.find(3) == 7 || uf.find(3) == SIZE - 1); for (int i = 0; i < SIZE - 1; i++) { uf.union(i, i + 1); } count = countEquivalenceClasses(uf); Assert.assertEquals("Got count " + count, 1, count); uf = new IntegerUnionFind(SIZE); for (int i = 0; i < SIZE; i++) { if ((i % 2) == 0) { uf.union(i, 0); } else { uf.union(i, 1); } } count = countEquivalenceClasses(uf); Assert.assertEquals("Got count " + count, 2, count); } private static int countEquivalenceClasses(IntegerUnionFind uf) { HashSet<Integer> s = HashSetFactory.make(); for (int i = 0; i < uf.size(); i++) { s.add(Integer.valueOf(uf.find(i))); } return s.size(); } @Test public void testBitVector() { testSingleBitVector(new BitVector()); } @Test public void testOffsetBitVector0_10() { testSingleBitVector(new OffsetBitVector(0, 10)); } @Test public void testOffsetBitVector10_10() { testSingleBitVector(new OffsetBitVector(10, 10)); } @Test public void testOffsetBitVector50_10() { testSingleBitVector(new OffsetBitVector(50, 10)); } @Test public void testOffsetBitVector50_50() { testSingleBitVector(new OffsetBitVector(50, 50)); } @Test public void testOffsetBitVector100_10() { testSingleBitVector(new OffsetBitVector(100, 10)); } private static void testSingleBitVector(BitVectorBase<?> bv) { // does the following not automatically scale the bitvector to // a reasonable size? bv.set(55); Assert.assertEquals("bv.max() is " + bv.max(), 55, bv.max()); Assert.assertTrue(bv.get(55)); bv.set(59); Assert.assertEquals(59, bv.max()); Assert.assertTrue(bv.get(55)); Assert.assertTrue(bv.get(59)); { boolean[] gets = new boolean[] {false, true, true}; int[] bits = new int[] {0, 55, 59}; for (int i = 0, j = 0; i != -1; i = bv.nextSetBit(i + 1), j++) { Assert.assertEquals(i, bits[j]); Assert.assertEquals(bv.get(i), gets[j]); } } bv.set(77); Assert.assertEquals("bv.max() is " + bv.max(), 77, bv.max()); { boolean[] gets = new boolean[] {false, true, true, true}; int[] bits = new int[] {0, 55, 59, 77}; for (int i = 0, j = 0; i != -1; i = bv.nextSetBit(i + 1), j++) { Assert.assertEquals(i, bits[j]); Assert.assertEquals(bv.get(i), gets[j]); } } bv.set(3); Assert.assertEquals("bv.max() is " + bv.max(), 77, bv.max()); { boolean[] gets = new boolean[] {false, true, true, true, true}; int[] bits = new int[] {0, 3, 55, 59, 77}; for (int i = 0, j = 0; i != -1; i = bv.nextSetBit(i + 1), j++) { Assert.assertEquals(i, bits[j]); Assert.assertEquals(bv.get(i), gets[j]); } } System.err.println(bv); } @Test public void testBitVectors() { testBitVectors(new BitVector(), new BitVector()); } @Test public void testOffsetBitVectors150_10() { testBitVectors(new OffsetBitVector(150, 10), new OffsetBitVector(150, 10)); } @Test public void testOffsetBitVectors100_200_10() { testBitVectors(new OffsetBitVector(100, 10), new OffsetBitVector(200, 10)); } @Test public void testOffsetBitVectors100_25_10() { testBitVectors(new OffsetBitVector(100, 10), new OffsetBitVector(25, 10)); } @Test public void testOffsetBitVectors35_25_20_10() { testBitVectors(new OffsetBitVector(35, 20), new OffsetBitVector(25, 10)); } private static <T extends BitVectorBase<T>> void testBitVectors(T v1, T v2) { v1.set(100); v1.set(101); v1.set(102); Assert.assertEquals("v1.max() is " + v1.max(), 102, v1.max()); v2.set(200); v2.set(201); v2.set(202); Assert.assertEquals("v2.max() is " + v2.max(), 202, v2.max()); Assert.assertTrue(v1.intersectionEmpty(v2)); Assert.assertTrue(v2.intersectionEmpty(v1)); v1.or(v2); System.err.println("v1 = " + v1 + ", v2 = " + v2); Assert.assertFalse("v1 = " + v1 + ", v2 = " + v2, v1.intersectionEmpty(v2)); Assert.assertFalse("v1 = " + v1 + ", v2 = " + v2, v2.intersectionEmpty(v1)); Assert.assertEquals("v1.max() is " + v1.max(), 202, v1.max()); { boolean[] gets = new boolean[] {false, true, true, true, true, true, true}; int[] bits = new int[] {0, 100, 101, 102, 200, 201, 202}; for (int i = 0, j = 0; i != -1; i = v1.nextSetBit(i + 1), j++) { Assert.assertEquals(i, bits[j]); Assert.assertEquals(v1.get(i), gets[j]); } } v1.clearAll(); v2.clearAll(); v1.set(100); v1.set(101); v1.set(102); v1.set(103); v1.set(104); v1.set(105); Assert.assertEquals("v1.max() is " + v1.max(), 105, v1.max()); v2.set(103); v2.set(104); v2.set(200); v2.set(201); Assert.assertEquals("v2.max() is " + v2.max(), 201, v2.max()); v1.and(v2); Assert.assertEquals("v1.max() is " + v1.max(), 104, v1.max()); { boolean[] gets = new boolean[] {false, true, true}; int[] bits = new int[] {0, 103, 104}; for (int i = 0, j = 0; i != -1; i = v1.nextSetBit(i + 1), j++) { Assert.assertEquals(i, bits[j]); Assert.assertEquals(v1.get(i), gets[j]); } } v1.set(100); v1.set(101); v1.set(102); v1.set(105); Assert.assertEquals("v1.max() is " + v1.max(), 105, v1.max()); { boolean[] gets = new boolean[] {false, true, true, true, true, true, true}; int[] bits = new int[] {0, 100, 101, 102, 103, 104, 105}; for (int i = 0, j = 0; i != -1; i = v1.nextSetBit(i + 1), j++) { Assert.assertEquals(i, bits[j]); Assert.assertEquals(v1.get(i), gets[j]); } } v2.clear(103); v2.clear(104); v1.andNot(v2); { boolean[] gets = new boolean[] {false, true, true, true, true, true, true}; int[] bits = new int[] {0, 100, 101, 102, 103, 104, 105}; for (int i = 0, j = 0; i != -1; i = v1.nextSetBit(i + 1), j++) { Assert.assertEquals(i, bits[j]); Assert.assertEquals(v1.get(i), gets[j]); } } v2.set(101); v2.set(102); System.err.println("v1 = " + v1 + ", v2 = " + v2); v1.andNot(v2); { boolean[] gets = new boolean[] {false, true, true, true, true}; int[] bits = new int[] {0, 100, 103, 104, 105}; for (int i = 0, j = 0; i != -1; i = v1.nextSetBit(i + 1), j++) { Assert.assertEquals(i, bits[j]); Assert.assertEquals(v1.get(i), gets[j]); } } v1.clearAll(); v2.clearAll(); v1.set(35); v1.set(101); v1.set(102); v1.set(103); v1.set(104); v1.set(105); v2.set(101); v2.set(102); v2.set(104); v2.set(206); System.err.println("v1 = " + v1 + ", v2 = " + v2); v1.xor(v2); { boolean[] gets = new boolean[] {false, true, true, true, true}; int[] bits = new int[] {0, 35, 103, 105, 206}; for (int i = 0, j = 0; i != -1; i = v1.nextSetBit(i + 1), j++) { Assert.assertEquals(i, bits[j]); Assert.assertEquals(v1.get(i), gets[j]); } } v2.set(35); v2.set(103); v2.set(105); System.err.println("v1 = " + v1 + ", v2 = " + v2); Assert.assertTrue(v1.isSubset(v2)); v2.clearAll(); v2.set(111); v2.or(v1); Assert.assertTrue(v1.isSubset(v2)); v2.and(v1); Assert.assertTrue(v1.sameBits(v2)); v1.clearAll(); } private static OffsetBitVector makeBigTestOffsetVector() { OffsetBitVector v1 = new OffsetBitVector(50000096, 1024); v1.set(50000101); v1.set(50000103); v1.set(50000112); v1.set(50000114); v1.set(50000116); v1.set(50000126); v1.set(50000128); v1.set(50000129); v1.set(50000135); v1.set(50000137); v1.set(50000143); v1.set(50000148); v1.set(50000151); v1.set(50000158); v1.set(50000163); v1.set(50000167); v1.set(50000170); v1.set(50000173); v1.set(50000180); v1.set(50000182); v1.set(50000185); v1.set(50000187); v1.set(50000190); v1.set(50000194); v1.set(50000199); v1.set(50000201); v1.set(50000204); v1.set(50000206); v1.set(50000209); v1.set(50000210); v1.set(50000218); v1.set(50000221); v1.set(50000223); v1.set(50000227); v1.set(50000232); v1.set(50000234); v1.set(50000243); v1.set(50000246); v1.set(50000250); v1.set(50000257); v1.set(50000263); v1.set(50000268); v1.set(50000273); v1.set(50000275); v1.set(50000278); v1.set(50000282); v1.set(50000285); v1.set(50000290); v1.set(50000293); v1.set(50000298); v1.set(50000300); v1.set(50000303); v1.set(50000306); v1.set(50000308); v1.set(50000310); v1.set(50000315); v1.set(50000325); v1.set(50000327); v1.set(50000335); v1.set(50000337); v1.set(50000342); v1.set(50000345); v1.set(50000349); v1.set(50000360); v1.set(50000362); v1.set(50000369); v1.set(50000374); v1.set(50000375); v1.set(50000378); v1.set(50000380); v1.set(50000383); v1.set(50000384); v1.set(50000388); v1.set(50000391); v1.set(50000400); v1.set(50000405); v1.set(50000409); v1.set(50000414); v1.set(50000417); v1.set(50000421); v1.set(50000426); v1.set(50000431); v1.set(50000435); v1.set(50000437); v1.set(50000439); v1.set(50000442); v1.set(50000446); v1.set(50000450); v1.set(50000455); v1.set(50000459); v1.set(50000460); v1.set(50000463); v1.set(50000470); v1.set(50000471); v1.set(50000480); v1.set(50000497); v1.set(50000498); v1.set(50000500); v1.set(50000505); v1.set(50000508); v1.set(50000511); v1.set(50000513); v1.set(50000520); v1.set(50000526); v1.set(50000529); v1.set(50000536); v1.set(50000539); v1.set(50000551); v1.set(50000555); v1.set(50000559); v1.set(50000563); v1.set(50000564); v1.set(50000566); v1.set(50000568); v1.set(50000570); v1.set(50000576); v1.set(50000587); v1.set(50000590); v1.set(50000594); v1.set(50000601); v1.set(50000605); v1.set(50000608); v1.set(50000610); v1.set(50000619); v1.set(50000628); v1.set(50000630); v1.set(50000634); v1.set(50000644); v1.set(50000647); v1.set(50000654); v1.set(50000658); v1.set(50000661); v1.set(50000663); v1.set(50000669); v1.set(50000671); v1.set(50000673); v1.set(50000676); v1.set(50000677); v1.set(50000680); v1.set(50000689); v1.set(50000692); v1.set(50000695); v1.set(50000705); v1.set(50000707); v1.set(50000708); v1.set(50000714); v1.set(50000716); v1.set(50000721); v1.set(50000727); v1.set(50000732); v1.set(50000736); v1.set(50000739); v1.set(50000741); v1.set(50000750); v1.set(50000753); v1.set(50000755); v1.set(50000765); v1.set(50000769); v1.set(50000773); v1.set(50000779); v1.set(50000782); v1.set(50000784); v1.set(50000787); v1.set(50000791); v1.set(50000792); v1.set(50000793); v1.set(50000795); v1.set(50000801); v1.set(50000806); v1.set(50000809); return v1; } @Test public void testSpecificBugsInOffsetBitVectors() { OffsetBitVector v1 = makeBigTestOffsetVector(); System.err.println(v1); OffsetBitVector v2 = new OffsetBitVector(50000128, 512); v2.set(50000137); v2.set(50000204); v2.set(50000278); v2.set(50000315); v2.set(50000362); v2.set(50000450); v2.set(50000455); v2.set(50000471); System.err.println(v2); v1.andNot(v2); System.err.println(v1); Assert.assertTrue(v1.intersectionEmpty(v2)); v1 = makeBigTestOffsetVector(); v1.and(v2); System.err.println(v1); Assert.assertTrue(v1.sameBits(v2)); Assert.assertTrue(v1.isSubset(v2)); Assert.assertTrue(v2.isSubset(v1)); } @Test public void testSpecificBugsInSemiSparseMutableIntSets() { SemiSparseMutableIntSet v1 = new SemiSparseMutableIntSet(); v1.add(54); v1.add(58); v1.add(59); v1.add(64); v1.add(67); v1.add(73); v1.add(83); v1.add(105); v1.add(110); v1.add(126); v1.add(136); v1.add(143); v1.add(150); v1.add(155); v1.add(156); v1.add(162); v1.add(168); v1.add(183); v1.add(191); v1.add(265); v1.add(294); v1.add(324); v1.add(344); v1.add(397); } }
41,088
28.731548
113
java
WALA
WALA-master/core/src/test/java/com/ibm/wala/core/tests/basic/WelshPowellTest.java
/* * Copyright (c) 2013 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package com.ibm.wala.core.tests.basic; import com.ibm.wala.util.collections.HashMapFactory; import com.ibm.wala.util.collections.Iterator2Iterable; import com.ibm.wala.util.graph.Graph; import com.ibm.wala.util.graph.NumberedGraph; import com.ibm.wala.util.graph.impl.DelegatingNumberedGraph; import com.ibm.wala.util.graph.impl.NodeWithNumberedEdges; import com.ibm.wala.util.graph.traverse.WelshPowell; import com.ibm.wala.util.graph.traverse.WelshPowell.ColoredVertices; import java.util.Map; import org.junit.Assert; import org.junit.Test; public class WelshPowellTest { public static <T> void assertColoring(Graph<T> G, Map<T, Integer> colors, boolean fullColor) { for (T n : G) { for (T succ : Iterator2Iterable.make(G.getSuccNodes(n))) { if (!fullColor && (!colors.containsKey(n) || !colors.containsKey(succ))) { continue; } Assert.assertTrue( n + " and succ: " + succ + " have same color: " + colors.get(n), colors.get(n).intValue() != colors.get(succ).intValue()); } for (T pred : Iterator2Iterable.make(G.getPredNodes(n))) { if (!fullColor && (!colors.containsKey(n) || !colors.containsKey(pred))) { continue; } Assert.assertTrue( n + " and pred: " + pred + " have same color:" + colors.get(n), colors.get(n).intValue() != colors.get(pred).intValue()); } } } private static class TypedNode<T> extends NodeWithNumberedEdges { private final T data; private TypedNode(T data) { this.data = data; } @Override public String toString() { return data.toString(); } } private static <T> NumberedGraph<TypedNode<T>> buildGraph(T[][] data) { DelegatingNumberedGraph<TypedNode<T>> G = new DelegatingNumberedGraph<>(); Map<T, TypedNode<T>> nodes = HashMapFactory.make(); for (T[] element : data) { TypedNode<T> n = new TypedNode<>(element[0]); nodes.put(element[0], n); G.addNode(n); } for (T[] element : data) { for (int j = 1; j < element.length; j++) { G.addEdge(nodes.get(element[0]), nodes.get(element[j])); } } return G; } @Test public void testOne() { NumberedGraph<TypedNode<Integer>> G = buildGraph( new Integer[][] { new Integer[] {1, 6, 7, 8}, new Integer[] {2, 5, 7, 8}, new Integer[] {3, 5, 6, 8}, new Integer[] {4, 7, 6, 5}, new Integer[] {5, 2, 4, 3}, new Integer[] {6, 3, 1, 4}, new Integer[] {7, 1, 2, 4}, new Integer[] {8, 1, 2, 3} }); ColoredVertices<TypedNode<Integer>> colors = new WelshPowell<TypedNode<Integer>>().color(G); System.err.println(colors.getColors()); assertColoring(G, colors.getColors(), true); Assert.assertTrue(colors.getNumColors() <= 4); } @Test public void testTwo() { NumberedGraph<TypedNode<String>> G = buildGraph( new String[][] { new String[] {"poly1", "poly2", "star1", "poly5"}, new String[] {"poly2", "poly1", "star2", "poly3"}, new String[] {"poly3", "poly2", "star3", "poly4"}, new String[] {"poly4", "poly3", "star4", "poly5"}, new String[] {"poly5", "poly4", "star5", "poly1"}, new String[] {"star1", "poly1", "star3", "star4"}, new String[] {"star2", "poly2", "star4", "star5"}, new String[] {"star3", "poly3", "star1", "star5"}, new String[] {"star4", "poly4", "star1", "star2"}, new String[] {"star5", "poly5", "star2", "star3"} }); ColoredVertices<TypedNode<String>> colors = new WelshPowell<TypedNode<String>>().color(G); System.err.println(colors.getColors()); assertColoring(G, colors.getColors(), true); Assert.assertEquals(3, colors.getNumColors()); } }
4,323
35.033333
96
java
WALA
WALA-master/core/src/test/java/com/ibm/wala/core/tests/callGraph/AcyclicCallGraphTest.java
package com.ibm.wala.core.tests.callGraph; import com.ibm.wala.core.tests.util.TestConstants; import com.ibm.wala.core.tests.util.WalaTestCase; import com.ibm.wala.ipa.callgraph.AnalysisCacheImpl; import com.ibm.wala.ipa.callgraph.AnalysisOptions; import com.ibm.wala.ipa.callgraph.AnalysisScope; import com.ibm.wala.ipa.callgraph.CGNode; import com.ibm.wala.ipa.callgraph.CallGraph; import com.ibm.wala.ipa.callgraph.Entrypoint; import com.ibm.wala.ipa.callgraph.pruned.PrunedCallGraph; import com.ibm.wala.ipa.cha.ClassHierarchy; import com.ibm.wala.ipa.cha.ClassHierarchyException; import com.ibm.wala.ipa.cha.ClassHierarchyFactory; import com.ibm.wala.util.CancelException; import com.ibm.wala.util.collections.HashMapFactory; import com.ibm.wala.util.collections.HashSetFactory; import com.ibm.wala.util.collections.Iterator2Collection; import com.ibm.wala.util.graph.Acyclic; import com.ibm.wala.util.intset.IBinaryNaturalRelation; import com.ibm.wala.util.intset.IntPair; import java.io.IOException; import java.util.Map; import java.util.Set; import org.junit.Assert; import org.junit.Test; public class AcyclicCallGraphTest extends WalaTestCase { @Test public void testNList() throws ClassHierarchyException, IllegalArgumentException, CancelException, IOException { AnalysisScope scope = CallGraphTestUtil.makeJ2SEAnalysisScope( TestConstants.WALA_TESTDATA, CallGraphTestUtil.REGRESSION_EXCLUSIONS); ClassHierarchy cha = ClassHierarchyFactory.make(scope); Iterable<Entrypoint> entrypoints = com.ibm.wala.ipa.callgraph.impl.Util.makeMainEntrypoints(cha, "Lrecurse/NList"); AnalysisOptions options = CallGraphTestUtil.makeAnalysisOptions(scope, entrypoints); CallGraph cg = CallGraphTestUtil.buildZeroCFA(options, new AnalysisCacheImpl(), cha, false); IBinaryNaturalRelation backEdges = Acyclic.computeBackEdges(cg, cg.getFakeRootNode()); Assert.assertTrue("NList should have cycles", backEdges.iterator().hasNext()); Map<CGNode, Set<CGNode>> cgBackEdges = HashMapFactory.make(); for (IntPair p : backEdges) { CGNode src = cg.getNode(p.getX()); if (!cgBackEdges.containsKey(src)) { cgBackEdges.put(src, HashSetFactory.<CGNode>make()); } cgBackEdges.get(src).add(cg.getNode(p.getY())); } PrunedCallGraph pcg = new PrunedCallGraph(cg, Iterator2Collection.toSet(cg.iterator()), cgBackEdges); Assert.assertFalse( "cycles should be gone", Acyclic.computeBackEdges(pcg, pcg.getFakeRootNode()).iterator().hasNext()); } }
2,574
39.234375
96
java
WALA
WALA-master/core/src/test/java/com/ibm/wala/core/tests/callGraph/CHACallGraphTest.java
/* * Copyright (c) 2013 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package com.ibm.wala.core.tests.callGraph; import com.ibm.wala.core.tests.util.TestConstants; import com.ibm.wala.ipa.callgraph.AnalysisScope; import com.ibm.wala.ipa.callgraph.CGNode; import com.ibm.wala.ipa.callgraph.CallGraph; import com.ibm.wala.ipa.callgraph.CallGraphStats; import com.ibm.wala.ipa.callgraph.Entrypoint; import com.ibm.wala.ipa.callgraph.cha.CHACallGraph; import com.ibm.wala.ipa.callgraph.impl.Util; 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.util.CancelException; import com.ibm.wala.util.intset.IntSet; import java.io.IOException; import java.util.function.Function; import org.junit.Assert; import org.junit.Test; public class CHACallGraphTest { @Test public void testJava_cup() throws ClassHierarchyException, IllegalArgumentException, CancelException, IOException { testCHA( TestConstants.JAVA_CUP, TestConstants.JAVA_CUP_MAIN, CallGraphTestUtil.REGRESSION_EXCLUSIONS); } public static CallGraph testCHA( String scopeFile, final String mainClass, final String exclusionsFile) throws ClassHierarchyException, IllegalArgumentException, CancelException, IOException { return testCHA(scopeFile, exclusionsFile, cha -> Util.makeMainEntrypoints(cha, mainClass)); } public static CallGraph testCHA( String scopeFile, String exclusionsFile, Function<IClassHierarchy, Iterable<Entrypoint>> makeEntrypoints) throws ClassHierarchyException, IllegalArgumentException, CancelException, IOException { AnalysisScope scope = CallGraphTestUtil.makeJ2SEAnalysisScope(scopeFile, exclusionsFile); IClassHierarchy cha = ClassHierarchyFactory.make(scope); CHACallGraph CG = new CHACallGraph(cha); CG.init(makeEntrypoints.apply(cha)); System.err.println(CallGraphStats.getCGStats(CG)); // basic well-formedness for (CGNode node : CG) { int nodeNum = CG.getNumber(node); CG.getSuccNodeNumbers(node) .foreach( succNum -> { CGNode succNode = CG.getNode(succNum); IntSet predNodeNumbers = CG.getPredNodeNumbers(succNode); Assert.assertNotNull( "no predecessors for " + succNode + " which is called by " + node, predNodeNumbers); Assert.assertTrue(predNodeNumbers.contains(nodeNum)); }); } return CG; } public static void main(String[] args) throws ClassHierarchyException, IllegalArgumentException, CancelException, IOException { testCHA(args[0], args.length > 1 ? args[1] : null, "Java60RegressionExclusions.txt"); } }
3,114
37.45679
95
java
WALA
WALA-master/core/src/test/java/com/ibm/wala/core/tests/callGraph/CPATest.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.callGraph; import com.ibm.wala.classLoader.Language; import com.ibm.wala.core.tests.util.TestConstants; import com.ibm.wala.core.tests.util.WalaTestCase; import com.ibm.wala.core.util.strings.Atom; import com.ibm.wala.ipa.callgraph.AnalysisCacheImpl; import com.ibm.wala.ipa.callgraph.AnalysisOptions; import com.ibm.wala.ipa.callgraph.AnalysisScope; import com.ibm.wala.ipa.callgraph.CGNode; import com.ibm.wala.ipa.callgraph.CallGraph; import com.ibm.wala.ipa.callgraph.Entrypoint; import com.ibm.wala.ipa.callgraph.impl.Util; import com.ibm.wala.ipa.callgraph.propagation.CPAContextSelector; import com.ibm.wala.ipa.callgraph.propagation.SSAPropagationCallGraphBuilder; import com.ibm.wala.ipa.cha.ClassHierarchy; import com.ibm.wala.ipa.cha.ClassHierarchyException; import com.ibm.wala.ipa.cha.ClassHierarchyFactory; import com.ibm.wala.types.ClassLoaderReference; import com.ibm.wala.types.Descriptor; import com.ibm.wala.types.MethodReference; import com.ibm.wala.types.TypeReference; import com.ibm.wala.util.CancelException; import java.io.IOException; import java.util.Set; import org.junit.Assert; import org.junit.Test; /** Check properties of a call to clone() in RTA */ public class CPATest extends WalaTestCase { @Test public void cpaTest1() throws ClassHierarchyException, IllegalArgumentException, CancelException, IOException { doCPATest("Lcpa/CPATest1", "(Lcpa/CPATest1$N;)Lcpa/CPATest1$N;"); } @Test public void cpaTest2() throws ClassHierarchyException, IllegalArgumentException, CancelException, IOException { doCPATest("Lcpa/CPATest2", "(Lcpa/CPATest2$N;I)Lcpa/CPATest2$N;"); } private static void doCPATest(String testClass, String testIdSignature) throws ClassHierarchyException, IllegalArgumentException, CancelException, IOException { AnalysisScope scope = CallGraphTestUtil.makeJ2SEAnalysisScope( TestConstants.WALA_TESTDATA, CallGraphTestUtil.REGRESSION_EXCLUSIONS); ClassHierarchy cha = ClassHierarchyFactory.make(scope); Iterable<Entrypoint> entrypoints = com.ibm.wala.ipa.callgraph.impl.Util.makeMainEntrypoints(cha, testClass); AnalysisOptions options = CallGraphTestUtil.makeAnalysisOptions(scope, entrypoints); SSAPropagationCallGraphBuilder builder = Util.makeZeroCFABuilder(Language.JAVA, options, new AnalysisCacheImpl(), cha); builder.setContextSelector(new CPAContextSelector(builder.getContextSelector())); CallGraph cg = builder.makeCallGraph(options, null); // Find id TypeReference str = TypeReference.findOrCreate(ClassLoaderReference.Application, testClass); MethodReference ct = MethodReference.findOrCreate( str, Atom.findOrCreateUnicodeAtom("id"), Descriptor.findOrCreateUTF8(testIdSignature)); Set<CGNode> idNodes = cg.getNodes(ct); System.err.println(cg); Assert.assertEquals(2, idNodes.size()); } }
3,310
39.378049
99
java
WALA
WALA-master/core/src/test/java/com/ibm/wala/core/tests/callGraph/CallGraphTest.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.callGraph; import com.ibm.wala.classLoader.IClass; import com.ibm.wala.classLoader.IMethod; import com.ibm.wala.classLoader.Language; import com.ibm.wala.core.tests.demandpa.AbstractPtrTest; import com.ibm.wala.core.tests.util.TestConstants; import com.ibm.wala.core.tests.util.WalaTestCase; import com.ibm.wala.core.util.strings.Atom; import com.ibm.wala.core.util.warnings.Warnings; import com.ibm.wala.ipa.callgraph.AnalysisCacheImpl; import com.ibm.wala.ipa.callgraph.AnalysisOptions; import com.ibm.wala.ipa.callgraph.AnalysisOptions.ReflectionOptions; import com.ibm.wala.ipa.callgraph.AnalysisScope; import com.ibm.wala.ipa.callgraph.CGNode; import com.ibm.wala.ipa.callgraph.CallGraph; import com.ibm.wala.ipa.callgraph.CallGraphBuilder; import com.ibm.wala.ipa.callgraph.CallGraphStats; import com.ibm.wala.ipa.callgraph.Entrypoint; import com.ibm.wala.ipa.callgraph.IAnalysisCacheView; import com.ibm.wala.ipa.callgraph.impl.AllApplicationEntrypoints; import com.ibm.wala.ipa.callgraph.impl.DefaultEntrypoint; import com.ibm.wala.ipa.callgraph.impl.Util; import com.ibm.wala.ipa.callgraph.propagation.InstanceKey; import com.ibm.wala.ipa.callgraph.propagation.PointerAnalysis; import com.ibm.wala.ipa.callgraph.propagation.PointerKey; import com.ibm.wala.ipa.callgraph.propagation.SSAPropagationCallGraphBuilder; import com.ibm.wala.ipa.callgraph.util.CallGraphSearchUtil; import com.ibm.wala.ipa.cfg.BasicBlockInContext; import com.ibm.wala.ipa.cfg.InterproceduralCFG; import com.ibm.wala.ipa.cha.ClassHierarchy; import com.ibm.wala.ipa.cha.ClassHierarchyException; import com.ibm.wala.ipa.cha.ClassHierarchyFactory; import com.ibm.wala.ipa.cha.IClassHierarchy; import com.ibm.wala.ssa.ISSABasicBlock; import com.ibm.wala.types.Descriptor; import com.ibm.wala.types.MethodReference; import com.ibm.wala.util.CancelException; import com.ibm.wala.util.collections.HashSetFactory; import com.ibm.wala.util.collections.Iterator2Iterable; import com.ibm.wala.util.collections.IteratorUtil; import com.ibm.wala.util.debug.Assertions; import com.ibm.wala.util.graph.Graph; import com.ibm.wala.util.graph.GraphIntegrity; import com.ibm.wala.util.graph.GraphIntegrity.UnsoundGraphException; import com.ibm.wala.util.intset.OrdinalSet; import java.io.IOException; import java.util.HashSet; import java.util.Iterator; import java.util.Set; import java.util.Spliterator; import java.util.Spliterators; import java.util.stream.Stream; import java.util.stream.StreamSupport; import org.junit.Assert; import org.junit.Test; /** Tests for Call Graph construction */ public class CallGraphTest extends WalaTestCase { public static void main(String[] args) { justThisTest(CallGraphTest.class); } @Test public void testJava_cup() throws ClassHierarchyException, IllegalArgumentException, CancelException, IOException { AnalysisScope scope = CallGraphTestUtil.makeJ2SEAnalysisScope( TestConstants.JAVA_CUP, CallGraphTestUtil.REGRESSION_EXCLUSIONS); ClassHierarchy cha = ClassHierarchyFactory.make(scope); Iterable<Entrypoint> entrypoints = com.ibm.wala.ipa.callgraph.impl.Util.makeMainEntrypoints(cha, TestConstants.JAVA_CUP_MAIN); AnalysisOptions options = CallGraphTestUtil.makeAnalysisOptions(scope, entrypoints); doCallGraphs(options, new AnalysisCacheImpl(), cha, useShortProfile()); } @Test public void testBcelVerifier() throws ClassHierarchyException, IllegalArgumentException, CancelException, IOException { AnalysisScope scope = CallGraphTestUtil.makeJ2SEAnalysisScope( TestConstants.BCEL, CallGraphTestUtil.REGRESSION_EXCLUSIONS); ClassHierarchy cha = ClassHierarchyFactory.make(scope); Iterable<Entrypoint> entrypoints = com.ibm.wala.ipa.callgraph.impl.Util.makeMainEntrypoints( cha, TestConstants.BCEL_VERIFIER_MAIN); AnalysisOptions options = CallGraphTestUtil.makeAnalysisOptions(scope, entrypoints); // this speeds up the test options.setReflectionOptions(ReflectionOptions.NONE); doCallGraphs(options, new AnalysisCacheImpl(), cha); } @Test public void testJLex() throws ClassHierarchyException, IllegalArgumentException, CancelException, IOException { AnalysisScope scope = CallGraphTestUtil.makeJ2SEAnalysisScope( TestConstants.JLEX, CallGraphTestUtil.REGRESSION_EXCLUSIONS); ClassHierarchy cha = ClassHierarchyFactory.make(scope); Iterable<Entrypoint> entrypoints = com.ibm.wala.ipa.callgraph.impl.Util.makeMainEntrypoints(cha, TestConstants.JLEX_MAIN); AnalysisOptions options = CallGraphTestUtil.makeAnalysisOptions(scope, entrypoints); doCallGraphs(options, new AnalysisCacheImpl(), cha); } @Test public void testCornerCases() throws ClassHierarchyException, IllegalArgumentException, CancelException, IOException { AnalysisScope scope = CallGraphTestUtil.makeJ2SEAnalysisScope( TestConstants.WALA_TESTDATA, CallGraphTestUtil.REGRESSION_EXCLUSIONS); ClassHierarchy cha = ClassHierarchyFactory.make(scope); Iterable<Entrypoint> entrypoints = new AllApplicationEntrypoints(scope, cha); AnalysisOptions options = CallGraphTestUtil.makeAnalysisOptions(scope, entrypoints); // this speeds up the test options.setReflectionOptions(ReflectionOptions.NONE); doCallGraphs(options, new AnalysisCacheImpl(), cha); // we expect a warning or two about class Abstract1, which has no concrete // subclasses String ws = Warnings.asString(); Assert.assertTrue( "failed to report a warning about Abstract1", ws.contains("cornerCases/Abstract1")); // we do not expect a warning about class Abstract2, which has a concrete // subclasses Assert.assertFalse("reported a warning about Abstract2", ws.contains("cornerCases/Abstract2")); } @Test public void testHello() throws ClassHierarchyException, IllegalArgumentException, CancelException, IOException { AnalysisScope scope = CallGraphTestUtil.makeJ2SEAnalysisScope( TestConstants.HELLO, CallGraphTestUtil.REGRESSION_EXCLUSIONS); ClassHierarchy cha = ClassHierarchyFactory.make(scope); Iterable<Entrypoint> entrypoints = com.ibm.wala.ipa.callgraph.impl.Util.makeMainEntrypoints(cha, TestConstants.HELLO_MAIN); AnalysisOptions options = CallGraphTestUtil.makeAnalysisOptions(scope, entrypoints); doCallGraphs(options, new AnalysisCacheImpl(), cha); } @Test public void testStaticInit() throws ClassHierarchyException, IllegalArgumentException, CancelException, IOException { AnalysisScope scope = CallGraphTestUtil.makeJ2SEAnalysisScope( TestConstants.WALA_TESTDATA, CallGraphTestUtil.REGRESSION_EXCLUSIONS); ClassHierarchy cha = ClassHierarchyFactory.make(scope); Iterable<Entrypoint> entrypoints = com.ibm.wala.ipa.callgraph.impl.Util.makeMainEntrypoints(cha, "LstaticInit/TestStaticInit"); AnalysisOptions options = CallGraphTestUtil.makeAnalysisOptions(scope, entrypoints); CallGraph cg = CallGraphTestUtil.buildZeroCFA(options, new AnalysisCacheImpl(), cha, false); boolean foundDoNothing = false; for (CGNode n : cg) { if (n.toString().contains("doNothing")) { foundDoNothing = true; break; } } Assert.assertTrue(foundDoNothing); options.setHandleStaticInit(false); cg = CallGraphTestUtil.buildZeroCFA(options, new AnalysisCacheImpl(), cha, false); for (CGNode n : cg) { Assert.assertFalse(n.toString().contains("doNothing")); } } @Test public void testJava8Smoke() throws ClassHierarchyException, IllegalArgumentException, CancelException, IOException { AnalysisScope scope = CallGraphTestUtil.makeJ2SEAnalysisScope( TestConstants.WALA_TESTDATA, CallGraphTestUtil.REGRESSION_EXCLUSIONS); ClassHierarchy cha = ClassHierarchyFactory.make(scope); Iterable<Entrypoint> entrypoints = com.ibm.wala.ipa.callgraph.impl.Util.makeMainEntrypoints(cha, "Llambda/SortingExample"); AnalysisOptions options = CallGraphTestUtil.makeAnalysisOptions(scope, entrypoints); CallGraph cg = CallGraphTestUtil.buildZeroCFA(options, new AnalysisCacheImpl(), cha, false); boolean foundSortForward = false; for (CGNode n : cg) { if (n.toString().contains("sortForward")) { foundSortForward = true; } } Assert.assertTrue("expected for sortForward", foundSortForward); } @Test public void testSystemProperties() throws ClassHierarchyException, IllegalArgumentException, CancelException, IOException { AnalysisScope scope = CallGraphTestUtil.makeJ2SEAnalysisScope( TestConstants.WALA_TESTDATA, CallGraphTestUtil.REGRESSION_EXCLUSIONS); ClassHierarchy cha = ClassHierarchyFactory.make(scope); Iterable<Entrypoint> entrypoints = com.ibm.wala.ipa.callgraph.impl.Util.makeMainEntrypoints( cha, "LstaticInit/TestSystemProperties"); AnalysisOptions options = CallGraphTestUtil.makeAnalysisOptions(scope, entrypoints); SSAPropagationCallGraphBuilder builder = Util.makeZeroCFABuilder(Language.JAVA, options, new AnalysisCacheImpl(), cha); CallGraph cg = builder.makeCallGraph(options); for (CGNode n : cg) { if (n.toString() .equals( "Node: < Application, LstaticInit/TestSystemProperties, main([Ljava/lang/String;)V > Context: Everywhere")) { boolean foundToCharArray = false; for (CGNode callee : Iterator2Iterable.make(cg.getSuccNodes(n))) { if (callee.getMethod().getName().toString().equals("toCharArray")) { foundToCharArray = true; break; } } Assert.assertTrue(foundToCharArray); break; } } } @Test public void testRecursion() throws ClassHierarchyException, IllegalArgumentException, CancelException, IOException { AnalysisScope scope = CallGraphTestUtil.makeJ2SEAnalysisScope( TestConstants.WALA_TESTDATA, CallGraphTestUtil.REGRESSION_EXCLUSIONS); ClassHierarchy cha = ClassHierarchyFactory.make(scope); Iterable<Entrypoint> entrypoints = com.ibm.wala.ipa.callgraph.impl.Util.makeMainEntrypoints(cha, TestConstants.RECURSE_MAIN); AnalysisOptions options = CallGraphTestUtil.makeAnalysisOptions(scope, entrypoints); doCallGraphs(options, new AnalysisCacheImpl(), cha); } @Test public void testHelloAllEntrypoints() throws ClassHierarchyException, IllegalArgumentException, CancelException, IOException { AnalysisScope scope = CallGraphTestUtil.makeJ2SEAnalysisScope( TestConstants.HELLO, CallGraphTestUtil.REGRESSION_EXCLUSIONS); ClassHierarchy cha = ClassHierarchyFactory.make(scope); Iterable<Entrypoint> entrypoints = new AllApplicationEntrypoints(scope, cha); AnalysisOptions options = CallGraphTestUtil.makeAnalysisOptions(scope, entrypoints); doCallGraphs(options, new AnalysisCacheImpl(), cha); } @Test public void testIO() throws ClassHierarchyException, IllegalArgumentException, CancelException, IOException { AnalysisScope scope = CallGraphTestUtil.makeJ2SEAnalysisScope( "primordial-base.txt", CallGraphTestUtil.REGRESSION_EXCLUSIONS); ClassHierarchy cha = ClassHierarchyFactory.make(scope); Iterable<Entrypoint> entrypoints = makePrimordialPublicEntrypoints(cha, "java/io"); AnalysisOptions options = CallGraphTestUtil.makeAnalysisOptions(scope, entrypoints); CallGraphTestUtil.buildZeroCFA(options, new AnalysisCacheImpl(), cha, false); } public static Iterable<Entrypoint> makePrimordialPublicEntrypoints( ClassHierarchy cha, String pkg) { final HashSet<Entrypoint> result = HashSetFactory.make(); for (IClass clazz : cha) { if (clazz.getName().toString().contains(pkg) && !clazz.isInterface() && !clazz.isAbstract()) { for (IMethod method : clazz.getDeclaredMethods()) { if (method.isPublic() && !method.isAbstract()) { System.out.println("Entry:" + method.getReference()); result.add(new DefaultEntrypoint(method, cha)); } } } } return result::iterator; } @Test public void testPrimordial() throws ClassHierarchyException, IllegalArgumentException, CancelException, IOException { if (useShortProfile()) { return; } AnalysisScope scope = CallGraphTestUtil.makeJ2SEAnalysisScope( "primordial.txt", System.getProperty("os.name").equals("Mac OS X") ? "Java60RegressionExclusions.txt" : "GUIExclusions.txt"); ClassHierarchy cha = ClassHierarchyFactory.make(scope); Iterable<Entrypoint> entrypoints = makePrimordialMainEntrypoints(cha); AnalysisOptions options = CallGraphTestUtil.makeAnalysisOptions(scope, entrypoints); CallGraphTestUtil.buildZeroCFA(options, new AnalysisCacheImpl(), cha, false); } @Test public void testZeroOneContainerCopyOf() throws IOException, ClassHierarchyException, IllegalArgumentException, CancelException { AnalysisScope scope = CallGraphTestUtil.makeJ2SEAnalysisScope( TestConstants.WALA_TESTDATA, CallGraphTestUtil.REGRESSION_EXCLUSIONS); ClassHierarchy cha = ClassHierarchyFactory.make(scope); Iterable<Entrypoint> entrypoints = Util.makeMainEntrypoints(cha, "Ldemandpa/TestArraysCopyOf"); AnalysisOptions options = CallGraphTestUtil.makeAnalysisOptions(scope, entrypoints); IAnalysisCacheView cache = new AnalysisCacheImpl(); CallGraphBuilder<InstanceKey> builder = Util.makeZeroOneContainerCFABuilder(options, cache, cha); CallGraph cg = builder.makeCallGraph(options, null); PointerAnalysis<InstanceKey> pa = builder.getPointerAnalysis(); CGNode mainMethod = AbstractPtrTest.findMainMethod(cg); PointerKey keyToQuery = AbstractPtrTest.getParam(mainMethod, "testThisVar", pa.getHeapModel()); OrdinalSet<InstanceKey> pointsToSet = pa.getPointsToSet(keyToQuery); Assert.assertEquals(1, pointsToSet.size()); } @Test public void testZeroOneContainerStaticMethods() throws IOException, ClassHierarchyException, IllegalArgumentException, CancelException { AnalysisScope scope = CallGraphTestUtil.makeJ2SEAnalysisScope( TestConstants.WALA_TESTDATA, CallGraphTestUtil.REGRESSION_EXCLUSIONS); ClassHierarchy cha = ClassHierarchyFactory.make(scope); Iterable<Entrypoint> entrypoints = Util.makeMainEntrypoints(cha, "Lslice/TestIntegerValueOf"); AnalysisOptions options = CallGraphTestUtil.makeAnalysisOptions(scope, entrypoints); IAnalysisCacheView cache = new AnalysisCacheImpl(); CallGraphBuilder<InstanceKey> builder = Util.makeZeroOneContainerCFABuilder(options, cache, cha); CallGraph cg = builder.makeCallGraph(options, null); CGNode mainMethod = CallGraphSearchUtil.findMainMethod(cg); Assert.assertTrue( "did not find call to valueOf", StreamSupport.stream( Spliterators.spliteratorUnknownSize( cg.getSuccNodes(mainMethod), Spliterator.ORDERED), false) .filter(succ -> succ.getMethod().getName().toString().equals("valueOf")) .findFirst() .isPresent()); } /** make main entrypoints, even in the primordial loader. */ public static Iterable<Entrypoint> makePrimordialMainEntrypoints(ClassHierarchy cha) { final Atom mainMethod = Atom.findOrCreateAsciiAtom("main"); final HashSet<Entrypoint> result = HashSetFactory.make(); for (IClass klass : cha) { MethodReference mainRef = MethodReference.findOrCreate( klass.getReference(), mainMethod, Descriptor.findOrCreateUTF8("([Ljava/lang/String;)V")); IMethod m = klass.getMethod(mainRef.getSelector()); if (m != null) { result.add(new DefaultEntrypoint(m, cha)); } } return result::iterator; } public static void doCallGraphs( AnalysisOptions options, IAnalysisCacheView cache, IClassHierarchy cha) throws IllegalArgumentException, CancelException { doCallGraphs(options, cache, cha, false); } /** TODO: refactor this to avoid excessive code bloat. */ public static void doCallGraphs( AnalysisOptions options, IAnalysisCacheView cache, IClassHierarchy cha, boolean testPAToString) throws IllegalArgumentException, CancelException { // /////////////// // // RTA ///// // /////////////// CallGraph cg = CallGraphTestUtil.buildRTA(options, cache, cha); try { GraphIntegrity.check(cg); } catch (UnsoundGraphException e1) { e1.printStackTrace(); Assert.fail(e1.getMessage()); } Set<MethodReference> rtaMethods = CallGraphStats.collectMethods(cg); System.err.println("RTA methods reached: " + rtaMethods.size()); System.err.println(CallGraphStats.getStats(cg)); System.err.println("RTA warnings:\n"); // /////////////// // // 0-CFA ///// // /////////////// cg = CallGraphTestUtil.buildZeroCFA(options, cache, cha, testPAToString); // FIXME: annoying special cases caused by clone2assign mean using // the rta graph for proper graph subset checking does not work. // (note that all the other such checks do use proper graph subset) Graph<MethodReference> squashZero = checkCallGraph(cg, null, "0-CFA"); // test Pretransitive 0-CFA // not currently supported // warnings = new WarningSet(); // options.setUsePreTransitiveSolver(true); // CallGraph cgP = CallGraphTestUtil.buildZeroCFA(options, cha, scope, // warnings); // options.setUsePreTransitiveSolver(false); // Graph squashPT = checkCallGraph(warnings, cgP, squashZero, null, "Pre-T // 1"); // checkCallGraph(warnings, cg, squashPT, null, "Pre-T 2"); // /////////////// // // 0-1-CFA /// // /////////////// cg = CallGraphTestUtil.buildZeroOneCFA(options, cache, cha, testPAToString); Graph<MethodReference> squashZeroOne = checkCallGraph(cg, squashZero, "0-1-CFA"); // /////////////////////////////////////////////////// // // 0-CFA augmented to disambiguate containers /// // /////////////////////////////////////////////////// cg = CallGraphTestUtil.buildZeroContainerCFA(options, cache, cha); Graph<MethodReference> squashZeroContainer = checkCallGraph(cg, squashZero, "0-Container-CFA"); // /////////////////////////////////////////////////// // // 0-1-CFA augmented to disambiguate containers /// // /////////////////////////////////////////////////// cg = CallGraphTestUtil.buildZeroOneContainerCFA(options, cache, cha); checkCallGraph(cg, squashZeroContainer, "0-1-Container-CFA"); checkCallGraph(cg, squashZeroOne, "0-1-Container-CFA"); // test ICFG checkICFG(cg); return; // ///////////// // // 1-CFA /// // ///////////// // warnings = new WarningSet(); // cg = buildOneCFA(); } /** Check properties of the InterproceduralCFG */ private static void checkICFG(CallGraph cg) { InterproceduralCFG icfg = new InterproceduralCFG(cg); try { GraphIntegrity.check(icfg); } catch (UnsoundGraphException e) { e.printStackTrace(); Assert.fail(); } // perform a little icfg exercise @SuppressWarnings("unused") int count = 0; for (BasicBlockInContext<ISSABasicBlock> bb : icfg) { if (icfg.hasCall(bb)) { count++; } } } /** * Check consistency of a callgraph, and check that this call graph is a subset of a super-graph * * @return a squashed version of cg */ private static Graph<MethodReference> checkCallGraph( CallGraph cg, Graph<MethodReference> superCG, String thisAlgorithm) { try { GraphIntegrity.check(cg); } catch (UnsoundGraphException e1) { Assert.fail(e1.getMessage()); } Set<MethodReference> callGraphMethods = CallGraphStats.collectMethods(cg); System.err.println(thisAlgorithm + " methods reached: " + callGraphMethods.size()); System.err.println(CallGraphStats.getStats(cg)); Graph<MethodReference> thisCG = squashCallGraph(thisAlgorithm, cg); if (superCG != null) { com.ibm.wala.ipa.callgraph.impl.Util.checkGraphSubset(superCG, thisCG); } else { // SJF: RTA has rotted a bit since it doesn't handle LoadClass instructions. // Commenting this out for now. // if (!superMethods.containsAll(callGraphMethods)) { // Set<MethodReference> temp = HashSetFactory.make(); // temp.addAll(callGraphMethods); // temp.removeAll(superMethods); // System.err.println("Violations"); // for (MethodReference m : temp) { // System.err.println(m); // } // Assertions.UNREACHABLE(); // } } return thisCG; } /** * @return a graph whose nodes are MethodReferences, and whose edges represent calls between * MethodReferences * @throws IllegalArgumentException if cg is null */ public static Graph<MethodReference> squashCallGraph(final String name, final CallGraph cg) { if (cg == null) { throw new IllegalArgumentException("cg is null"); } final Set<MethodReference> nodes = HashSetFactory.make(); for (CGNode cgNode : cg) { nodes.add(cgNode.getMethod().getReference()); } return new Graph<>() { @Override public String toString() { return "squashed " + name + " call graph\n" + "Original graph:" + cg; } /* * @see com.ibm.wala.util.graph.NodeManager#iterator() */ @Override public Iterator<MethodReference> iterator() { return nodes.iterator(); } @Override public Stream<MethodReference> stream() { return nodes.stream(); } /* * @see com.ibm.wala.util.graph.NodeManager#containsNode(java.lang.Object) */ @Override public boolean containsNode(MethodReference N) { return nodes.contains(N); } /* * @see com.ibm.wala.util.graph.NodeManager#getNumberOfNodes() */ @Override public int getNumberOfNodes() { return nodes.size(); } /* * @see com.ibm.wala.util.graph.EdgeManager#getPredNodes(java.lang.Object) */ @Override public Iterator<MethodReference> getPredNodes(MethodReference N) { Set<MethodReference> pred = HashSetFactory.make(10); MethodReference methodReference = N; for (CGNode cgNode : cg.getNodes(methodReference)) for (CGNode p : Iterator2Iterable.make(cg.getPredNodes(cgNode))) pred.add(p.getMethod().getReference()); return pred.iterator(); } /* * @see com.ibm.wala.util.graph.EdgeManager#getPredNodeCount(java.lang.Object) */ @Override public int getPredNodeCount(MethodReference N) { return IteratorUtil.count(getPredNodes(N)); } /* * @see com.ibm.wala.util.graph.EdgeManager#getSuccNodes(java.lang.Object) */ @Override public Iterator<MethodReference> getSuccNodes(MethodReference N) { Set<MethodReference> succ = HashSetFactory.make(10); MethodReference methodReference = N; for (CGNode node : cg.getNodes(methodReference)) for (CGNode p : Iterator2Iterable.make(cg.getSuccNodes(node))) succ.add(p.getMethod().getReference()); return succ.iterator(); } /* * @see com.ibm.wala.util.graph.EdgeManager#getSuccNodeCount(java.lang.Object) */ @Override public int getSuccNodeCount(MethodReference N) { return IteratorUtil.count(getSuccNodes(N)); } /* * @see com.ibm.wala.util.graph.NodeManager#addNode(java.lang.Object) */ @Override public void addNode(MethodReference n) { Assertions.UNREACHABLE(); } /* * @see com.ibm.wala.util.graph.NodeManager#removeNode(java.lang.Object) */ @Override public void removeNode(MethodReference n) { Assertions.UNREACHABLE(); } /* * @see com.ibm.wala.util.graph.EdgeManager#addEdge(java.lang.Object, java.lang.Object) */ @Override public void addEdge(MethodReference src, MethodReference dst) { Assertions.UNREACHABLE(); } @Override public void removeEdge(MethodReference src, MethodReference dst) { Assertions.UNREACHABLE(); } /* * @see com.ibm.wala.util.graph.EdgeManager#removeAllIncidentEdges(java.lang.Object) */ @Override public void removeAllIncidentEdges(MethodReference node) { Assertions.UNREACHABLE(); } /* * @see com.ibm.wala.util.graph.Graph#removeNodeAndEdges(java.lang.Object) */ @Override public void removeNodeAndEdges(MethodReference N) { Assertions.UNREACHABLE(); } @Override public void removeIncomingEdges(MethodReference node) { // TODO Auto-generated method stubMethodReference Assertions.UNREACHABLE(); } @Override public void removeOutgoingEdges(MethodReference node) { // TODO Auto-generated method stub Assertions.UNREACHABLE(); } @Override public boolean hasEdge(MethodReference src, MethodReference dst) { for (MethodReference succ : Iterator2Iterable.make(getSuccNodes(src))) { if (dst.equals(succ)) { return true; } } return false; } }; } }
26,137
37.551622
123
java
WALA
WALA-master/core/src/test/java/com/ibm/wala/core/tests/callGraph/ClassConstantTest.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.core.tests.util.TestConstants; import com.ibm.wala.core.tests.util.WalaTestCase; import com.ibm.wala.ipa.callgraph.AnalysisCacheImpl; import com.ibm.wala.ipa.callgraph.AnalysisOptions; import com.ibm.wala.ipa.callgraph.AnalysisScope; import com.ibm.wala.ipa.callgraph.CGNode; import com.ibm.wala.ipa.callgraph.CallGraph; import com.ibm.wala.ipa.callgraph.Entrypoint; import com.ibm.wala.ipa.callgraph.impl.Util; import com.ibm.wala.ipa.cha.ClassHierarchy; import com.ibm.wala.ipa.cha.ClassHierarchyException; import com.ibm.wala.ipa.cha.ClassHierarchyFactory; import com.ibm.wala.types.ClassLoaderReference; import com.ibm.wala.types.MethodReference; import com.ibm.wala.types.TypeReference; import com.ibm.wala.util.CancelException; import java.io.IOException; import java.util.Set; import org.junit.Assert; import org.junit.Test; /** Check handling of class constants (test for part of 1.5 support) */ public class ClassConstantTest extends WalaTestCase { @Test public void testClassConstants() throws ClassHierarchyException, IllegalArgumentException, CancelException, IOException { AnalysisScope scope = CallGraphTestUtil.makeJ2SEAnalysisScope( TestConstants.WALA_TESTDATA, CallGraphTestUtil.REGRESSION_EXCLUSIONS); ClassHierarchy cha = ClassHierarchyFactory.make(scope); // make sure we have the test class TypeReference mainClassRef = TypeReference.findOrCreate( ClassLoaderReference.Application, TestConstants.CLASSCONSTANT_MAIN); Assert.assertNotNull(cha.lookupClass(mainClassRef)); // make call graph Iterable<Entrypoint> entrypoints = Util.makeMainEntrypoints(cha, TestConstants.CLASSCONSTANT_MAIN); AnalysisOptions options = CallGraphTestUtil.makeAnalysisOptions(scope, entrypoints); CallGraph cg = CallGraphTestUtil.buildZeroCFA(options, new AnalysisCacheImpl(), cha, false); // System.out.println("\nCall graph:"); // Trace.println(cg); // make sure the main method is reached MethodReference mainMethodRef = MethodReference.findOrCreate(mainClassRef, "main", "([Ljava/lang/String;)V"); Set<CGNode> mainMethodNodes = cg.getNodes(mainMethodRef); Assert.assertFalse(mainMethodNodes.isEmpty()); CGNode mainMethodNode = mainMethodNodes.iterator().next(); // Trace.println("main IR:"); // Trace.println(mainMethodNode.getIR()); // Make sure call to hashCode is there (it uses the class constant) TypeReference classRef = TypeReference.findOrCreate(ClassLoaderReference.Primordial, "Ljava/lang/Class"); MethodReference hashCodeRef = MethodReference.findOrCreate(classRef, "hashCode", "()I"); Set<CGNode> hashCodeNodes = cg.getNodes(hashCodeRef); Assert.assertFalse(hashCodeNodes.isEmpty()); // make sure call to hashCode from main Assert.assertTrue(cg.hasEdge(mainMethodNode, hashCodeNodes.iterator().next())); } }
3,345
40.825
96
java
WALA
WALA-master/core/src/test/java/com/ibm/wala/core/tests/callGraph/CloneTest.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.callGraph; import com.ibm.wala.classLoader.CallSiteReference; import com.ibm.wala.core.tests.util.TestConstants; import com.ibm.wala.core.tests.util.WalaTestCase; import com.ibm.wala.ipa.callgraph.AnalysisCacheImpl; import com.ibm.wala.ipa.callgraph.AnalysisOptions; import com.ibm.wala.ipa.callgraph.AnalysisScope; import com.ibm.wala.ipa.callgraph.CGNode; import com.ibm.wala.ipa.callgraph.CallGraph; import com.ibm.wala.ipa.callgraph.Entrypoint; import com.ibm.wala.ipa.callgraph.impl.AllApplicationEntrypoints; import com.ibm.wala.ipa.cha.ClassHierarchy; import com.ibm.wala.ipa.cha.ClassHierarchyException; import com.ibm.wala.ipa.cha.ClassHierarchyFactory; import com.ibm.wala.types.ClassLoaderReference; import com.ibm.wala.types.MethodReference; import com.ibm.wala.types.TypeReference; import com.ibm.wala.util.CancelException; import com.ibm.wala.util.collections.Iterator2Iterable; import java.io.IOException; import java.util.Set; import org.junit.Assert; import org.junit.Test; /** Check properties of a call to clone() in RTA */ public class CloneTest extends WalaTestCase { @Test public void testClone() throws ClassHierarchyException, IllegalArgumentException, CancelException, IOException { AnalysisScope scope = CallGraphTestUtil.makeJ2SEAnalysisScope( TestConstants.WALA_TESTDATA, CallGraphTestUtil.REGRESSION_EXCLUSIONS); ClassHierarchy cha = ClassHierarchyFactory.make(scope); Iterable<Entrypoint> entrypoints = new AllApplicationEntrypoints(scope, cha); AnalysisOptions options = CallGraphTestUtil.makeAnalysisOptions(scope, entrypoints); CallGraph cg = CallGraphTestUtil.buildRTA(options, new AnalysisCacheImpl(), cha); // Find node corresponding to java.text.MessageFormat.clone() TypeReference t = TypeReference.findOrCreate(ClassLoaderReference.Primordial, "Ljava/text/MessageFormat"); MethodReference m = MethodReference.findOrCreate(t, "clone", "()Ljava/lang/Object;"); CGNode node = cg.getNodes(m).iterator().next(); // Check there's exactly one target for each super call in // MessageFormat.clone() for (CallSiteReference site : Iterator2Iterable.make(node.iterateCallSites())) { if (site.isSpecial()) { if (site.getDeclaredTarget().getDeclaringClass().equals(TypeReference.JavaLangObject)) { Set<CGNode> targets = cg.getPossibleTargets(node, site); if (targets.size() != 1) { System.err.println(targets.size() + " targets found for " + site); for (CGNode cgNode : targets) { System.err.println(" " + cgNode); } Assert.fail("found " + targets.size() + " targets for " + site + " in " + node); } } } } } }
3,156
40.539474
96
java
WALA
WALA-master/core/src/test/java/com/ibm/wala/core/tests/callGraph/DebuggingBitsetCallGraphTest.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.callGraph; import com.ibm.wala.core.tests.util.WalaTestCase; import com.ibm.wala.ipa.cha.ClassHierarchyException; import com.ibm.wala.util.CancelException; import com.ibm.wala.util.intset.BimodalMutableIntSetFactory; import com.ibm.wala.util.intset.BitVectorIntSetFactory; import com.ibm.wala.util.intset.DebuggingMutableIntSetFactory; import com.ibm.wala.util.intset.IntSetUtil; import com.ibm.wala.util.intset.MutableIntSetFactory; import com.ibm.wala.util.intset.MutableSharedBitVectorIntSetFactory; import com.ibm.wala.util.intset.MutableSparseIntSetFactory; import com.ibm.wala.util.intset.SemiSparseMutableIntSetFactory; import java.io.IOException; import org.junit.Test; /** Run the call graph only test with paranoid debugging bit vectors */ public class DebuggingBitsetCallGraphTest extends WalaTestCase { public static void main(String[] args) { justThisTest(DebuggingBitsetCallGraphTest.class); } private final CallGraphTest graphTest; public DebuggingBitsetCallGraphTest() { graphTest = new CallGraphTest(); } private void runBitsetTest(MutableIntSetFactory<?> p, MutableIntSetFactory<?> s) throws ClassHierarchyException, IllegalArgumentException, CancelException, IOException { MutableIntSetFactory<?> save = IntSetUtil.getDefaultIntSetFactory(); try { IntSetUtil.setDefaultIntSetFactory(new DebuggingMutableIntSetFactory(p, s)); graphTest.testJLex(); } finally { IntSetUtil.setDefaultIntSetFactory(save); } } @Test public void testBimodalSparse() throws ClassHierarchyException, IllegalArgumentException, CancelException, IOException { runBitsetTest(new BimodalMutableIntSetFactory(), new MutableSparseIntSetFactory()); } @Test public void testSharedBimodal() throws ClassHierarchyException, IllegalArgumentException, CancelException, IOException { runBitsetTest(new MutableSharedBitVectorIntSetFactory(), new BimodalMutableIntSetFactory()); } @Test public void testSharedSparse() throws ClassHierarchyException, IllegalArgumentException, CancelException, IOException { runBitsetTest(new MutableSharedBitVectorIntSetFactory(), new MutableSparseIntSetFactory()); } @Test public void testSharedBitVector() throws ClassHierarchyException, IllegalArgumentException, CancelException, IOException { runBitsetTest(new MutableSharedBitVectorIntSetFactory(), new BitVectorIntSetFactory()); } @Test public void testSemiSparseShared() throws ClassHierarchyException, IllegalArgumentException, CancelException, IOException { runBitsetTest(new SemiSparseMutableIntSetFactory(), new MutableSharedBitVectorIntSetFactory()); } }
3,081
37.049383
99
java
WALA
WALA-master/core/src/test/java/com/ibm/wala/core/tests/callGraph/DefaultMethodsTest.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.callGraph; import com.ibm.wala.classLoader.IClass; import com.ibm.wala.classLoader.IMethod; import com.ibm.wala.core.tests.util.TestConstants; import com.ibm.wala.core.tests.util.WalaTestCase; import com.ibm.wala.ipa.callgraph.AnalysisCacheImpl; import com.ibm.wala.ipa.callgraph.AnalysisOptions; import com.ibm.wala.ipa.callgraph.AnalysisScope; import com.ibm.wala.ipa.callgraph.CGNode; import com.ibm.wala.ipa.callgraph.CallGraph; import com.ibm.wala.ipa.callgraph.Entrypoint; import com.ibm.wala.ipa.cha.ClassHierarchy; import com.ibm.wala.ipa.cha.ClassHierarchyException; import com.ibm.wala.ipa.cha.ClassHierarchyFactory; import com.ibm.wala.types.ClassLoaderReference; import com.ibm.wala.types.MethodReference; import com.ibm.wala.types.TypeReference; import com.ibm.wala.util.CancelException; import java.io.IOException; import java.util.Collection; import org.junit.Assert; import org.junit.Test; /** Check properties of a call to clone() in RTA */ public class DefaultMethodsTest extends WalaTestCase { @Test public void testDefaultMethods() throws ClassHierarchyException, IllegalArgumentException, CancelException, IOException { AnalysisScope scope = CallGraphTestUtil.makeJ2SEAnalysisScope( TestConstants.WALA_TESTDATA, CallGraphTestUtil.REGRESSION_EXCLUSIONS); ClassHierarchy cha = ClassHierarchyFactory.make(scope); Iterable<Entrypoint> entrypoints = com.ibm.wala.ipa.callgraph.impl.Util.makeMainEntrypoints( cha, "LdefaultMethods/DefaultMethods"); AnalysisOptions options = CallGraphTestUtil.makeAnalysisOptions(scope, entrypoints); CallGraph cg = CallGraphTestUtil.buildZeroCFA(options, new AnalysisCacheImpl(), cha, false); // Find node corresponding to main TypeReference tm = TypeReference.findOrCreate( ClassLoaderReference.Application, "LdefaultMethods/DefaultMethods"); MethodReference mm = MethodReference.findOrCreate(tm, "main", "([Ljava/lang/String;)V"); Assert.assertTrue("expect main node", cg.getNodes(mm).iterator().hasNext()); CGNode mnode = cg.getNodes(mm).iterator().next(); // Find node corresponding to Interface1.silly TypeReference t1s = TypeReference.findOrCreate(ClassLoaderReference.Application, "LdefaultMethods/Interface1"); MethodReference t1m = MethodReference.findOrCreate(t1s, "silly", "()I"); Assert.assertTrue("expect Interface1.silly node", cg.getNodes(t1m).iterator().hasNext()); CGNode t1node = cg.getNodes(t1m).iterator().next(); // Check call from main to Interface1.silly Assert.assertTrue( "should have call site from main to Interface1.silly", cg.getPossibleSites(mnode, t1node).hasNext()); // Find node corresponding to Interface2.silly TypeReference t2s = TypeReference.findOrCreate(ClassLoaderReference.Application, "LdefaultMethods/Interface2"); MethodReference t2m = MethodReference.findOrCreate(t2s, "silly", "()I"); Assert.assertTrue("expect Interface2.silly node", cg.getNodes(t2m).iterator().hasNext()); CGNode t2node = cg.getNodes(t1m).iterator().next(); // Check call from main to Interface2.silly Assert.assertTrue( "should have call site from main to Interface2.silly", cg.getPossibleSites(mnode, t2node).hasNext()); // Find node corresponding to Test.silly TypeReference tts = TypeReference.findOrCreate( ClassLoaderReference.Application, "LdefaultMethods/DefaultMethods$Test3"); MethodReference ttm = MethodReference.findOrCreate(tts, "silly", "()I"); Assert.assertTrue("expect Interface1.silly node", cg.getNodes(ttm).iterator().hasNext()); CGNode ttnode = cg.getNodes(ttm).iterator().next(); // Check call from main to Test3.silly Assert.assertTrue( "should have call site from main to Test3.silly", cg.getPossibleSites(mnode, ttnode).hasNext()); // Check that IClass.getAllMethods() returns default methods #219. TypeReference test1Type = TypeReference.findOrCreate( ClassLoaderReference.Application, "LdefaultMethods/DefaultMethods$Test1"); IClass test1Class = cha.lookupClass(test1Type); Collection<? extends IMethod> allMethods = test1Class.getAllMethods(); IMethod defaultMethod = test1Class.getMethod(t1m.getSelector()); Assert.assertTrue( "Expecting default methods to show up in IClass.allMethods()", allMethods.contains(defaultMethod)); } }
4,878
42.954955
99
java
WALA
WALA-master/core/src/test/java/com/ibm/wala/core/tests/callGraph/FinalizerTest.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.callGraph; import com.ibm.wala.core.tests.util.TestConstants; import com.ibm.wala.core.tests.util.WalaTestCase; import com.ibm.wala.ipa.callgraph.AnalysisCacheImpl; import com.ibm.wala.ipa.callgraph.AnalysisOptions; import com.ibm.wala.ipa.callgraph.AnalysisScope; import com.ibm.wala.ipa.callgraph.CGNode; import com.ibm.wala.ipa.callgraph.CallGraph; import com.ibm.wala.ipa.callgraph.Entrypoint; import com.ibm.wala.ipa.cha.ClassHierarchy; import com.ibm.wala.ipa.cha.ClassHierarchyException; import com.ibm.wala.ipa.cha.ClassHierarchyFactory; import com.ibm.wala.types.ClassLoaderReference; import com.ibm.wala.types.MethodReference; import com.ibm.wala.types.TypeReference; import com.ibm.wala.util.CancelException; import java.io.IOException; import org.junit.Assert; import org.junit.Test; /** Check properties of a call to clone() in RTA */ public class FinalizerTest extends WalaTestCase { @Test public void testFinalize() throws ClassHierarchyException, IllegalArgumentException, CancelException, IOException { AnalysisScope scope = CallGraphTestUtil.makeJ2SEAnalysisScope( TestConstants.WALA_TESTDATA, CallGraphTestUtil.REGRESSION_EXCLUSIONS); ClassHierarchy cha = ClassHierarchyFactory.make(scope); Iterable<Entrypoint> entrypoints = com.ibm.wala.ipa.callgraph.impl.Util.makeMainEntrypoints(cha, "Lfinalizers/Finalizers"); AnalysisOptions options = CallGraphTestUtil.makeAnalysisOptions(scope, entrypoints); CallGraph cg = CallGraphTestUtil.buildZeroCFA(options, new AnalysisCacheImpl(), cha, false); // Find node corresponding to finalize TypeReference t = TypeReference.findOrCreate(ClassLoaderReference.Application, "Lfinalizers/Finalizers"); MethodReference m = MethodReference.findOrCreate(t, "finalize", "()V"); Assert.assertTrue("expect finalizer node", cg.getNodes(m).iterator().hasNext()); CGNode node = cg.getNodes(m).iterator().next(); // Check it's reachable from root Assert.assertTrue( "should have call site from root", cg.getPossibleSites(cg.getFakeRootNode(), node).hasNext()); } }
2,529
39.806452
96
java
WALA
WALA-master/core/src/test/java/com/ibm/wala/core/tests/callGraph/Java7CallGraphTest.java
/* * Copyright (c) 2002 - 2014 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package com.ibm.wala.core.tests.callGraph; import static org.junit.Assume.assumeFalse; import com.ibm.wala.analysis.reflection.java7.MethodHandles; import com.ibm.wala.classLoader.Language; import com.ibm.wala.core.tests.shrike.DynamicCallGraphTestBase; import com.ibm.wala.ipa.callgraph.AnalysisCacheImpl; import com.ibm.wala.ipa.callgraph.AnalysisOptions; import com.ibm.wala.ipa.callgraph.AnalysisScope; import com.ibm.wala.ipa.callgraph.CallGraph; import com.ibm.wala.ipa.callgraph.Entrypoint; import com.ibm.wala.ipa.callgraph.IAnalysisCacheView; import com.ibm.wala.ipa.callgraph.impl.Util; import com.ibm.wala.ipa.callgraph.propagation.SSAPropagationCallGraphBuilder; import com.ibm.wala.ipa.cha.ClassHierarchy; import com.ibm.wala.ipa.cha.ClassHierarchyException; import com.ibm.wala.ipa.cha.ClassHierarchyFactory; import com.ibm.wala.shrike.shrikeBT.analysis.Analyzer.FailureException; import com.ibm.wala.shrike.shrikeCT.InvalidClassFileException; import com.ibm.wala.types.ClassLoaderReference; import com.ibm.wala.util.CancelException; import com.ibm.wala.util.PlatformUtil; import com.ibm.wala.util.io.TemporaryFile; import java.io.File; import java.io.IOException; import java.util.jar.JarFile; import org.junit.Test; public class Java7CallGraphTest extends DynamicCallGraphTestBase { @Test public void testOcamlHelloHash() throws ClassHierarchyException, IllegalArgumentException, CancelException, IOException, ClassNotFoundException, InvalidClassFileException, FailureException, SecurityException, InterruptedException { // Known to be broken on Windows, but not intentionally so. Please fix if you know how! // <https://github.com/wala/WALA/issues/608> assumeFalse(PlatformUtil.onWindows()); if (!"True".equals(System.getenv("APPVEYOR"))) { testOCamlJar("hello_hash.jar"); } } private void testOCamlJar(String jarFile, String... args) throws ClassHierarchyException, IllegalArgumentException, CancelException, IOException, ClassNotFoundException, InvalidClassFileException, FailureException, SecurityException, InterruptedException { File F = TemporaryFile.urlToFile( jarFile.replace('.', '_') + ".jar", getClass().getClassLoader().getResource(jarFile)); F.deleteOnExit(); AnalysisScope scope = CallGraphTestUtil.makeJ2SEAnalysisScope( "base.txt", CallGraphTestUtil.REGRESSION_EXCLUSIONS); scope.addToScope(ClassLoaderReference.Application, new JarFile(F, false)); ClassHierarchy cha = ClassHierarchyFactory.make(scope); Iterable<Entrypoint> entrypoints = com.ibm.wala.ipa.callgraph.impl.Util.makeMainEntrypoints(cha, "Lpack/ocamljavaMain"); AnalysisOptions options = CallGraphTestUtil.makeAnalysisOptions(scope, entrypoints); options.setUseConstantSpecificKeys(true); IAnalysisCacheView cache = new AnalysisCacheImpl(); SSAPropagationCallGraphBuilder builder = Util.makeZeroCFABuilder(Language.JAVA, options, cache, cha); MethodHandles.analyzeMethodHandles(options, builder); CallGraph cg = builder.makeCallGraph(options, null); System.err.println(cg); instrument(F.getAbsolutePath()); run("pack.ocamljavaMain", null, args); checkNodes( cg, t -> { String s = t.toString(); return s.contains("Lpack/") || s.contains("Locaml/stdlib/"); }); } }
3,803
37.816327
98
java
WALA
WALA-master/core/src/test/java/com/ibm/wala/core/tests/callGraph/KawaCallGraphTest.java
/* * Copyright (c) 2002 - 2014 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package com.ibm.wala.core.tests.callGraph; import com.ibm.wala.analysis.reflection.java7.MethodHandles; import com.ibm.wala.classLoader.Language; import com.ibm.wala.classLoader.Module; import com.ibm.wala.classLoader.ResourceJarFileModule; import com.ibm.wala.core.tests.shrike.DynamicCallGraphTestBase; import com.ibm.wala.core.util.CancelRuntimeException; import com.ibm.wala.core.util.strings.Atom; import com.ibm.wala.ipa.callgraph.AnalysisCacheImpl; import com.ibm.wala.ipa.callgraph.AnalysisOptions; import com.ibm.wala.ipa.callgraph.AnalysisOptions.ReflectionOptions; import com.ibm.wala.ipa.callgraph.AnalysisScope; import com.ibm.wala.ipa.callgraph.CGNode; import com.ibm.wala.ipa.callgraph.CallGraph; import com.ibm.wala.ipa.callgraph.CallGraphBuilderCancelException; import com.ibm.wala.ipa.callgraph.Entrypoint; import com.ibm.wala.ipa.callgraph.IAnalysisCacheView; import com.ibm.wala.ipa.callgraph.impl.Util; import com.ibm.wala.ipa.callgraph.propagation.SSAPropagationCallGraphBuilder; import com.ibm.wala.ipa.cha.ClassHierarchy; import com.ibm.wala.ipa.cha.ClassHierarchyException; import com.ibm.wala.ipa.cha.ClassHierarchyFactory; import com.ibm.wala.tests.util.SlowTests; import com.ibm.wala.types.ClassLoaderReference; import com.ibm.wala.types.Descriptor; import com.ibm.wala.types.MethodReference; import com.ibm.wala.types.TypeReference; import com.ibm.wala.util.MonitorUtil.IProgressMonitor; import java.io.IOException; import java.util.Set; import org.junit.Test; import org.junit.experimental.categories.Category; @Category(SlowTests.class) public class KawaCallGraphTest extends DynamicCallGraphTestBase { @Test public void testKawaChess() throws ClassHierarchyException, IllegalArgumentException, IOException, SecurityException { CallGraph CG = testKawa( new ResourceJarFileModule(getClass().getClassLoader().getResource("kawachess.jar")), "baseAndDesktop.txt", "main"); Set<CGNode> status = getNodes( CG, "Lchess", "startingStatus", "(Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;"); assert !status.isEmpty(); Set<CGNode> color = getNodes( CG, "Lchess", "startingColor", "(Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;"); assert !color.isEmpty(); Set<CGNode> loadImage = getNodes( CG, "Limg", "loadImage", "(Ljava/lang/CharSequence;)Ljava/awt/image/BufferedImage;"); assert !loadImage.isEmpty(); Set<CGNode> append$v = getNodes(CG, "Lkawa/lang/Quote", "append$V", "([Ljava/lang/Object;)Ljava/lang/Object;"); assert !append$v.isEmpty(); Set<CGNode> clinit = getNodes(CG, "Lkawa/lib/kawa/base", "<clinit>", "()V"); assert !clinit.isEmpty(); } @Test public void testKawaTest() throws ClassHierarchyException, IllegalArgumentException, IOException, SecurityException { CallGraph CG = testKawa( new ResourceJarFileModule(getClass().getClassLoader().getResource("kawatest.jar")), "base.txt", "test"); Set<CGNode> nodes = getNodes(CG, "Ltest", "plusish$V", "(Lgnu/lists/LList;)Ljava/lang/Object;"); assert !nodes.isEmpty(); } private static Set<CGNode> getNodes(CallGraph CG, String cls, String method, String descr) { Set<CGNode> nodes = CG.getNodes( MethodReference.findOrCreate( TypeReference.find(ClassLoaderReference.Application, cls), Atom.findOrCreateUnicodeAtom(method), Descriptor.findOrCreateUTF8(descr))); return nodes; } /** Maximum number of outer fixed point iterations to use when building the Kawa call graph. */ private static final int MAX_ITERATIONS = 6; /** * Builds a call graph for a Kawa module. Call graph construction is terminated after {@link * #MAX_ITERATIONS} runs of the outer fixed point loop of call graph construction. * * @param code the module * @param scopeFile the scope file to use * @param main entrypoint method for the call graph * @return the call graph */ private CallGraph testKawa(Module code, String scopeFile, String main) throws ClassHierarchyException, IllegalArgumentException, IOException, SecurityException { AnalysisScope scope = CallGraphTestUtil.makeJ2SEAnalysisScope( scopeFile, CallGraphTestUtil.REGRESSION_EXCLUSIONS_FOR_GUI); scope.addToScope( ClassLoaderReference.Application, new ResourceJarFileModule(getClass().getClassLoader().getResource("kawa.jar"))); scope.addToScope(ClassLoaderReference.Application, code); ClassHierarchy cha = ClassHierarchyFactory.make(scope); Iterable<Entrypoint> entrypoints = com.ibm.wala.ipa.callgraph.impl.Util.makeMainEntrypoints(cha, 'L' + main); AnalysisOptions options = CallGraphTestUtil.makeAnalysisOptions(scope, entrypoints); IAnalysisCacheView cache = new AnalysisCacheImpl(); options.setReflectionOptions(ReflectionOptions.STRING_ONLY); options.setTraceStringConstants(true); options.setUseConstantSpecificKeys(true); SSAPropagationCallGraphBuilder builder = Util.makeZeroCFABuilder(Language.JAVA, options, cache, cha); MethodHandles.analyzeMethodHandles(options, builder); CallGraph cg; try { cg = builder.makeCallGraph( options, new IProgressMonitor() { private long time = System.currentTimeMillis(); private int iterations = 0; @Override public void beginTask(String task, int totalWork) { noteElapsedTime(); } private void noteElapsedTime() { long now = System.currentTimeMillis(); if (now - time >= 10000) { System.out.println("worked " + (now - time)); System.out.flush(); time = now; } } @Override public void subTask(String subTask) { noteElapsedTime(); } @Override public void cancel() { assert false; } @Override public boolean isCanceled() { return false; } @Override public void done() { noteElapsedTime(); } @Override public void worked(int units) { noteElapsedTime(); iterations++; if (iterations >= MAX_ITERATIONS) { throw CancelRuntimeException.make("should have run long enough"); } } @Override public String getCancelMessage() { assert false : "should not cancel"; return null; } }); } catch (CallGraphBuilderCancelException cgbe) { cg = cgbe.getPartialCallGraph(); } return cg; } }
7,596
34.666667
100
java
WALA
WALA-master/core/src/test/java/com/ibm/wala/core/tests/callGraph/LambdaTest.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.callGraph; import com.ibm.wala.classLoader.CallSiteReference; import com.ibm.wala.core.tests.util.TestConstants; import com.ibm.wala.core.tests.util.WalaTestCase; import com.ibm.wala.core.util.strings.Atom; import com.ibm.wala.ipa.callgraph.AnalysisCacheImpl; import com.ibm.wala.ipa.callgraph.AnalysisOptions; import com.ibm.wala.ipa.callgraph.AnalysisScope; import com.ibm.wala.ipa.callgraph.CGNode; import com.ibm.wala.ipa.callgraph.CallGraph; import com.ibm.wala.ipa.callgraph.Entrypoint; import com.ibm.wala.ipa.cha.ClassHierarchy; import com.ibm.wala.ipa.cha.ClassHierarchyException; import com.ibm.wala.ipa.cha.ClassHierarchyFactory; import com.ibm.wala.types.ClassLoaderReference; import com.ibm.wala.types.Descriptor; import com.ibm.wala.types.MethodReference; import com.ibm.wala.types.TypeReference; import com.ibm.wala.util.CancelException; import com.ibm.wala.util.collections.Iterator2Collection; import com.ibm.wala.util.collections.Iterator2Iterable; import java.io.IOException; import java.util.List; import java.util.Set; import java.util.function.Consumer; import java.util.function.Function; import org.junit.Assert; import org.junit.Test; /** Check properties of a call to clone() in RTA */ public class LambdaTest extends WalaTestCase { @Test public void testBug144() throws IOException, ClassHierarchyException, IllegalArgumentException, CancelException { AnalysisScope scope = CallGraphTestUtil.makeJ2SEAnalysisScope( TestConstants.WALA_TESTDATA, CallGraphTestUtil.REGRESSION_EXCLUSIONS); ClassHierarchy cha = ClassHierarchyFactory.make(scope); Iterable<Entrypoint> entrypoints = com.ibm.wala.ipa.callgraph.impl.Util.makeMainEntrypoints(cha, "Lbug144/A"); AnalysisOptions options = CallGraphTestUtil.makeAnalysisOptions(scope, entrypoints); @SuppressWarnings("unused") CallGraph cg = CallGraphTestUtil.buildZeroCFA(options, new AnalysisCacheImpl(), cha, false); } @Test public void testBug137() throws IOException, ClassHierarchyException, IllegalArgumentException, CancelException { AnalysisScope scope = CallGraphTestUtil.makeJ2SEAnalysisScope( TestConstants.WALA_TESTDATA, CallGraphTestUtil.REGRESSION_EXCLUSIONS); ClassHierarchy cha = ClassHierarchyFactory.make(scope); Iterable<Entrypoint> entrypoints = com.ibm.wala.ipa.callgraph.impl.Util.makeMainEntrypoints(cha, "Lspecial/A"); AnalysisOptions options = CallGraphTestUtil.makeAnalysisOptions(scope, entrypoints); CallGraph cg = CallGraphTestUtil.buildZeroCFA(options, new AnalysisCacheImpl(), cha, false); TypeReference A = TypeReference.findOrCreate(ClassLoaderReference.Application, "Lspecial/A"); MethodReference ct = MethodReference.findOrCreate( A, Atom.findOrCreateUnicodeAtom("<init>"), Descriptor.findOrCreateUTF8("()V")); Set<CGNode> ctnodes = cg.getNodes(ct); Assert.assertEquals(1, ctnodes.size()); MethodReference ts = MethodReference.findOrCreate( A, Atom.findOrCreateUnicodeAtom("toString"), Descriptor.findOrCreateUTF8("()Ljava/lang/String;")); Set<CGNode> tsnodes = cg.getNodes(ts); Assert.assertEquals(1, tsnodes.size()); } @Test public void testSortingExample() throws ClassHierarchyException, IllegalArgumentException, CancelException, IOException { AnalysisScope scope = CallGraphTestUtil.makeJ2SEAnalysisScope( TestConstants.WALA_TESTDATA, CallGraphTestUtil.REGRESSION_EXCLUSIONS); ClassHierarchy cha = ClassHierarchyFactory.make(scope); Iterable<Entrypoint> entrypoints = com.ibm.wala.ipa.callgraph.impl.Util.makeMainEntrypoints(cha, "Llambda/SortingExample"); AnalysisOptions options = CallGraphTestUtil.makeAnalysisOptions(scope, entrypoints); CallGraph cg = CallGraphTestUtil.buildZeroCFA(options, new AnalysisCacheImpl(), cha, false); // Find compareTo TypeReference str = TypeReference.findOrCreate(ClassLoaderReference.Primordial, "Ljava/lang/String"); MethodReference ct = MethodReference.findOrCreate( str, Atom.findOrCreateUnicodeAtom("compareTo"), Descriptor.findOrCreateUTF8("(Ljava/lang/String;)I")); Set<CGNode> ctnodes = cg.getNodes(ct); checkCompareToCalls(cg, ctnodes, "id1", 1); checkCompareToCalls(cg, ctnodes, "id2", 1); checkCompareToCalls(cg, ctnodes, "id3", 2); checkCompareToCalls(cg, ctnodes, "id4", 1); } protected void checkCompareToCalls(CallGraph cg, Set<CGNode> ctnodes, String x, int expected) { // Find node corresponding to id1 TypeReference tid1 = TypeReference.findOrCreate(ClassLoaderReference.Application, "Llambda/SortingExample"); MethodReference mid1 = MethodReference.findOrCreate(tid1, x, "(I)I"); Assert.assertTrue("expect " + x + " node", cg.getNodes(mid1).iterator().hasNext()); CGNode id1node = cg.getNodes(mid1).iterator().next(); // caller of id1 is dynamic from sortForward, and has 1 compareTo CGNode sfnode = cg.getPredNodes(id1node).next(); int count = 0; for (CallSiteReference site : Iterator2Iterable.make(sfnode.iterateCallSites())) { if (ctnodes.containsAll(cg.getPossibleTargets(sfnode, site))) { count++; } } Assert.assertEquals("expected one call to compareTo", expected, count); System.err.println("found " + count + " compareTo calls in " + sfnode); } @Test public void testMethodRefs() throws ClassHierarchyException, IllegalArgumentException, CancelException, IOException { AnalysisScope scope = CallGraphTestUtil.makeJ2SEAnalysisScope( TestConstants.WALA_TESTDATA, CallGraphTestUtil.REGRESSION_EXCLUSIONS); ClassHierarchy cha = ClassHierarchyFactory.make(scope); Iterable<Entrypoint> entrypoints = com.ibm.wala.ipa.callgraph.impl.Util.makeMainEntrypoints(cha, "Llambda/MethodRefs"); AnalysisOptions options = CallGraphTestUtil.makeAnalysisOptions(scope, entrypoints); CallGraph cg = CallGraphTestUtil.buildZeroCFA(options, new AnalysisCacheImpl(), cha, false); Function<String, MethodReference> getTargetRef = (klass) -> MethodReference.findOrCreate( TypeReference.findOrCreate( ClassLoaderReference.Application, "Llambda/MethodRefs$" + klass), Atom.findOrCreateUnicodeAtom("target"), Descriptor.findOrCreateUTF8("()V")); System.out.println(cg); Assert.assertEquals( "expected C1.target() to be reachable", 1, cg.getNodes(getTargetRef.apply("C1")).size()); Assert.assertEquals( "expected C2.target() to be reachable", 1, cg.getNodes(getTargetRef.apply("C2")).size()); Assert.assertEquals( "expected C3.target() to be reachable", 1, cg.getNodes(getTargetRef.apply("C3")).size()); Assert.assertEquals( "expected C4.target() to be reachable", 1, cg.getNodes(getTargetRef.apply("C4")).size()); Assert.assertEquals( "expected C5.target() to *not* be reachable", 0, cg.getNodes(getTargetRef.apply("C5")).size()); } @Test public void testParamsAndCapture() throws ClassHierarchyException, IllegalArgumentException, CancelException, IOException { AnalysisScope scope = CallGraphTestUtil.makeJ2SEAnalysisScope( TestConstants.WALA_TESTDATA, CallGraphTestUtil.REGRESSION_EXCLUSIONS); ClassHierarchy cha = ClassHierarchyFactory.make(scope); Iterable<Entrypoint> entrypoints = com.ibm.wala.ipa.callgraph.impl.Util.makeMainEntrypoints(cha, "Llambda/ParamsAndCapture"); AnalysisOptions options = CallGraphTestUtil.makeAnalysisOptions(scope, entrypoints); CallGraph cg = CallGraphTestUtil.buildZeroCFA(options, new AnalysisCacheImpl(), cha, false); Function<String, MethodReference> getTargetRef = (klass) -> MethodReference.findOrCreate( TypeReference.findOrCreate( ClassLoaderReference.Application, "Llambda/ParamsAndCapture$" + klass), Atom.findOrCreateUnicodeAtom("target"), Descriptor.findOrCreateUTF8("()V")); System.out.println(cg); Consumer<String> checkCalledFromOneSite = (klassName) -> { Set<CGNode> nodes = cg.getNodes(getTargetRef.apply(klassName)); Assert.assertEquals( "expected " + klassName + ".target() to be reachable", 1, nodes.size()); CGNode node = nodes.iterator().next(); List<CGNode> predNodes = Iterator2Collection.toList(cg.getPredNodes(node)); Assert.assertEquals( "expected " + klassName + ".target() to be invoked from one calling method", 1, predNodes.size()); CGNode pred = predNodes.get(0); List<CallSiteReference> sites = Iterator2Collection.toList(cg.getPossibleSites(pred, node)); Assert.assertEquals( "expected " + klassName + ".target() to be invoked from one call site", 1, sites.size()); }; checkCalledFromOneSite.accept("C1"); checkCalledFromOneSite.accept("C2"); checkCalledFromOneSite.accept("C3"); checkCalledFromOneSite.accept("C4"); checkCalledFromOneSite.accept("C5"); } @Test public void testLambaMetafactoryCall() throws ClassHierarchyException, IllegalArgumentException, CancelException, IOException { AnalysisScope scope = CallGraphTestUtil.makeJ2SEAnalysisScope( TestConstants.WALA_TESTDATA, CallGraphTestUtil.REGRESSION_EXCLUSIONS); ClassHierarchy cha = ClassHierarchyFactory.make(scope); Iterable<Entrypoint> entrypoints = com.ibm.wala.ipa.callgraph.impl.Util.makeMainEntrypoints(cha, "Llambda/CallMetaFactory"); AnalysisOptions options = CallGraphTestUtil.makeAnalysisOptions(scope, entrypoints); // shouldn't crash CallGraph cg = CallGraphTestUtil.buildZeroCFA(options, new AnalysisCacheImpl(), cha, false); // exceedingly unlikely to fail, but ensures that optimizer won't remove buildZeroCFA call Assert.assertTrue(cg.getNumberOfNodes() > 0); } }
10,619
42.52459
98
java
WALA
WALA-master/core/src/test/java/com/ibm/wala/core/tests/callGraph/LibModelsTest.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.callGraph; import com.ibm.wala.core.tests.util.TestConstants; import com.ibm.wala.core.tests.util.WalaTestCase; import com.ibm.wala.ipa.callgraph.AnalysisCacheImpl; import com.ibm.wala.ipa.callgraph.AnalysisOptions; import com.ibm.wala.ipa.callgraph.AnalysisScope; import com.ibm.wala.ipa.callgraph.CallGraph; import com.ibm.wala.ipa.callgraph.Entrypoint; import com.ibm.wala.ipa.cha.ClassHierarchy; import com.ibm.wala.ipa.cha.ClassHierarchyException; import com.ibm.wala.ipa.cha.ClassHierarchyFactory; import com.ibm.wala.types.ClassLoaderReference; import com.ibm.wala.types.MethodReference; import com.ibm.wala.types.TypeReference; import com.ibm.wala.util.CancelException; import java.io.IOException; import org.junit.Assert; import org.junit.Test; /** Check properties of a call to clone() in RTA */ public class LibModelsTest extends WalaTestCase { @Test public void testLibModels() throws ClassHierarchyException, IllegalArgumentException, CancelException, IOException { AnalysisScope scope = CallGraphTestUtil.makeJ2SEAnalysisScope( TestConstants.WALA_TESTDATA, CallGraphTestUtil.REGRESSION_EXCLUSIONS); ClassHierarchy cha = ClassHierarchyFactory.make(scope); String libModelsTestClass = "Llibmodels/LibModels"; Iterable<Entrypoint> entrypoints = com.ibm.wala.ipa.callgraph.impl.Util.makeMainEntrypoints(cha, libModelsTestClass); AnalysisOptions options = CallGraphTestUtil.makeAnalysisOptions(scope, entrypoints); CallGraph cg = CallGraphTestUtil.buildZeroCFA(options, new AnalysisCacheImpl(), cha, false); // System.err.println(cg); // Find node corresponding to finalize TypeReference t = TypeReference.findOrCreate(ClassLoaderReference.Application, libModelsTestClass); MethodReference m = MethodReference.findOrCreate(t, "reachable1", "()V"); Assert.assertTrue( "expect reachable1 from addShutdownHook", cg.getNodes(m).iterator().hasNext()); MethodReference m2 = MethodReference.findOrCreate(t, "reachable2", "()V"); Assert.assertTrue( "expect reachable2 from uncaught exception handler", cg.getNodes(m2).iterator().hasNext()); } }
2,569
40.451613
99
java
WALA
WALA-master/core/src/test/java/com/ibm/wala/core/tests/callGraph/PiNodeCallGraphTest.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.callGraph; import com.ibm.wala.classLoader.CallSiteReference; import com.ibm.wala.core.tests.util.TestConstants; import com.ibm.wala.core.tests.util.WalaTestCase; import com.ibm.wala.core.util.strings.Atom; import com.ibm.wala.ipa.callgraph.AnalysisCacheImpl; import com.ibm.wala.ipa.callgraph.AnalysisOptions; import com.ibm.wala.ipa.callgraph.AnalysisScope; import com.ibm.wala.ipa.callgraph.CGNode; import com.ibm.wala.ipa.callgraph.CallGraph; import com.ibm.wala.ipa.callgraph.Entrypoint; import com.ibm.wala.ipa.cha.ClassHierarchy; import com.ibm.wala.ipa.cha.ClassHierarchyException; import com.ibm.wala.ipa.cha.ClassHierarchyFactory; import com.ibm.wala.ssa.DefaultIRFactory; import com.ibm.wala.ssa.SSAOptions; import com.ibm.wala.ssa.SSAPiNodePolicy; import com.ibm.wala.types.ClassLoaderReference; import com.ibm.wala.types.Descriptor; import com.ibm.wala.types.MemberReference; import com.ibm.wala.types.MethodReference; import com.ibm.wala.types.TypeName; import com.ibm.wala.types.TypeReference; import com.ibm.wala.util.CancelException; import com.ibm.wala.util.collections.HashSetFactory; import com.ibm.wala.util.collections.Iterator2Iterable; import java.io.IOException; import java.util.Set; import org.junit.Assert; import org.junit.Test; /** */ public class PiNodeCallGraphTest extends WalaTestCase { public static void main(String[] args) { justThisTest(PiNodeCallGraphTest.class); } private static final String whateverName = TestConstants.PI_TEST_MAIN + "$Whatever"; private static final String thisName = TestConstants.PI_TEST_MAIN + "$This"; private static final String thatName = TestConstants.PI_TEST_MAIN + "$That"; private static final ClassLoaderReference loader = ClassLoaderReference.Application; private static final TypeReference whateverRef = TypeReference.findOrCreate(loader, TypeName.string2TypeName(whateverName)); private static final TypeReference thisRef = TypeReference.findOrCreate(loader, TypeName.string2TypeName(thisName)); private static final TypeReference thatRef = TypeReference.findOrCreate(loader, TypeName.string2TypeName(thatName)); private static final MethodReference thisBinaryRef = MethodReference.findOrCreate( thisRef, Atom.findOrCreateUnicodeAtom("binary"), Descriptor.findOrCreateUTF8("(" + whateverName + ";)V")); private static final MethodReference thatBinaryRef = MethodReference.findOrCreate( thatRef, Atom.findOrCreateUnicodeAtom("binary"), Descriptor.findOrCreateUTF8("(" + whateverName + ";)V")); private static final MemberReference unary2Ref = MethodReference.findOrCreate( whateverRef, Atom.findOrCreateUnicodeAtom("unary2"), Descriptor.findOrCreateUTF8("()V")); private static CallGraph doGraph(boolean usePiNodes) throws ClassHierarchyException, IllegalArgumentException, CancelException, IOException { AnalysisScope scope = CallGraphTestUtil.makeJ2SEAnalysisScope( TestConstants.WALA_TESTDATA, CallGraphTestUtil.REGRESSION_EXCLUSIONS); ClassHierarchy cha = ClassHierarchyFactory.make(scope); Iterable<Entrypoint> entrypoints = com.ibm.wala.ipa.callgraph.impl.Util.makeMainEntrypoints(cha, TestConstants.PI_TEST_MAIN); AnalysisOptions options = CallGraphTestUtil.makeAnalysisOptions(scope, entrypoints); SSAPiNodePolicy policy = usePiNodes ? SSAOptions.getAllBuiltInPiNodes() : null; options.getSSAOptions().setPiNodePolicy(policy); return CallGraphTestUtil.buildZeroCFA( options, new AnalysisCacheImpl(new DefaultIRFactory(), options.getSSAOptions()), cha, false); } private static void checkCallAssertions( CallGraph cg, int desiredNumberOfTargets, int desiredNumberOfCalls, int numLocalCastCallees) { int numberOfCalls = 0; Set<CGNode> callerNodes = HashSetFactory.make(); callerNodes.addAll(cg.getNodes(thisBinaryRef)); callerNodes.addAll(cg.getNodes(thatBinaryRef)); assert callerNodes.size() == 2; for (CGNode n : callerNodes) { for (CallSiteReference csRef : Iterator2Iterable.make(n.iterateCallSites())) { if (csRef.getDeclaredTarget().equals(unary2Ref)) { numberOfCalls++; assert cg.getNumberOfTargets(n, csRef) == desiredNumberOfTargets; } } } assert numberOfCalls == desiredNumberOfCalls; CGNode localCastNode = cg.getNodes( MethodReference.findOrCreate( TypeReference.findOrCreate(loader, TestConstants.PI_TEST_MAIN), "localCast", "()V")) .iterator() .next(); int actualLocalCastCallees = cg.getSuccNodeCount(localCastNode); Assert.assertEquals(numLocalCastCallees, actualLocalCastCallees); } @Test public void testNoPiNodes() throws ClassHierarchyException, IllegalArgumentException, CancelException, IOException { checkCallAssertions(doGraph(false), 2, 2, 2); } @Test public void testPiNodes() throws ClassHierarchyException, IllegalArgumentException, CancelException, IOException { checkCallAssertions(doGraph(true), 1, 2, 1); } }
5,618
37.486301
100
java
WALA
WALA-master/core/src/test/java/com/ibm/wala/core/tests/callGraph/ReflectionTest.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.callGraph; import com.ibm.wala.classLoader.IClass; import com.ibm.wala.classLoader.IMethod; import com.ibm.wala.core.tests.util.TestConstants; import com.ibm.wala.core.tests.util.WalaTestCase; import com.ibm.wala.core.util.warnings.Warning; import com.ibm.wala.core.util.warnings.Warnings; import com.ibm.wala.ipa.callgraph.AnalysisCacheImpl; import com.ibm.wala.ipa.callgraph.AnalysisOptions; import com.ibm.wala.ipa.callgraph.AnalysisOptions.ReflectionOptions; import com.ibm.wala.ipa.callgraph.AnalysisScope; import com.ibm.wala.ipa.callgraph.CGNode; import com.ibm.wala.ipa.callgraph.CallGraph; import com.ibm.wala.ipa.callgraph.Context; import com.ibm.wala.ipa.callgraph.ContextKey; import com.ibm.wala.ipa.callgraph.Entrypoint; import com.ibm.wala.ipa.callgraph.impl.Everywhere; import com.ibm.wala.ipa.callgraph.propagation.ConstantKey; import com.ibm.wala.ipa.callgraph.propagation.InstanceKey; import com.ibm.wala.ipa.callgraph.propagation.LocalPointerKey; import com.ibm.wala.ipa.callgraph.propagation.PointerAnalysis; import com.ibm.wala.ipa.callgraph.propagation.ReceiverInstanceContext; 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.types.ClassLoaderReference; import com.ibm.wala.types.MethodReference; import com.ibm.wala.types.Selector; import com.ibm.wala.types.TypeReference; import com.ibm.wala.util.CancelException; import com.ibm.wala.util.WalaException; import com.ibm.wala.util.collections.HashSetFactory; import com.ibm.wala.util.collections.Iterator2Collection; import com.ibm.wala.util.collections.Iterator2Iterable; import com.ibm.wala.util.collections.Pair; import com.ibm.wala.util.intset.OrdinalSet; import java.io.IOException; import java.util.Collection; import java.util.Iterator; import java.util.List; import java.util.Optional; import java.util.Set; import org.junit.AfterClass; import org.junit.Assert; import org.junit.Test; /** Tests for Call Graph construction */ public class ReflectionTest extends WalaTestCase { public static void main(String[] args) { justThisTest(ReflectionTest.class); } private static AnalysisScope cachedScope; private static AnalysisScope findOrCreateAnalysisScope() throws IOException { if (cachedScope == null) { cachedScope = CallGraphTestUtil.makeJ2SEAnalysisScope( TestConstants.WALA_TESTDATA, "Java60RegressionExclusions.txt"); } return cachedScope; } private static IClassHierarchy cachedCHA; private static IClassHierarchy findOrCreateCHA(AnalysisScope scope) throws ClassHierarchyException { if (cachedCHA == null) { cachedCHA = ClassHierarchyFactory.make(scope); } return cachedCHA; } @AfterClass public static void afterClass() { cachedCHA = null; cachedScope = null; } /** test that when analyzing Reflect1.main(), there is no warning about "Integer". */ @Test public void testReflect1() throws WalaException, IllegalArgumentException, CancelException, IOException { AnalysisScope scope = findOrCreateAnalysisScope(); IClassHierarchy cha = findOrCreateCHA(scope); Iterable<Entrypoint> entrypoints = com.ibm.wala.ipa.callgraph.impl.Util.makeMainEntrypoints(cha, TestConstants.REFLECT1_MAIN); AnalysisOptions options = CallGraphTestUtil.makeAnalysisOptions(scope, entrypoints); Warnings.clear(); CallGraphTest.doCallGraphs(options, new AnalysisCacheImpl(), cha); for (Warning w : Iterator2Iterable.make(Warnings.iterator())) { if (w.toString().indexOf("com/ibm/jvm") > 0) { continue; } if (w.toString().contains("Integer")) { Assert.fail(w.toString()); } } } /** * Test that when analyzing reflect2, the call graph includes a node for * java.lang.Integer.<clinit>. This should be forced by the call for * Class.forName("java.lang.Integer"). */ @Test public void testReflect2() throws WalaException, IllegalArgumentException, CancelException, IOException { AnalysisScope scope = findOrCreateAnalysisScope(); IClassHierarchy cha = findOrCreateCHA(scope); Iterable<Entrypoint> entrypoints = com.ibm.wala.ipa.callgraph.impl.Util.makeMainEntrypoints(cha, TestConstants.REFLECT2_MAIN); AnalysisOptions options = CallGraphTestUtil.makeAnalysisOptions(scope, entrypoints); CallGraph cg = CallGraphTestUtil.buildZeroOneCFA(options, new AnalysisCacheImpl(), cha, false); TypeReference tr = TypeReference.findOrCreate(ClassLoaderReference.Application, "Ljava/lang/Integer"); MethodReference mr = MethodReference.findOrCreate(tr, "<clinit>", "()V"); Set<CGNode> nodes = cg.getNodes(mr); Assert.assertFalse(nodes.isEmpty()); } /** * Check that when analyzing Reflect3, the successors of newInstance do not include * reflection/Reflect3$Hash */ @Test public void testReflect3() throws IOException, ClassHierarchyException, IllegalArgumentException, CancelException { AnalysisScope scope = findOrCreateAnalysisScope(); IClassHierarchy cha = findOrCreateCHA(scope); Iterable<Entrypoint> entrypoints = com.ibm.wala.ipa.callgraph.impl.Util.makeMainEntrypoints(cha, TestConstants.REFLECT3_MAIN); AnalysisOptions options = CallGraphTestUtil.makeAnalysisOptions(scope, entrypoints); CallGraph cg = CallGraphTestUtil.buildZeroOneCFA(options, new AnalysisCacheImpl(), cha, false); TypeReference tr = TypeReference.findOrCreate(ClassLoaderReference.Application, "Ljava/lang/Class"); MethodReference mr = MethodReference.findOrCreate(tr, "newInstance", "()Ljava/lang/Object;"); Set<CGNode> newInstanceNodes = cg.getNodes(mr); Set<CGNode> succNodes = HashSetFactory.make(); for (CGNode newInstanceNode : newInstanceNodes) { Iterator<? extends CGNode> succNodesIter = cg.getSuccNodes(newInstanceNode); while (succNodesIter.hasNext()) { succNodes.add(succNodesIter.next()); } } TypeReference extraneousTR = TypeReference.findOrCreate(ClassLoaderReference.Application, "Lreflection/Reflect3$Hash"); IClass hashClass = cha.lookupClass(extraneousTR); assert hashClass != null; MethodReference extraneousMR = MethodReference.findOrCreate(extraneousTR, "<init>", "()V"); Set<CGNode> extraneousNodes = cg.getNodes(extraneousMR); succNodes.retainAll(extraneousNodes); Assert.assertTrue(succNodes.isEmpty()); } /** * Check that when analyzing Reflect4, successors of newInstance() do not include FilePermission * ctor. */ @Test public void testReflect4() throws IOException, ClassHierarchyException, IllegalArgumentException, CancelException { AnalysisScope scope = findOrCreateAnalysisScope(); IClassHierarchy cha = findOrCreateCHA(scope); Iterable<Entrypoint> entrypoints = com.ibm.wala.ipa.callgraph.impl.Util.makeMainEntrypoints(cha, TestConstants.REFLECT4_MAIN); AnalysisOptions options = CallGraphTestUtil.makeAnalysisOptions(scope, entrypoints); CallGraph cg = CallGraphTestUtil.buildZeroOneCFA(options, new AnalysisCacheImpl(), cha, false); TypeReference tr = TypeReference.findOrCreate(ClassLoaderReference.Application, "Ljava/lang/Class"); MethodReference mr = MethodReference.findOrCreate(tr, "newInstance", "()Ljava/lang/Object;"); Set<CGNode> newInstanceNodes = cg.getNodes(mr); Set<CGNode> succNodes = HashSetFactory.make(); for (CGNode newInstanceNode : newInstanceNodes) { Iterator<? extends CGNode> succNodesIter = cg.getSuccNodes(newInstanceNode); while (succNodesIter.hasNext()) { succNodes.add(succNodesIter.next()); } } TypeReference extraneousTR = TypeReference.findOrCreate(ClassLoaderReference.Application, "Ljava/io/FilePermission"); MethodReference extraneousMR = MethodReference.findOrCreate( extraneousTR, "<init>", "(Ljava/lang/String;Ljava/lang/String;)V"); Set<CGNode> extraneousNodes = cg.getNodes(extraneousMR); succNodes.retainAll(extraneousNodes); Assert.assertTrue(succNodes.isEmpty()); } /** * Check that when analyzing Reflect5, successors of newInstance do not include a Reflect5$A ctor */ @Test public void testReflect5() throws IOException, ClassHierarchyException, IllegalArgumentException, CancelException { AnalysisScope scope = findOrCreateAnalysisScope(); IClassHierarchy cha = findOrCreateCHA(scope); Iterable<Entrypoint> entrypoints = com.ibm.wala.ipa.callgraph.impl.Util.makeMainEntrypoints(cha, TestConstants.REFLECT5_MAIN); AnalysisOptions options = CallGraphTestUtil.makeAnalysisOptions(scope, entrypoints); CallGraph cg = CallGraphTestUtil.buildZeroOneCFA(options, new AnalysisCacheImpl(), cha, false); TypeReference tr = TypeReference.findOrCreate(ClassLoaderReference.Application, "Ljava/lang/Class"); MethodReference mr = MethodReference.findOrCreate(tr, "newInstance", "()Ljava/lang/Object;"); Set<CGNode> newInstanceNodes = cg.getNodes(mr); Set<CGNode> succNodes = HashSetFactory.make(); for (CGNode newInstanceNode : newInstanceNodes) { Iterator<? extends CGNode> succNodesIter = cg.getSuccNodes(newInstanceNode); while (succNodesIter.hasNext()) { succNodes.add(succNodesIter.next()); } } TypeReference extraneousTR = TypeReference.findOrCreate(ClassLoaderReference.Application, "Lreflection/Reflect5$A"); MethodReference extraneousMR = MethodReference.findOrCreate(extraneousTR, "<init>", "()V"); Set<CGNode> extraneousNodes = cg.getNodes(extraneousMR); succNodes.retainAll(extraneousNodes); Assert.assertTrue(succNodes.isEmpty()); } /** * Check that when analyzing Reflect6, successors of newInstance do not include a Reflect6$A ctor */ @Test public void testReflect6() throws IOException, ClassHierarchyException, IllegalArgumentException, CancelException { AnalysisScope scope = findOrCreateAnalysisScope(); IClassHierarchy cha = findOrCreateCHA(scope); Iterable<Entrypoint> entrypoints = com.ibm.wala.ipa.callgraph.impl.Util.makeMainEntrypoints(cha, TestConstants.REFLECT6_MAIN); AnalysisOptions options = CallGraphTestUtil.makeAnalysisOptions(scope, entrypoints); CallGraph cg = CallGraphTestUtil.buildZeroOneCFA(options, new AnalysisCacheImpl(), cha, false); TypeReference tr = TypeReference.findOrCreate(ClassLoaderReference.Application, "Ljava/lang/Class"); MethodReference mr = MethodReference.findOrCreate(tr, "newInstance", "()Ljava/lang/Object;"); Set<CGNode> newInstanceNodes = cg.getNodes(mr); Set<CGNode> succNodes = HashSetFactory.make(); for (CGNode newInstanceNode : newInstanceNodes) { Iterator<? extends CGNode> succNodesIter = cg.getSuccNodes(newInstanceNode); while (succNodesIter.hasNext()) { succNodes.add(succNodesIter.next()); } } TypeReference extraneousTR = TypeReference.findOrCreate(ClassLoaderReference.Application, "Lreflection/Reflect6$A"); MethodReference extraneousMR = MethodReference.findOrCreate(extraneousTR, "<init>", "(I)V"); Set<CGNode> extraneousNodes = cg.getNodes(extraneousMR); succNodes.retainAll(extraneousNodes); Assert.assertTrue(succNodes.isEmpty()); } @Test public void testReflect7() throws Exception { AnalysisScope scope = findOrCreateAnalysisScope(); IClassHierarchy cha = findOrCreateCHA(scope); Iterable<Entrypoint> entrypoints = com.ibm.wala.ipa.callgraph.impl.Util.makeMainEntrypoints(cha, TestConstants.REFLECT7_MAIN); AnalysisOptions options = CallGraphTestUtil.makeAnalysisOptions(scope, entrypoints); CallGraph cg = CallGraphTestUtil.buildZeroOneCFA(options, new AnalysisCacheImpl(), cha, false); final String mainClass = "Lreflection/Reflect7"; TypeReference mainTr = TypeReference.findOrCreate(ClassLoaderReference.Application, mainClass); MethodReference mainMr = MethodReference.findOrCreate(mainTr, "main", "([Ljava/lang/String;)V"); TypeReference constrTr = TypeReference.findOrCreate( ClassLoaderReference.Primordial, "Ljava/lang/reflect/Constructor"); MethodReference newInstanceMr = MethodReference.findOrCreate( constrTr, "newInstance", "([Ljava/lang/Object;)Ljava/lang/Object;"); String fpInitSig = "java.io.FilePermission.<init>(Ljava/lang/String;Ljava/lang/String;)V"; String fpToStringSig = "java.security.Permission.toString()Ljava/lang/String;"; Set<CGNode> mainNodes = cg.getNodes(mainMr); // Get all the children of the main node(s) Collection<CGNode> mainChildren = getSuccNodes(cg, mainNodes); // Verify that one of those children is Constructor.newInstance, where // Constructor is a FilePermission constructor CGNode filePermConstrNewInstanceNode = null; for (CGNode node : mainChildren) { Context context = node.getContext(); if (context.isA(ReceiverInstanceContext.class) && node.getMethod().getReference().equals(newInstanceMr)) { @SuppressWarnings("unchecked") ConstantKey<IMethod> c = (ConstantKey<IMethod>) context.get(ContextKey.RECEIVER); IMethod ctor = c.getValue(); if (ctor.getSignature().equals(fpInitSig)) { filePermConstrNewInstanceNode = node; break; } } } Assert.assertNotNull(filePermConstrNewInstanceNode); // Now verify that this node has FilePermission.<init> children CGNode filePermInitNode = null; Iterator<? extends CGNode> filePermConstrNewInstanceChildren = cg.getSuccNodes(filePermConstrNewInstanceNode); while (filePermConstrNewInstanceChildren.hasNext()) { CGNode node = filePermConstrNewInstanceChildren.next(); if (node.getMethod().getSignature().equals(fpInitSig)) { filePermInitNode = node; break; } } Assert.assertNotNull(filePermInitNode); // Furthermore, verify that main has a FilePermission.toString child CGNode filePermToStringNode = null; for (CGNode node : mainChildren) { if (node.getMethod().getSignature().equals(fpToStringSig)) { filePermToStringNode = node; break; } } Assert.assertNotNull(filePermToStringNode); } private static Collection<CGNode> getSuccNodes(CallGraph cg, Collection<CGNode> nodes) { Set<CGNode> succNodes = HashSetFactory.make(); for (CGNode newInstanceNode : nodes) { Iterator<? extends CGNode> succNodesIter = cg.getSuccNodes(newInstanceNode); while (succNodesIter.hasNext()) { succNodes.add(succNodesIter.next()); } } return succNodes; } /** * Test that when analyzing reflect8, the call graph includes a node for * java.lang.Integer.toString() */ @Test public void testReflect8() throws WalaException, IllegalArgumentException, CancelException, IOException { AnalysisScope scope = findOrCreateAnalysisScope(); IClassHierarchy cha = findOrCreateCHA(scope); Iterable<Entrypoint> entrypoints = com.ibm.wala.ipa.callgraph.impl.Util.makeMainEntrypoints(cha, TestConstants.REFLECT8_MAIN); AnalysisOptions options = CallGraphTestUtil.makeAnalysisOptions(scope, entrypoints); CallGraph cg = CallGraphTestUtil.buildZeroOneCFA(options, new AnalysisCacheImpl(), cha, false); TypeReference tr = TypeReference.findOrCreate(ClassLoaderReference.Primordial, "Ljava/lang/Integer"); MethodReference mr = MethodReference.findOrCreate(tr, "toString", "()Ljava/lang/String;"); Set<CGNode> nodes = cg.getNodes(mr); Assert.assertFalse(nodes.isEmpty()); } /** * Test that when analyzing reflect9, the call graph includes a node for * java.lang.Integer.toString() */ @Test public void testReflect9() throws WalaException, IllegalArgumentException, CancelException, IOException { AnalysisScope scope = findOrCreateAnalysisScope(); IClassHierarchy cha = findOrCreateCHA(scope); Iterable<Entrypoint> entrypoints = com.ibm.wala.ipa.callgraph.impl.Util.makeMainEntrypoints(cha, TestConstants.REFLECT9_MAIN); AnalysisOptions options = CallGraphTestUtil.makeAnalysisOptions(scope, entrypoints); CallGraph cg = CallGraphTestUtil.buildZeroOneCFA(options, new AnalysisCacheImpl(), cha, false); TypeReference tr = TypeReference.findOrCreate(ClassLoaderReference.Primordial, "Ljava/lang/Integer"); MethodReference mr = MethodReference.findOrCreate(tr, "toString", "()Ljava/lang/String;"); Set<CGNode> nodes = cg.getNodes(mr); Assert.assertFalse(nodes.isEmpty()); } /** * Test that when analyzing Reflect10, the call graph includes a node for * java.lang.Integer.toString() */ @Test public void testReflect10() throws WalaException, IllegalArgumentException, CancelException, IOException { AnalysisScope scope = findOrCreateAnalysisScope(); IClassHierarchy cha = findOrCreateCHA(scope); Iterable<Entrypoint> entrypoints = com.ibm.wala.ipa.callgraph.impl.Util.makeMainEntrypoints(cha, TestConstants.REFLECT10_MAIN); AnalysisOptions options = CallGraphTestUtil.makeAnalysisOptions(scope, entrypoints); CallGraph cg = CallGraphTestUtil.buildZeroOneCFA(options, new AnalysisCacheImpl(), cha, false); TypeReference tr = TypeReference.findOrCreate(ClassLoaderReference.Primordial, "Ljava/lang/Integer"); MethodReference mr = MethodReference.findOrCreate(tr, "toString", "()Ljava/lang/String;"); Set<CGNode> nodes = cg.getNodes(mr); System.err.println(cg); Assert.assertFalse(nodes.isEmpty()); } /** * Test that when analyzing Reflect11, the call graph includes a node for java.lang.Object.wait() */ @Test public void testReflect11() throws WalaException, IllegalArgumentException, CancelException, IOException { AnalysisScope scope = findOrCreateAnalysisScope(); IClassHierarchy cha = findOrCreateCHA(scope); Iterable<Entrypoint> entrypoints = com.ibm.wala.ipa.callgraph.impl.Util.makeMainEntrypoints(cha, TestConstants.REFLECT11_MAIN); AnalysisOptions options = CallGraphTestUtil.makeAnalysisOptions(scope, entrypoints); CallGraph cg = CallGraphTestUtil.buildZeroOneCFA(options, new AnalysisCacheImpl(), cha, false); TypeReference tr = TypeReference.findOrCreate(ClassLoaderReference.Primordial, "Ljava/lang/Object"); MethodReference mr = MethodReference.findOrCreate(tr, "wait", "()V"); Set<CGNode> nodes = cg.getNodes(mr); Assert.assertFalse(nodes.isEmpty()); } /** * Test that when analyzing Reflect12, the call graph does not include a node for * reflection.Helper.n but does include a node for reflection.Helper.m */ @Test public void testReflect12() throws WalaException, IllegalArgumentException, CancelException, IOException { AnalysisScope scope = findOrCreateAnalysisScope(); IClassHierarchy cha = findOrCreateCHA(scope); Iterable<Entrypoint> entrypoints = com.ibm.wala.ipa.callgraph.impl.Util.makeMainEntrypoints(cha, TestConstants.REFLECT12_MAIN); AnalysisOptions options = CallGraphTestUtil.makeAnalysisOptions(scope, entrypoints); CallGraph cg = CallGraphTestUtil.buildZeroOneCFA(options, new AnalysisCacheImpl(), cha, false); TypeReference tr = TypeReference.findOrCreate(ClassLoaderReference.Application, "Lreflection/Helper"); MethodReference mr = MethodReference.findOrCreate( tr, "m", "(Ljava/lang/Object;Ljava/lang/Object;Ljava/lang/Object;)V"); Set<CGNode> nodes = cg.getNodes(mr); Assert.assertFalse(nodes.isEmpty()); mr = MethodReference.findOrCreate(tr, "n", "(Ljava/lang/Object;Ljava/lang/Object;)V"); nodes = cg.getNodes(mr); Assert.assertTrue(nodes.isEmpty()); } /** * Test that when analyzing Reflect13, the call graph includes both a node for reflection.Helper.n * and a node for reflection.Helper.m */ @Test public void testReflect13() throws WalaException, IllegalArgumentException, CancelException, IOException { AnalysisScope scope = findOrCreateAnalysisScope(); IClassHierarchy cha = findOrCreateCHA(scope); Iterable<Entrypoint> entrypoints = com.ibm.wala.ipa.callgraph.impl.Util.makeMainEntrypoints(cha, TestConstants.REFLECT13_MAIN); AnalysisOptions options = CallGraphTestUtil.makeAnalysisOptions(scope, entrypoints); CallGraph cg = CallGraphTestUtil.buildZeroOneCFA(options, new AnalysisCacheImpl(), cha, false); TypeReference tr = TypeReference.findOrCreate(ClassLoaderReference.Application, "Lreflection/Helper"); MethodReference mr = MethodReference.findOrCreate( tr, "m", "(Ljava/lang/Object;Ljava/lang/Object;Ljava/lang/Object;)V"); Set<CGNode> nodes = cg.getNodes(mr); Assert.assertFalse(nodes.isEmpty()); mr = MethodReference.findOrCreate(tr, "n", "(Ljava/lang/Object;Ljava/lang/Object;)V"); nodes = cg.getNodes(mr); Assert.assertFalse(nodes.isEmpty()); } /** * Test that when analyzing Reflect14, the call graph does not include a node for * reflection.Helper.n but does include a node for reflection.Helper.s */ @Test public void testReflect14() throws WalaException, IllegalArgumentException, CancelException, IOException { AnalysisScope scope = findOrCreateAnalysisScope(); IClassHierarchy cha = findOrCreateCHA(scope); Iterable<Entrypoint> entrypoints = com.ibm.wala.ipa.callgraph.impl.Util.makeMainEntrypoints(cha, TestConstants.REFLECT14_MAIN); AnalysisOptions options = CallGraphTestUtil.makeAnalysisOptions(scope, entrypoints); CallGraph cg = CallGraphTestUtil.buildZeroOneCFA(options, new AnalysisCacheImpl(), cha, false); TypeReference tr = TypeReference.findOrCreate(ClassLoaderReference.Application, "Lreflection/Helper"); MethodReference mr = MethodReference.findOrCreate(tr, "s", "(Ljava/lang/Object;Ljava/lang/Object;)V"); Set<CGNode> nodes = cg.getNodes(mr); Assert.assertFalse(nodes.isEmpty()); mr = MethodReference.findOrCreate(tr, "n", "(Ljava/lang/Object;Ljava/lang/Object;)V"); nodes = cg.getNodes(mr); Assert.assertTrue(nodes.isEmpty()); } /** * Test that when analyzing Reflect15, the call graph includes a node for the constructor of * Helper that takes 2 parameters and for Helper.n, but no node for the constructors of Helper * that takes 0 or 1 parameters. */ @Test public void testReflect15() throws WalaException, IllegalArgumentException, CancelException, IOException { AnalysisScope scope = findOrCreateAnalysisScope(); IClassHierarchy cha = findOrCreateCHA(scope); Iterable<Entrypoint> entrypoints = com.ibm.wala.ipa.callgraph.impl.Util.makeMainEntrypoints(cha, TestConstants.REFLECT15_MAIN); AnalysisOptions options = CallGraphTestUtil.makeAnalysisOptions(scope, entrypoints); CallGraph cg = CallGraphTestUtil.buildZeroOneCFA(options, new AnalysisCacheImpl(), cha, false); TypeReference tr = TypeReference.findOrCreate(ClassLoaderReference.Application, "Lreflection/Helper"); MethodReference mr = MethodReference.findOrCreate(tr, "<init>", "(Ljava/lang/Object;Ljava/lang/Object;)V"); Set<CGNode> nodes = cg.getNodes(mr); Assert.assertFalse(nodes.isEmpty()); mr = MethodReference.findOrCreate(tr, "<init>", "(Ljava/lang/Object;)V"); nodes = cg.getNodes(mr); Assert.assertTrue(nodes.isEmpty()); mr = MethodReference.findOrCreate(tr, "<init>", "()V"); nodes = cg.getNodes(mr); Assert.assertTrue(nodes.isEmpty()); mr = MethodReference.findOrCreate(tr, "n", "(Ljava/lang/Object;Ljava/lang/Object;)V"); nodes = cg.getNodes(mr); Assert.assertFalse(nodes.isEmpty()); } /** * Test that when analyzing Reflect16, the call graph includes a node for * java.lang.Integer.toString() */ @Test public void testReflect16() throws WalaException, IllegalArgumentException, CancelException, IOException { AnalysisScope scope = findOrCreateAnalysisScope(); IClassHierarchy cha = findOrCreateCHA(scope); Iterable<Entrypoint> entrypoints = com.ibm.wala.ipa.callgraph.impl.Util.makeMainEntrypoints(cha, TestConstants.REFLECT16_MAIN); AnalysisOptions options = CallGraphTestUtil.makeAnalysisOptions(scope, entrypoints); CallGraph cg = CallGraphTestUtil.buildZeroOneCFA(options, new AnalysisCacheImpl(), cha, false); TypeReference tr = TypeReference.findOrCreate(ClassLoaderReference.Primordial, "Ljava/lang/Integer"); MethodReference mr = MethodReference.findOrCreate(tr, "toString", "()Ljava/lang/String;"); Set<CGNode> nodes = cg.getNodes(mr); Assert.assertFalse(nodes.isEmpty()); } /** * Test that when analyzing Reflect17, the call graph does not include any edges from * reflection.Helper.t() */ @Test public void testReflect17() throws WalaException, IllegalArgumentException, CancelException, IOException { AnalysisScope scope = findOrCreateAnalysisScope(); IClassHierarchy cha = findOrCreateCHA(scope); Iterable<Entrypoint> entrypoints = com.ibm.wala.ipa.callgraph.impl.Util.makeMainEntrypoints(cha, TestConstants.REFLECT17_MAIN); AnalysisOptions options = CallGraphTestUtil.makeAnalysisOptions(scope, entrypoints); CallGraph cg = CallGraphTestUtil.buildZeroOneCFA(options, new AnalysisCacheImpl(), cha, false); TypeReference tr = TypeReference.findOrCreate(ClassLoaderReference.Application, "Lreflection/Helper"); MethodReference mr = MethodReference.findOrCreate(tr, "t", "(Ljava/lang/Integer;)V"); CGNode node = cg.getNode(cg.getClassHierarchy().resolveMethod(mr), Everywhere.EVERYWHERE); Assert.assertEquals(0, cg.getSuccNodeCount(node)); } /** * Test that when analyzing Reflect18, the call graph includes a node for * java.lang.Integer.toString() */ @Test public void testReflect18() throws WalaException, IllegalArgumentException, CancelException, IOException { AnalysisScope scope = findOrCreateAnalysisScope(); IClassHierarchy cha = findOrCreateCHA(scope); Iterable<Entrypoint> entrypoints = com.ibm.wala.ipa.callgraph.impl.Util.makeMainEntrypoints(cha, TestConstants.REFLECT18_MAIN); AnalysisOptions options = CallGraphTestUtil.makeAnalysisOptions(scope, entrypoints); CallGraph cg = CallGraphTestUtil.buildZeroOneCFA(options, new AnalysisCacheImpl(), cha, false); TypeReference tr = TypeReference.findOrCreate(ClassLoaderReference.Application, "Lreflection/Helper"); MethodReference mr = MethodReference.findOrCreate(tr, "t", "(Ljava/lang/Integer;)V"); CGNode node = cg.getNode(cg.getClassHierarchy().resolveMethod(mr), Everywhere.EVERYWHERE); Assert.assertEquals(1, cg.getSuccNodeCount(node)); CGNode succ = cg.getSuccNodes(node).next(); Assert.assertEquals( "Node: < Primordial, Ljava/lang/Integer, toString()Ljava/lang/String; > Context: Everywhere", succ.toString()); } /** * Test that when analyzing Reflect19, the call graph includes a node for * java.lang.Integer.toString() */ @Test public void testReflect19() throws WalaException, IllegalArgumentException, CancelException, IOException { AnalysisScope scope = findOrCreateAnalysisScope(); IClassHierarchy cha = findOrCreateCHA(scope); Iterable<Entrypoint> entrypoints = com.ibm.wala.ipa.callgraph.impl.Util.makeMainEntrypoints(cha, TestConstants.REFLECT19_MAIN); AnalysisOptions options = CallGraphTestUtil.makeAnalysisOptions(scope, entrypoints); CallGraph cg = CallGraphTestUtil.buildZeroOneCFA(options, new AnalysisCacheImpl(), cha, false); TypeReference tr = TypeReference.findOrCreate(ClassLoaderReference.Primordial, "Ljava/lang/Integer"); MethodReference mr = MethodReference.findOrCreate(tr, "toString", "()Ljava/lang/String;"); Set<CGNode> nodes = cg.getNodes(mr); Assert.assertFalse(nodes.isEmpty()); } /** Test that when analyzing Reflect20, the call graph includes a node for Helper.o. */ @Test public void testReflect20() throws WalaException, IllegalArgumentException, CancelException, IOException { AnalysisScope scope = findOrCreateAnalysisScope(); IClassHierarchy cha = findOrCreateCHA(scope); Iterable<Entrypoint> entrypoints = com.ibm.wala.ipa.callgraph.impl.Util.makeMainEntrypoints(cha, TestConstants.REFLECT20_MAIN); AnalysisOptions options = CallGraphTestUtil.makeAnalysisOptions(scope, entrypoints); CallGraph cg = CallGraphTestUtil.buildZeroOneCFA(options, new AnalysisCacheImpl(), cha, false); TypeReference tr = TypeReference.findOrCreate(ClassLoaderReference.Application, "Lreflection/Helper"); MethodReference mr = MethodReference.findOrCreate(tr, "o", "(Ljava/lang/Object;Ljava/lang/Object;)V"); Set<CGNode> nodes = cg.getNodes(mr); Assert.assertFalse(nodes.isEmpty()); } /** * Test that when analyzing Reflect21, the call graph includes a node for the constructor of * {@code Helper} that takes two {@link Object} parameters. This is to test the support for * Class.getDeclaredConstructor. */ @Test public void testReflect21() throws WalaException, IllegalArgumentException, CancelException, IOException { AnalysisScope scope = findOrCreateAnalysisScope(); IClassHierarchy cha = findOrCreateCHA(scope); Iterable<Entrypoint> entrypoints = com.ibm.wala.ipa.callgraph.impl.Util.makeMainEntrypoints(cha, TestConstants.REFLECT21_MAIN); AnalysisOptions options = CallGraphTestUtil.makeAnalysisOptions(scope, entrypoints); CallGraph cg = CallGraphTestUtil.buildZeroOneCFA(options, new AnalysisCacheImpl(), cha, false); TypeReference tr = TypeReference.findOrCreate(ClassLoaderReference.Application, "Lreflection/Helper"); MethodReference mr = MethodReference.findOrCreate(tr, "<init>", "(Ljava/lang/Object;Ljava/lang/Object;)V"); Set<CGNode> nodes = cg.getNodes(mr); Assert.assertFalse(nodes.isEmpty()); } /** * Test that when analyzing Reflect22, the call graph includes a node for the constructor of * {@code Helper} that takes one {@link Integer} parameters. This is to test the support for * Class.getDeclaredConstructors. */ @Test public void testReflect22() throws WalaException, IllegalArgumentException, CancelException, IOException { AnalysisScope scope = findOrCreateAnalysisScope(); IClassHierarchy cha = findOrCreateCHA(scope); Iterable<Entrypoint> entrypoints = com.ibm.wala.ipa.callgraph.impl.Util.makeMainEntrypoints(cha, TestConstants.REFLECT22_MAIN); AnalysisOptions options = CallGraphTestUtil.makeAnalysisOptions(scope, entrypoints); CallGraph cg = CallGraphTestUtil.buildZeroOneCFA(options, new AnalysisCacheImpl(), cha, false); TypeReference tr = TypeReference.findOrCreate(ClassLoaderReference.Application, "Lreflection/Helper"); MethodReference mr = MethodReference.findOrCreate(tr, "<init>", "(Ljava/lang/Integer;)V"); Set<CGNode> nodes = cg.getNodes(mr); Assert.assertFalse(nodes.isEmpty()); } /** * Test that when analyzing Reflect22, the call graph includes a node for the constructor of * {@code Helper} that takes one {@link Integer} parameters. This is to test the support for * Class.getDeclaredConstructors. */ @Test public void testReflect23() throws WalaException, IllegalArgumentException, CancelException, IOException { AnalysisScope scope = findOrCreateAnalysisScope(); IClassHierarchy cha = findOrCreateCHA(scope); Iterable<Entrypoint> entrypoints = com.ibm.wala.ipa.callgraph.impl.Util.makeMainEntrypoints(cha, TestConstants.REFLECT23_MAIN); AnalysisOptions options = CallGraphTestUtil.makeAnalysisOptions(scope, entrypoints); CallGraph cg = CallGraphTestUtil.buildZeroOneCFA(options, new AnalysisCacheImpl(), cha, false); TypeReference tr = TypeReference.findOrCreate(ClassLoaderReference.Application, "Lreflection/Helper"); MethodReference mr = MethodReference.findOrCreate(tr, "u", "(Ljava/lang/Integer;)V"); Set<CGNode> nodes = cg.getNodes(mr); Assert.assertFalse(nodes.isEmpty()); } /** * Test that when analyzing Reflect24. * * <p>Through the pointer analysis in the CallGraph construction process, it can be inferred that * the type pointed to by the 0th parameter of the {@code com.ibm.wala.test.People#doNothing()} * method is {@code Helper} * * <p>This is to test the support for Object.getClass(). */ @Test public void testReflect24() throws WalaException, IllegalArgumentException, CancelException, IOException { AnalysisScope scope = findOrCreateAnalysisScope(); IClassHierarchy cha = findOrCreateCHA(scope); Iterable<Entrypoint> entrypoints = com.ibm.wala.ipa.callgraph.impl.Util.makeMainEntrypoints(cha, TestConstants.REFLECT24_MAIN); AnalysisOptions options = CallGraphTestUtil.makeAnalysisOptions(scope, entrypoints); Pair<CallGraph, PointerAnalysis<InstanceKey>> pair = CallGraphTestUtil.buildNCFA(1, options, new AnalysisCacheImpl(), cha); CallGraph cg = pair.fst; PointerAnalysis<InstanceKey> pointerAnalysis = pair.snd; TypeReference helperTr = TypeReference.findOrCreate(ClassLoaderReference.Application, "Lreflection/Helper"); IClass helperClass = cha.lookupClass(helperTr); Assert.assertNotNull(helperClass); TypeReference reflect24Tr = TypeReference.findOrCreate(ClassLoaderReference.Application, "Lreflection/Reflect24"); MethodReference mr = MethodReference.findOrCreate(reflect24Tr, "doNothing", "(Ljava/lang/Class;)V"); Set<CGNode> nodes = cg.getNodes(mr); Assert.assertEquals(1, nodes.size()); // get the pts corresponding to the 0th parameter of the Reflect24#doNothing() method Optional<CGNode> firstMatched = nodes.stream().findFirst(); Assert.assertTrue(firstMatched.isPresent()); CGNode cgNode = firstMatched.get(); LocalPointerKey localPointerKey = new LocalPointerKey(cgNode, cgNode.getIR().getParameter(0)); OrdinalSet<InstanceKey> pts = pointerAnalysis.getPointsToSet(localPointerKey); Assert.assertEquals(1, pts.size()); for (InstanceKey mappedObject : pts) { // the type corresponding to the 0th parameter should be Helper Assert.assertTrue(mappedObject instanceof ConstantKey); Assert.assertEquals(((ConstantKey<?>) mappedObject).getValue(), helperClass); } } /** * Test that when analyzing GetMethodContext, the call graph must contain exactly one call to each * of the following methods: * * <ul> * <li>GetMethodContext$B#foo() * <li>GetMethodContext$C#bar() * </ul> * * and must not contain * * <ul> * <li>GetMethodContext$A#bar() * <li>GetMethodContext$A#baz() * <li>GetMethodContext$A#foo() * <li>GetMethodContext$B#bar() * <li>GetMethodContext$B#baz() * <li>GetMethodContext$C#baz() * <li>GetMethodContext$C#foo() * </ul> */ @Test public void testGetMethodContext() throws WalaException, IllegalArgumentException, CancelException, IOException { TypeReference ta = TypeReference.findOrCreate( ClassLoaderReference.Application, "Lreflection/GetMethodContext$A"); TypeReference tb = TypeReference.findOrCreate( ClassLoaderReference.Application, "Lreflection/GetMethodContext$B"); TypeReference tc = TypeReference.findOrCreate( ClassLoaderReference.Application, "Lreflection/GetMethodContext$C"); Selector sfoo = Selector.make("foo()V"), sbar = Selector.make("bar()V"), sbaz = Selector.make("baz()V"); MethodReference mafoo = MethodReference.findOrCreate(ta, sfoo), mbfoo = MethodReference.findOrCreate(tb, sfoo), mcfoo = MethodReference.findOrCreate(tc, sfoo), mabar = MethodReference.findOrCreate(ta, sbar), mbbar = MethodReference.findOrCreate(tb, sbar), mcbar = MethodReference.findOrCreate(tc, sbar), mabaz = MethodReference.findOrCreate(ta, sbaz), mbbaz = MethodReference.findOrCreate(tb, sbaz), mcbaz = MethodReference.findOrCreate(tc, sbaz); AnalysisScope scope = findOrCreateAnalysisScope(); IClassHierarchy cha = findOrCreateCHA(scope); Iterable<Entrypoint> entrypoints = com.ibm.wala.ipa.callgraph.impl.Util.makeMainEntrypoints( cha, TestConstants.REFLECTGETMETHODCONTEXT_MAIN); AnalysisOptions options = CallGraphTestUtil.makeAnalysisOptions(scope, entrypoints); CallGraph cg = CallGraphTestUtil.buildZeroOneCFA(options, new AnalysisCacheImpl(), cha, false); Set<CGNode> cgn; cgn = cg.getNodes(mabar); Assert.assertTrue(cgn.isEmpty()); cgn = cg.getNodes(mabaz); Assert.assertTrue(cgn.isEmpty()); cgn = cg.getNodes(mafoo); Assert.assertTrue(cgn.isEmpty()); cgn = cg.getNodes(mbbar); Assert.assertTrue(cgn.isEmpty()); cgn = cg.getNodes(mbbaz); Assert.assertTrue(cgn.isEmpty()); cgn = cg.getNodes(mcbaz); Assert.assertTrue(cgn.isEmpty()); cgn = cg.getNodes(mcfoo); Assert.assertTrue(cgn.isEmpty()); cgn = cg.getNodes(mbfoo); Assert.assertEquals(1, cgn.size()); cgn = cg.getNodes(mcbar); Assert.assertEquals(1, cgn.size()); } @Test public void testForNameThrownExceptions() throws WalaException, IllegalArgumentException, CancelException, IOException { AnalysisScope scope = findOrCreateAnalysisScope(); IClassHierarchy cha = findOrCreateCHA(scope); Iterable<Entrypoint> entrypoints = com.ibm.wala.ipa.callgraph.impl.Util.makeMainEntrypoints( cha, "Lreflection/ForNameThrownExceptions"); AnalysisOptions options = CallGraphTestUtil.makeAnalysisOptions(scope, entrypoints); options.setReflectionOptions(ReflectionOptions.NONE); CallGraph cg = CallGraphTestUtil.buildZeroCFA(options, new AnalysisCacheImpl(), cha, false); IMethod mainMethod = entrypoints.iterator().next().getMethod(); List<CGNode> mainCallees = Iterator2Collection.toList(cg.getSuccNodes(cg.getNode(mainMethod, Everywhere.EVERYWHERE))); Assert.assertTrue(mainCallees.stream().anyMatch(n -> n.toString().contains("getMessage"))); options.setReflectionOptions(ReflectionOptions.STRING_ONLY); cg = CallGraphTestUtil.buildZeroCFA(options, new AnalysisCacheImpl(), cha, false); mainCallees = Iterator2Collection.toList(cg.getSuccNodes(cg.getNode(mainMethod, Everywhere.EVERYWHERE))); // getMessage() should _not_ be a callee with reflection handling enabled Assert.assertFalse(mainCallees.stream().anyMatch(n -> n.toString().contains("getMessage"))); } }
39,326
44.889148
101
java
WALA
WALA-master/core/src/test/java/com/ibm/wala/core/tests/callGraph/StaticInterfaceMethodTest.java
package com.ibm.wala.core.tests.callGraph; import com.ibm.wala.core.tests.util.TestConstants; import com.ibm.wala.ipa.callgraph.AnalysisCacheImpl; import com.ibm.wala.ipa.callgraph.AnalysisOptions; import com.ibm.wala.ipa.callgraph.AnalysisScope; import com.ibm.wala.ipa.callgraph.CallGraph; import com.ibm.wala.ipa.callgraph.Entrypoint; import com.ibm.wala.ipa.callgraph.impl.DefaultEntrypoint; import com.ibm.wala.ipa.cha.ClassHierarchy; import com.ibm.wala.ipa.cha.ClassHierarchyException; import com.ibm.wala.ipa.cha.ClassHierarchyFactory; import com.ibm.wala.types.ClassLoaderReference; import com.ibm.wala.types.MethodReference; import com.ibm.wala.types.TypeReference; import com.ibm.wala.util.CancelException; import java.io.IOException; import java.util.List; import org.junit.Assert; import org.junit.Test; public class StaticInterfaceMethodTest { @Test public void staticInterfaceMethodAsEntrypoint() throws ClassHierarchyException, IllegalArgumentException, CancelException, IOException { AnalysisScope scope = CallGraphTestUtil.makeJ2SEAnalysisScope( TestConstants.WALA_TESTDATA, CallGraphTestUtil.REGRESSION_EXCLUSIONS); ClassHierarchy cha = ClassHierarchyFactory.make(scope); MethodReference staticInterfaceMethodRef = MethodReference.findOrCreate( TypeReference.findOrCreate( ClassLoaderReference.Application, "LstaticInterfaceMethod/InterfaceWithStaticMethod"), "test", "()V"); Iterable<Entrypoint> entrypoints = List.of(new DefaultEntrypoint(staticInterfaceMethodRef, cha)); AnalysisOptions options = CallGraphTestUtil.makeAnalysisOptions(scope, entrypoints); CallGraph cg = CallGraphTestUtil.buildZeroCFA(options, new AnalysisCacheImpl(), cha, false); Assert.assertEquals(1, cg.getNodes(staticInterfaceMethodRef).size()); } }
1,895
38.5
96
java
WALA
WALA-master/core/src/test/java/com/ibm/wala/core/tests/callGraph/SyntheticTest.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.callGraph; import com.ibm.wala.classLoader.IMethod; import com.ibm.wala.core.tests.util.TestConstants; import com.ibm.wala.core.tests.util.WalaTestCase; import com.ibm.wala.ipa.callgraph.AnalysisCacheImpl; import com.ibm.wala.ipa.callgraph.AnalysisOptions; import com.ibm.wala.ipa.callgraph.AnalysisScope; import com.ibm.wala.ipa.callgraph.CGNode; import com.ibm.wala.ipa.callgraph.CallGraph; import com.ibm.wala.ipa.callgraph.Entrypoint; import com.ibm.wala.ipa.callgraph.impl.SubtypesEntrypoint; import com.ibm.wala.ipa.cha.ClassHierarchy; import com.ibm.wala.ipa.cha.ClassHierarchyException; import com.ibm.wala.ipa.cha.ClassHierarchyFactory; import com.ibm.wala.ssa.IR; import com.ibm.wala.types.ClassLoaderReference; import com.ibm.wala.types.MethodReference; import com.ibm.wala.types.TypeReference; import com.ibm.wala.util.CancelException; import java.io.IOException; import java.util.Collections; import org.junit.Assert; import org.junit.Test; /** Tests for synthetic methods */ public class SyntheticTest extends WalaTestCase { @Test public void testMultiSubtypes() throws ClassHierarchyException, IllegalArgumentException, CancelException, IOException { AnalysisScope scope = CallGraphTestUtil.makeJ2SEAnalysisScope( TestConstants.WALA_TESTDATA, CallGraphTestUtil.REGRESSION_EXCLUSIONS); ClassHierarchy cha = ClassHierarchyFactory.make(scope); TypeReference t = TypeReference.findOrCreate(ClassLoaderReference.Application, "LmultiTypes/Foo"); MethodReference mref = MethodReference.findOrCreate(t, "foo", "(LmultiTypes/Foo$A;)V"); IMethod m = cha.resolveMethod(mref); assert m != null; SubtypesEntrypoint e = new SubtypesEntrypoint(m, cha); AnalysisOptions options = CallGraphTestUtil.makeAnalysisOptions(scope, Collections.<Entrypoint>singleton(e)); CallGraph cg = CallGraphTestUtil.buildZeroCFA(options, new AnalysisCacheImpl(), cha, false); TypeReference tA = TypeReference.findOrCreate(ClassLoaderReference.Application, "LmultiTypes/Foo$A"); MethodReference barA = MethodReference.findOrCreate(tA, "bar", "()V"); TypeReference tB = TypeReference.findOrCreate(ClassLoaderReference.Application, "LmultiTypes/Foo$B"); MethodReference barB = MethodReference.findOrCreate(tB, "bar", "()V"); Assert.assertEquals(1, cg.getNodes(barA).size()); Assert.assertEquals(1, cg.getNodes(barB).size()); CGNode root = cg.getFakeRootNode(); IR ir = root.getIR(); Assert.assertTrue(ir.iteratePhis().hasNext()); } }
2,953
40.605634
96
java
WALA
WALA-master/core/src/test/java/com/ibm/wala/core/tests/cfg/exc/inter/NullPointerExceptionInterTest.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.cfg.exc.inter; 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.IntraprocNullPointerAnalysis; import com.ibm.wala.classLoader.ClassLoaderFactory; import com.ibm.wala.classLoader.ClassLoaderFactoryImpl; import com.ibm.wala.core.tests.callGraph.CallGraphTestUtil; import com.ibm.wala.core.tests.util.TestConstants; import com.ibm.wala.core.tests.util.WalaTestCase; import com.ibm.wala.core.util.config.AnalysisScopeReader; import com.ibm.wala.core.util.io.FileProvider; import com.ibm.wala.core.util.strings.StringStuff; import com.ibm.wala.core.util.warnings.Warnings; import com.ibm.wala.ipa.callgraph.AnalysisCacheImpl; import com.ibm.wala.ipa.callgraph.AnalysisOptions; import com.ibm.wala.ipa.callgraph.AnalysisScope; import com.ibm.wala.ipa.callgraph.CGNode; import com.ibm.wala.ipa.callgraph.CallGraph; import com.ibm.wala.ipa.callgraph.CallGraphBuilder; import com.ibm.wala.ipa.callgraph.Entrypoint; import com.ibm.wala.ipa.callgraph.IAnalysisCacheView; import com.ibm.wala.ipa.callgraph.impl.Util; import com.ibm.wala.ipa.callgraph.propagation.InstanceKey; import com.ibm.wala.ipa.cha.ClassHierarchy; import com.ibm.wala.ipa.cha.ClassHierarchyException; import com.ibm.wala.ipa.cha.ClassHierarchyFactory; import com.ibm.wala.ssa.SSAInstruction; import com.ibm.wala.ssa.analysis.IExplodedBasicBlock; import com.ibm.wala.types.MethodReference; import com.ibm.wala.util.CancelException; import com.ibm.wala.util.NullProgressMonitor; import com.ibm.wala.util.WalaException; import com.ibm.wala.util.graph.GraphIntegrity.UnsoundGraphException; import org.junit.AfterClass; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; /** * Test validity and precision of inter-procedural NullpointerException-Analysis {@link * IntraprocNullPointerAnalysis} */ public class NullPointerExceptionInterTest extends WalaTestCase { private static AnalysisScope scope; private static ClassHierarchy cha; private static CallGraph cg; private static IAnalysisCacheView cache; @BeforeClass public static void beforeClass() throws Exception { cache = new AnalysisCacheImpl(); scope = AnalysisScopeReader.instance.readJavaScope( TestConstants.WALA_TESTDATA, new FileProvider().getFile(CallGraphTestUtil.REGRESSION_EXCLUSIONS), NullPointerExceptionInterTest.class.getClassLoader()); ClassLoaderFactory factory = new ClassLoaderFactoryImpl(scope.getExclusions()); try { cha = ClassHierarchyFactory.make(scope, factory); Iterable<Entrypoint> entrypoints = com.ibm.wala.ipa.callgraph.impl.Util.makeMainEntrypoints( cha, "Lcfg/exc/inter/CallFieldAccess"); AnalysisOptions options = new AnalysisOptions(scope, entrypoints); CallGraphBuilder<InstanceKey> builder = Util.makeNCFABuilder(1, options, cache, cha); cg = builder.makeCallGraph(options, null); } catch (ClassHierarchyException e) { throw new Exception(e); } } @AfterClass public static void afterClass() throws Exception { Warnings.clear(); scope = null; cha = null; cg = null; cache = null; } public static void main(String[] args) { justThisTest(NullPointerExceptionInterTest.class); } @Test public void testIfException() throws UnsoundGraphException, CancelException, WalaException { MethodReference mr = StringStuff.makeMethodReference( "cfg.exc.inter.CallFieldAccess.callIfException()Lcfg/exc/intra/B"); InterprocAnalysisResult<SSAInstruction, IExplodedBasicBlock> interExplodedCFG = NullPointerAnalysis.computeInterprocAnalysis(cg, new NullProgressMonitor()); Assert.assertEquals(1, cg.getNodes(mr).size()); final CGNode callNode = cg.getNodes(mr).iterator().next(); ExceptionPruningAnalysis<SSAInstruction, IExplodedBasicBlock> intraExplodedCFG = interExplodedCFG.getResult(callNode); Assert.assertTrue(intraExplodedCFG.hasExceptions()); } @Test public void testDynamicIfException() throws UnsoundGraphException, CancelException, WalaException { MethodReference mr = StringStuff.makeMethodReference( "cfg.exc.inter.CallFieldAccess.callDynamicIfException()Lcfg/exc/intra/B"); Assert.assertEquals(1, cg.getNodes(mr).size()); final CGNode callNode = cg.getNodes(mr).iterator().next(); InterprocAnalysisResult<SSAInstruction, IExplodedBasicBlock> interExplodedCFG = NullPointerAnalysis.computeInterprocAnalysis(cg, new NullProgressMonitor()); ExceptionPruningAnalysis<SSAInstruction, IExplodedBasicBlock> intraExplodedCFG = interExplodedCFG.getResult(callNode); Assert.assertTrue(intraExplodedCFG.hasExceptions()); } @Test public void testIfNoException() throws UnsoundGraphException, CancelException, WalaException { MethodReference mr = StringStuff.makeMethodReference( "cfg.exc.inter.CallFieldAccess.callIfNoException()Lcfg/exc/intra/B"); InterprocAnalysisResult<SSAInstruction, IExplodedBasicBlock> interExplodedCFG = NullPointerAnalysis.computeInterprocAnalysis(cg, new NullProgressMonitor()); Assert.assertEquals(1, cg.getNodes(mr).size()); final CGNode callNode = cg.getNodes(mr).iterator().next(); ExceptionPruningAnalysis<SSAInstruction, IExplodedBasicBlock> intraExplodedCFG = interExplodedCFG.getResult(callNode); Assert.assertFalse(intraExplodedCFG.hasExceptions()); } @Test public void testDynamicIfNoException() throws UnsoundGraphException, CancelException, WalaException { MethodReference mr = StringStuff.makeMethodReference( "cfg.exc.inter.CallFieldAccess.callDynamicIfNoException()Lcfg/exc/intra/B"); InterprocAnalysisResult<SSAInstruction, IExplodedBasicBlock> interExplodedCFG = NullPointerAnalysis.computeInterprocAnalysis(cg, new NullProgressMonitor()); Assert.assertEquals(1, cg.getNodes(mr).size()); final CGNode callNode = cg.getNodes(mr).iterator().next(); ExceptionPruningAnalysis<SSAInstruction, IExplodedBasicBlock> intraExplodedCFG = interExplodedCFG.getResult(callNode); Assert.assertFalse(intraExplodedCFG.hasExceptions()); } @Test public void testIf2Exception() throws UnsoundGraphException, CancelException, WalaException { MethodReference mr = StringStuff.makeMethodReference( "cfg.exc.inter.CallFieldAccess.callIf2Exception()Lcfg/exc/intra/B"); InterprocAnalysisResult<SSAInstruction, IExplodedBasicBlock> interExplodedCFG = NullPointerAnalysis.computeInterprocAnalysis(cg, new NullProgressMonitor()); Assert.assertEquals(1, cg.getNodes(mr).size()); final CGNode callNode = cg.getNodes(mr).iterator().next(); ExceptionPruningAnalysis<SSAInstruction, IExplodedBasicBlock> intraExplodedCFG = interExplodedCFG.getResult(callNode); Assert.assertTrue(intraExplodedCFG.hasExceptions()); } @Test public void testDynamicIf2Exception() throws UnsoundGraphException, CancelException, WalaException { MethodReference mr = StringStuff.makeMethodReference( "cfg.exc.inter.CallFieldAccess.callDynamicIf2Exception()Lcfg/exc/intra/B"); Assert.assertEquals(1, cg.getNodes(mr).size()); final CGNode callNode = cg.getNodes(mr).iterator().next(); InterprocAnalysisResult<SSAInstruction, IExplodedBasicBlock> interExplodedCFG = NullPointerAnalysis.computeInterprocAnalysis(cg, new NullProgressMonitor()); ExceptionPruningAnalysis<SSAInstruction, IExplodedBasicBlock> intraExplodedCFG = interExplodedCFG.getResult(callNode); Assert.assertTrue(intraExplodedCFG.hasExceptions()); } @Test public void testIf2NoException() throws UnsoundGraphException, CancelException, WalaException { MethodReference mr = StringStuff.makeMethodReference( "cfg.exc.inter.CallFieldAccess.callIf2NoException()Lcfg/exc/intra/B"); InterprocAnalysisResult<SSAInstruction, IExplodedBasicBlock> interExplodedCFG = NullPointerAnalysis.computeInterprocAnalysis(cg, new NullProgressMonitor()); Assert.assertEquals(1, cg.getNodes(mr).size()); final CGNode callNode = cg.getNodes(mr).iterator().next(); ExceptionPruningAnalysis<SSAInstruction, IExplodedBasicBlock> intraExplodedCFG = interExplodedCFG.getResult(callNode); Assert.assertFalse(intraExplodedCFG.hasExceptions()); } @Test public void testDynamicIf2NoException() throws UnsoundGraphException, CancelException, WalaException { MethodReference mr = StringStuff.makeMethodReference( "cfg.exc.inter.CallFieldAccess.callDynamicIf2NoException()Lcfg/exc/intra/B"); InterprocAnalysisResult<SSAInstruction, IExplodedBasicBlock> interExplodedCFG = NullPointerAnalysis.computeInterprocAnalysis(cg, new NullProgressMonitor()); Assert.assertEquals(1, cg.getNodes(mr).size()); final CGNode callNode = cg.getNodes(mr).iterator().next(); ExceptionPruningAnalysis<SSAInstruction, IExplodedBasicBlock> intraExplodedCFG = interExplodedCFG.getResult(callNode); Assert.assertFalse(intraExplodedCFG.hasExceptions()); } @Test public void testGetException() throws UnsoundGraphException, CancelException, WalaException { MethodReference mr = StringStuff.makeMethodReference( "cfg.exc.inter.CallFieldAccess.callGetException()Lcfg/exc/intra/B"); InterprocAnalysisResult<SSAInstruction, IExplodedBasicBlock> interExplodedCFG = NullPointerAnalysis.computeInterprocAnalysis(cg, new NullProgressMonitor()); Assert.assertEquals(1, cg.getNodes(mr).size()); final CGNode callNode = cg.getNodes(mr).iterator().next(); ExceptionPruningAnalysis<SSAInstruction, IExplodedBasicBlock> intraExplodedCFG = interExplodedCFG.getResult(callNode); Assert.assertTrue(intraExplodedCFG.hasExceptions()); } @Test public void testDynamicGetException() throws UnsoundGraphException, CancelException, WalaException { MethodReference mr = StringStuff.makeMethodReference( "cfg.exc.inter.CallFieldAccess.callDynamicGetException()Lcfg/exc/intra/B"); Assert.assertEquals(1, cg.getNodes(mr).size()); final CGNode callNode = cg.getNodes(mr).iterator().next(); InterprocAnalysisResult<SSAInstruction, IExplodedBasicBlock> interExplodedCFG = NullPointerAnalysis.computeInterprocAnalysis(cg, new NullProgressMonitor()); ExceptionPruningAnalysis<SSAInstruction, IExplodedBasicBlock> intraExplodedCFG = interExplodedCFG.getResult(callNode); Assert.assertTrue(intraExplodedCFG.hasExceptions()); } }
11,215
38.77305
97
java
WALA
WALA-master/core/src/test/java/com/ibm/wala/core/tests/cfg/exc/intra/NullPointerExceptionIntraTest.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.cfg.exc.intra; import com.ibm.wala.cfg.ControlFlowGraph; import com.ibm.wala.cfg.exc.ExceptionPruningAnalysis; import com.ibm.wala.cfg.exc.NullPointerAnalysis; import com.ibm.wala.cfg.exc.intra.IntraprocNullPointerAnalysis; import com.ibm.wala.cfg.exc.intra.NullPointerState; import com.ibm.wala.cfg.exc.intra.NullPointerState.State; import com.ibm.wala.classLoader.ClassLoaderFactory; import com.ibm.wala.classLoader.ClassLoaderFactoryImpl; import com.ibm.wala.classLoader.IMethod; import com.ibm.wala.core.tests.util.TestConstants; import com.ibm.wala.core.tests.util.WalaTestCase; import com.ibm.wala.core.util.config.AnalysisScopeReader; import com.ibm.wala.core.util.io.FileProvider; import com.ibm.wala.core.util.strings.StringStuff; import com.ibm.wala.core.util.warnings.Warnings; import com.ibm.wala.ipa.callgraph.AnalysisCacheImpl; import com.ibm.wala.ipa.callgraph.AnalysisScope; import com.ibm.wala.ipa.cha.ClassHierarchy; import com.ibm.wala.ipa.cha.ClassHierarchyException; import com.ibm.wala.ipa.cha.ClassHierarchyFactory; import com.ibm.wala.ssa.IR; import com.ibm.wala.ssa.ISSABasicBlock; import com.ibm.wala.ssa.SSAInstruction; import com.ibm.wala.ssa.SSAReturnInstruction; import com.ibm.wala.ssa.analysis.IExplodedBasicBlock; import com.ibm.wala.types.MethodReference; import com.ibm.wala.util.CancelException; import com.ibm.wala.util.NullProgressMonitor; import com.ibm.wala.util.collections.Iterator2Iterable; import com.ibm.wala.util.graph.GraphIntegrity.UnsoundGraphException; import java.util.Collection; import org.junit.AfterClass; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Ignore; import org.junit.Test; /** * Test validity and precision of intra-procedurel NullpointerException-Analysis {@link * IntraprocNullPointerAnalysis} */ public class NullPointerExceptionIntraTest extends WalaTestCase { private static AnalysisScope scope; private static ClassHierarchy cha; @BeforeClass public static void beforeClass() throws Exception { scope = AnalysisScopeReader.instance.readJavaScope( TestConstants.WALA_TESTDATA, new FileProvider().getFile("J2SEClassHierarchyExclusions.txt"), NullPointerExceptionIntraTest.class.getClassLoader()); ClassLoaderFactory factory = new ClassLoaderFactoryImpl(scope.getExclusions()); try { cha = ClassHierarchyFactory.make(scope, factory); } catch (ClassHierarchyException e) { throw new Exception(e); } } @AfterClass public static void afterClass() throws Exception { Warnings.clear(); scope = null; cha = null; } public static void main(String[] args) { justThisTest(NullPointerExceptionIntraTest.class); } @Test public void testParam() throws UnsoundGraphException, CancelException { MethodReference mr = StringStuff.makeMethodReference( "cfg.exc.intra.FieldAccess.testParam(ZLcfg/exc/intra/B;Lcfg/exc/intra/B;)Lcfg/exc/intra/B"); IMethod m = cha.resolveMethod(mr); AnalysisCacheImpl cache = new AnalysisCacheImpl(); IR ir = cache.getIR(m); final ISSABasicBlock returnNode = returnNode(ir.getControlFlowGraph()); final int returnVal = returnVal(returnNode); { ExceptionPruningAnalysis<SSAInstruction, IExplodedBasicBlock> intraExplodedCFG = NullPointerAnalysis.createIntraproceduralExplodedCFGAnalysis(ir); intraExplodedCFG.compute(new NullProgressMonitor()); final IExplodedBasicBlock returnNodeExploded = returnNodeExploded(returnNode, intraExplodedCFG.getCFG()); final NullPointerState returnState = intraExplodedCFG.getState(returnNodeExploded); Assert.assertEquals(State.NULL, returnState.getState(returnVal)); } { ExceptionPruningAnalysis<SSAInstruction, ISSABasicBlock> intraSSACFG = NullPointerAnalysis.createIntraproceduralSSACFGAnalyis(ir); intraSSACFG.compute(new NullProgressMonitor()); Assert.assertEquals(ir.getControlFlowGraph().exit(), intraSSACFG.getCFG().exit()); Assert.assertEquals(returnNode, returnNode(intraSSACFG.getCFG())); final NullPointerState returnState = intraSSACFG.getState(returnNode); Assert.assertEquals(State.NULL, returnState.getState(returnVal)); } } @Test public void testDynamicParam() throws UnsoundGraphException, CancelException { MethodReference mr = StringStuff.makeMethodReference( "cfg.exc.intra.FieldAccessDynamic.testParam(ZLcfg/exc/intra/B;Lcfg/exc/intra/B;)Lcfg/exc/intra/B"); IMethod m = cha.resolveMethod(mr); AnalysisCacheImpl cache = new AnalysisCacheImpl(); IR ir = cache.getIR(m); final ISSABasicBlock returnNode = returnNode(ir.getControlFlowGraph()); final int returnVal = returnVal(returnNode); { ExceptionPruningAnalysis<SSAInstruction, IExplodedBasicBlock> intraExplodedCFG = NullPointerAnalysis.createIntraproceduralExplodedCFGAnalysis(ir); intraExplodedCFG.compute(new NullProgressMonitor()); final IExplodedBasicBlock returnNodeExploded = returnNodeExploded(returnNode, intraExplodedCFG.getCFG()); final NullPointerState returnState = intraExplodedCFG.getState(returnNodeExploded); Assert.assertEquals(State.NULL, returnState.getState(returnVal)); } { ExceptionPruningAnalysis<SSAInstruction, ISSABasicBlock> intraSSACFG = NullPointerAnalysis.createIntraproceduralSSACFGAnalyis(ir); intraSSACFG.compute(new NullProgressMonitor()); Assert.assertEquals(ir.getControlFlowGraph().exit(), intraSSACFG.getCFG().exit()); Assert.assertEquals(returnNode, returnNode(intraSSACFG.getCFG())); final NullPointerState returnState = intraSSACFG.getState(returnNode); Assert.assertEquals(State.NULL, returnState.getState(returnVal)); } } @Test public void testParam2() throws UnsoundGraphException, CancelException { MethodReference mr = StringStuff.makeMethodReference( "cfg.exc.intra.FieldAccess.testParam2(ZLcfg/exc/intra/B;Lcfg/exc/intra/B;)Lcfg/exc/intra/B"); IMethod m = cha.resolveMethod(mr); AnalysisCacheImpl cache = new AnalysisCacheImpl(); IR ir = cache.getIR(m); final ISSABasicBlock returnNode = returnNode(ir.getControlFlowGraph()); final int returnVal = returnVal(returnNode); { ExceptionPruningAnalysis<SSAInstruction, IExplodedBasicBlock> intraExplodedCFG = NullPointerAnalysis.createIntraproceduralExplodedCFGAnalysis(ir); intraExplodedCFG.compute(new NullProgressMonitor()); final IExplodedBasicBlock returnNodeExploded = returnNodeExploded(returnNode, intraExplodedCFG.getCFG()); final NullPointerState returnState = intraExplodedCFG.getState(returnNodeExploded); Assert.assertEquals(State.NOT_NULL, returnState.getState(returnVal)); } { ExceptionPruningAnalysis<SSAInstruction, ISSABasicBlock> intraSSACFG = NullPointerAnalysis.createIntraproceduralSSACFGAnalyis(ir); intraSSACFG.compute(new NullProgressMonitor()); Assert.assertEquals(ir.getControlFlowGraph().exit(), intraSSACFG.getCFG().exit()); Assert.assertEquals(returnNode, returnNode(intraSSACFG.getCFG())); final NullPointerState returnState = intraSSACFG.getState(returnNode); Assert.assertEquals(State.NOT_NULL, returnState.getState(returnVal)); } } @Ignore @Test public void testDynamicParam2() throws UnsoundGraphException, CancelException { MethodReference mr = StringStuff.makeMethodReference( "cfg.exc.intra.FieldAccess.testDynamicParam2(ZLcfg/exc/intra/B;Lcfg/exc/intra/B;)Lcfg/exc/intra/B"); IMethod m = cha.resolveMethod(mr); AnalysisCacheImpl cache = new AnalysisCacheImpl(); IR ir = cache.getIR(m); final ISSABasicBlock returnNode = returnNode(ir.getControlFlowGraph()); final int returnVal = returnVal(returnNode); { ExceptionPruningAnalysis<SSAInstruction, IExplodedBasicBlock> intraExplodedCFG = NullPointerAnalysis.createIntraproceduralExplodedCFGAnalysis(ir); intraExplodedCFG.compute(new NullProgressMonitor()); final IExplodedBasicBlock returnNodeExploded = returnNodeExploded(returnNode, intraExplodedCFG.getCFG()); final NullPointerState returnState = intraExplodedCFG.getState(returnNodeExploded); Assert.assertEquals(State.NOT_NULL, returnState.getState(returnVal)); } { ExceptionPruningAnalysis<SSAInstruction, ISSABasicBlock> intraSSACFG = NullPointerAnalysis.createIntraproceduralSSACFGAnalyis(ir); intraSSACFG.compute(new NullProgressMonitor()); Assert.assertEquals(ir.getControlFlowGraph().exit(), intraSSACFG.getCFG().exit()); Assert.assertEquals(returnNode, returnNode(intraSSACFG.getCFG())); final NullPointerState returnState = intraSSACFG.getState(returnNode); Assert.assertEquals(State.NOT_NULL, returnState.getState(returnVal)); } } @Test public void testIf() throws UnsoundGraphException, CancelException { MethodReference mr = StringStuff.makeMethodReference( "cfg.exc.intra.FieldAccess.testIf(ZLcfg/exc/intra/B;Lcfg/exc/intra/B;)Lcfg/exc/intra/B"); IMethod m = cha.resolveMethod(mr); AnalysisCacheImpl cache = new AnalysisCacheImpl(); IR ir = cache.getIR(m); final ISSABasicBlock returnNode = returnNode(ir.getControlFlowGraph()); final int returnVal = returnVal(returnNode); { ExceptionPruningAnalysis<SSAInstruction, IExplodedBasicBlock> intraExplodedCFG = NullPointerAnalysis.createIntraproceduralExplodedCFGAnalysis(ir); intraExplodedCFG.compute(new NullProgressMonitor()); final IExplodedBasicBlock returnNodeExploded = returnNodeExploded(returnNode, intraExplodedCFG.getCFG()); final NullPointerState returnState = intraExplodedCFG.getState(returnNodeExploded); Assert.assertEquals(State.NOT_NULL, returnState.getState(returnVal)); } { ExceptionPruningAnalysis<SSAInstruction, ISSABasicBlock> intraSSACFG = NullPointerAnalysis.createIntraproceduralSSACFGAnalyis(ir); intraSSACFG.compute(new NullProgressMonitor()); Assert.assertEquals(ir.getControlFlowGraph().exit(), intraSSACFG.getCFG().exit()); Assert.assertEquals(returnNode, returnNode(intraSSACFG.getCFG())); final NullPointerState returnState = intraSSACFG.getState(returnNode); Assert.assertEquals(State.NOT_NULL, returnState.getState(returnVal)); } } @Test public void testDynamicIf() throws UnsoundGraphException, CancelException { MethodReference mr = StringStuff.makeMethodReference( "cfg.exc.intra.FieldAccessDynamic.testIf(ZLcfg/exc/intra/B;Lcfg/exc/intra/B;)Lcfg/exc/intra/B"); IMethod m = cha.resolveMethod(mr); AnalysisCacheImpl cache = new AnalysisCacheImpl(); IR ir = cache.getIR(m); final ISSABasicBlock returnNode = returnNode(ir.getControlFlowGraph()); final int returnVal = returnVal(returnNode); { ExceptionPruningAnalysis<SSAInstruction, IExplodedBasicBlock> intraExplodedCFG = NullPointerAnalysis.createIntraproceduralExplodedCFGAnalysis(ir); intraExplodedCFG.compute(new NullProgressMonitor()); final IExplodedBasicBlock returnNodeExploded = returnNodeExploded(returnNode, intraExplodedCFG.getCFG()); final NullPointerState returnState = intraExplodedCFG.getState(returnNodeExploded); Assert.assertEquals(State.NOT_NULL, returnState.getState(returnVal)); } { ExceptionPruningAnalysis<SSAInstruction, ISSABasicBlock> intraSSACFG = NullPointerAnalysis.createIntraproceduralSSACFGAnalyis(ir); intraSSACFG.compute(new NullProgressMonitor()); Assert.assertEquals(ir.getControlFlowGraph().exit(), intraSSACFG.getCFG().exit()); Assert.assertEquals(returnNode, returnNode(intraSSACFG.getCFG())); final NullPointerState returnState = intraSSACFG.getState(returnNode); Assert.assertEquals(State.NOT_NULL, returnState.getState(returnVal)); } } @Test public void testIf2() throws UnsoundGraphException, CancelException { MethodReference mr = StringStuff.makeMethodReference( "cfg.exc.intra.FieldAccess.testIf2(ZLcfg/exc/intra/B;Lcfg/exc/intra/B;)Lcfg/exc/intra/B"); IMethod m = cha.resolveMethod(mr); AnalysisCacheImpl cache = new AnalysisCacheImpl(); IR ir = cache.getIR(m); final ISSABasicBlock returnNode = returnNode(ir.getControlFlowGraph()); final int returnVal = returnVal(returnNode); { ExceptionPruningAnalysis<SSAInstruction, IExplodedBasicBlock> intraExplodedCFG = NullPointerAnalysis.createIntraproceduralExplodedCFGAnalysis(ir); intraExplodedCFG.compute(new NullProgressMonitor()); final IExplodedBasicBlock returnNodeExploded = returnNodeExploded(returnNode, intraExplodedCFG.getCFG()); final NullPointerState returnState = intraExplodedCFG.getState(returnNodeExploded); Assert.assertNotEquals(State.NOT_NULL, returnState.getState(returnVal)); Assert.assertNotEquals(State.NULL, returnState.getState(returnVal)); } { ExceptionPruningAnalysis<SSAInstruction, ISSABasicBlock> intraSSACFG = NullPointerAnalysis.createIntraproceduralSSACFGAnalyis(ir); intraSSACFG.compute(new NullProgressMonitor()); Assert.assertEquals(ir.getControlFlowGraph().exit(), intraSSACFG.getCFG().exit()); Assert.assertEquals(returnNode, returnNode(intraSSACFG.getCFG())); final NullPointerState returnState = intraSSACFG.getState(returnNode); Assert.assertNotEquals(State.NOT_NULL, returnState.getState(returnVal)); Assert.assertNotEquals(State.NULL, returnState.getState(returnVal)); } } @Test public void testDynamicIf2() throws UnsoundGraphException, CancelException { MethodReference mr = StringStuff.makeMethodReference( "cfg.exc.intra.FieldAccessDynamic.testIf2(ZLcfg/exc/intra/B;Lcfg/exc/intra/B;)Lcfg/exc/intra/B"); IMethod m = cha.resolveMethod(mr); AnalysisCacheImpl cache = new AnalysisCacheImpl(); IR ir = cache.getIR(m); final ISSABasicBlock returnNode = returnNode(ir.getControlFlowGraph()); final int returnVal = returnVal(returnNode); { ExceptionPruningAnalysis<SSAInstruction, IExplodedBasicBlock> intraExplodedCFG = NullPointerAnalysis.createIntraproceduralExplodedCFGAnalysis(ir); intraExplodedCFG.compute(new NullProgressMonitor()); final IExplodedBasicBlock returnNodeExploded = returnNodeExploded(returnNode, intraExplodedCFG.getCFG()); final NullPointerState returnState = intraExplodedCFG.getState(returnNodeExploded); Assert.assertNotEquals(State.NOT_NULL, returnState.getState(returnVal)); Assert.assertNotEquals(State.NULL, returnState.getState(returnVal)); } { ExceptionPruningAnalysis<SSAInstruction, ISSABasicBlock> intraSSACFG = NullPointerAnalysis.createIntraproceduralSSACFGAnalyis(ir); intraSSACFG.compute(new NullProgressMonitor()); Assert.assertEquals(ir.getControlFlowGraph().exit(), intraSSACFG.getCFG().exit()); Assert.assertEquals(returnNode, returnNode(intraSSACFG.getCFG())); final NullPointerState returnState = intraSSACFG.getState(returnNode); Assert.assertNotEquals(State.NOT_NULL, returnState.getState(returnVal)); Assert.assertNotEquals(State.NULL, returnState.getState(returnVal)); } } @Test public void testIfContinued() throws UnsoundGraphException, CancelException { MethodReference mr = StringStuff.makeMethodReference( "cfg.exc.intra.FieldAccess.testIfContinued(ZLcfg/exc/intra/B;Lcfg/exc/intra/B;Lcfg/exc/intra/B;)Lcfg/exc/intra/B"); IMethod m = cha.resolveMethod(mr); AnalysisCacheImpl cache = new AnalysisCacheImpl(); IR ir = cache.getIR(m); final ISSABasicBlock returnNode = returnNode(ir.getControlFlowGraph()); final int returnVal = returnVal(returnNode); { ExceptionPruningAnalysis<SSAInstruction, IExplodedBasicBlock> intraExplodedCFG = NullPointerAnalysis.createIntraproceduralExplodedCFGAnalysis(ir); intraExplodedCFG.compute(new NullProgressMonitor()); final IExplodedBasicBlock returnNodeExploded = returnNodeExploded(returnNode, intraExplodedCFG.getCFG()); final NullPointerState returnState = intraExplodedCFG.getState(returnNodeExploded); Assert.assertNotEquals(State.NOT_NULL, returnState.getState(returnVal)); Assert.assertNotEquals(State.NULL, returnState.getState(returnVal)); } { ExceptionPruningAnalysis<SSAInstruction, ISSABasicBlock> intraSSACFG = NullPointerAnalysis.createIntraproceduralSSACFGAnalyis(ir); intraSSACFG.compute(new NullProgressMonitor()); Assert.assertEquals(ir.getControlFlowGraph().exit(), intraSSACFG.getCFG().exit()); Assert.assertEquals(returnNode, returnNode(intraSSACFG.getCFG())); final NullPointerState returnState = intraSSACFG.getState(returnNode); Assert.assertNotEquals(State.NOT_NULL, returnState.getState(returnVal)); Assert.assertNotEquals(State.NULL, returnState.getState(returnVal)); } } @Test public void testDynamicIfContinued() throws UnsoundGraphException, CancelException { MethodReference mr = StringStuff.makeMethodReference( "cfg.exc.intra.FieldAccessDynamic.testIfContinued(ZLcfg/exc/intra/B;Lcfg/exc/intra/B;Lcfg/exc/intra/B;)Lcfg/exc/intra/B"); IMethod m = cha.resolveMethod(mr); AnalysisCacheImpl cache = new AnalysisCacheImpl(); IR ir = cache.getIR(m); final ISSABasicBlock returnNode = returnNode(ir.getControlFlowGraph()); final int returnVal = returnVal(returnNode); { ExceptionPruningAnalysis<SSAInstruction, IExplodedBasicBlock> intraExplodedCFG = NullPointerAnalysis.createIntraproceduralExplodedCFGAnalysis(ir); intraExplodedCFG.compute(new NullProgressMonitor()); final IExplodedBasicBlock returnNodeExploded = returnNodeExploded(returnNode, intraExplodedCFG.getCFG()); final NullPointerState returnState = intraExplodedCFG.getState(returnNodeExploded); Assert.assertNotEquals(State.NOT_NULL, returnState.getState(returnVal)); Assert.assertNotEquals(State.NULL, returnState.getState(returnVal)); } { ExceptionPruningAnalysis<SSAInstruction, ISSABasicBlock> intraSSACFG = NullPointerAnalysis.createIntraproceduralSSACFGAnalyis(ir); intraSSACFG.compute(new NullProgressMonitor()); Assert.assertEquals(ir.getControlFlowGraph().exit(), intraSSACFG.getCFG().exit()); Assert.assertEquals(returnNode, returnNode(intraSSACFG.getCFG())); final NullPointerState returnState = intraSSACFG.getState(returnNode); Assert.assertNotEquals(State.NOT_NULL, returnState.getState(returnVal)); Assert.assertNotEquals(State.NULL, returnState.getState(returnVal)); } } @Test public void testIf3() throws UnsoundGraphException, CancelException { MethodReference mr = StringStuff.makeMethodReference( "cfg.exc.intra.FieldAccess.testIf3(ZLcfg/exc/intra/B;)Lcfg/exc/intra/B"); IMethod m = cha.resolveMethod(mr); AnalysisCacheImpl cache = new AnalysisCacheImpl(); IR ir = cache.getIR(m); final ISSABasicBlock returnNode = returnNode(ir.getControlFlowGraph()); final int returnVal = returnVal(returnNode); { ExceptionPruningAnalysis<SSAInstruction, IExplodedBasicBlock> intraExplodedCFG = NullPointerAnalysis.createIntraproceduralExplodedCFGAnalysis(ir); intraExplodedCFG.compute(new NullProgressMonitor()); final IExplodedBasicBlock returnNodeExploded = returnNodeExploded(returnNode, intraExplodedCFG.getCFG()); final NullPointerState returnState = intraExplodedCFG.getState(returnNodeExploded); Assert.assertNotEquals(State.NOT_NULL, returnState.getState(returnVal)); Assert.assertNotEquals(State.NULL, returnState.getState(returnVal)); } { ExceptionPruningAnalysis<SSAInstruction, ISSABasicBlock> intraSSACFG = NullPointerAnalysis.createIntraproceduralSSACFGAnalyis(ir); intraSSACFG.compute(new NullProgressMonitor()); Assert.assertEquals(ir.getControlFlowGraph().exit(), intraSSACFG.getCFG().exit()); Assert.assertEquals(returnNode, returnNode(intraSSACFG.getCFG())); final NullPointerState returnState = intraSSACFG.getState(returnNode); Assert.assertNotEquals(State.NOT_NULL, returnState.getState(returnVal)); Assert.assertNotEquals(State.NULL, returnState.getState(returnVal)); } } @Test public void testDynamicIf3() throws UnsoundGraphException, CancelException { MethodReference mr = StringStuff.makeMethodReference( "cfg.exc.intra.FieldAccessDynamic.testIf3(ZLcfg/exc/intra/B;)Lcfg/exc/intra/B"); IMethod m = cha.resolveMethod(mr); AnalysisCacheImpl cache = new AnalysisCacheImpl(); IR ir = cache.getIR(m); final ISSABasicBlock returnNode = returnNode(ir.getControlFlowGraph()); final int returnVal = returnVal(returnNode); { ExceptionPruningAnalysis<SSAInstruction, IExplodedBasicBlock> intraExplodedCFG = NullPointerAnalysis.createIntraproceduralExplodedCFGAnalysis(ir); intraExplodedCFG.compute(new NullProgressMonitor()); final IExplodedBasicBlock returnNodeExploded = returnNodeExploded(returnNode, intraExplodedCFG.getCFG()); final NullPointerState returnState = intraExplodedCFG.getState(returnNodeExploded); Assert.assertNotEquals(State.NOT_NULL, returnState.getState(returnVal)); Assert.assertNotEquals(State.NULL, returnState.getState(returnVal)); } { ExceptionPruningAnalysis<SSAInstruction, ISSABasicBlock> intraSSACFG = NullPointerAnalysis.createIntraproceduralSSACFGAnalyis(ir); intraSSACFG.compute(new NullProgressMonitor()); Assert.assertEquals(ir.getControlFlowGraph().exit(), intraSSACFG.getCFG().exit()); Assert.assertEquals(returnNode, returnNode(intraSSACFG.getCFG())); final NullPointerState returnState = intraSSACFG.getState(returnNode); Assert.assertNotEquals(State.NOT_NULL, returnState.getState(returnVal)); Assert.assertNotEquals(State.NULL, returnState.getState(returnVal)); } } @Test public void testWhile() throws UnsoundGraphException, CancelException { MethodReference mr = StringStuff.makeMethodReference( "cfg.exc.intra.FieldAccess.testWhile(ZLcfg/exc/intra/B;)Lcfg/exc/intra/B"); IMethod m = cha.resolveMethod(mr); AnalysisCacheImpl cache = new AnalysisCacheImpl(); IR ir = cache.getIR(m); final ISSABasicBlock returnNode = returnNode(ir.getControlFlowGraph()); final int returnVal = returnVal(returnNode); { ExceptionPruningAnalysis<SSAInstruction, IExplodedBasicBlock> intraExplodedCFG = NullPointerAnalysis.createIntraproceduralExplodedCFGAnalysis(ir); intraExplodedCFG.compute(new NullProgressMonitor()); final IExplodedBasicBlock returnNodeExploded = returnNodeExploded(returnNode, intraExplodedCFG.getCFG()); final NullPointerState returnState = intraExplodedCFG.getState(returnNodeExploded); Assert.assertNotEquals(State.NOT_NULL, returnState.getState(returnVal)); Assert.assertNotEquals(State.NULL, returnState.getState(returnVal)); } { ExceptionPruningAnalysis<SSAInstruction, ISSABasicBlock> intraSSACFG = NullPointerAnalysis.createIntraproceduralSSACFGAnalyis(ir); intraSSACFG.compute(new NullProgressMonitor()); Assert.assertEquals(ir.getControlFlowGraph().exit(), intraSSACFG.getCFG().exit()); Assert.assertEquals(returnNode, returnNode(intraSSACFG.getCFG())); final NullPointerState returnState = intraSSACFG.getState(returnNode); Assert.assertNotEquals(State.NOT_NULL, returnState.getState(returnVal)); Assert.assertNotEquals(State.NULL, returnState.getState(returnVal)); } } @Test public void testWhileDynamic() throws UnsoundGraphException, CancelException { MethodReference mr = StringStuff.makeMethodReference( "cfg.exc.intra.FieldAccessDynamic.testWhile(ZLcfg/exc/intra/B;)Lcfg/exc/intra/B"); IMethod m = cha.resolveMethod(mr); AnalysisCacheImpl cache = new AnalysisCacheImpl(); IR ir = cache.getIR(m); final ISSABasicBlock returnNode = returnNode(ir.getControlFlowGraph()); final int returnVal = returnVal(returnNode); { ExceptionPruningAnalysis<SSAInstruction, IExplodedBasicBlock> intraExplodedCFG = NullPointerAnalysis.createIntraproceduralExplodedCFGAnalysis(ir); intraExplodedCFG.compute(new NullProgressMonitor()); final IExplodedBasicBlock returnNodeExploded = returnNodeExploded(returnNode, intraExplodedCFG.getCFG()); final NullPointerState returnState = intraExplodedCFG.getState(returnNodeExploded); Assert.assertNotEquals(State.NOT_NULL, returnState.getState(returnVal)); Assert.assertNotEquals(State.NULL, returnState.getState(returnVal)); } { ExceptionPruningAnalysis<SSAInstruction, ISSABasicBlock> intraSSACFG = NullPointerAnalysis.createIntraproceduralSSACFGAnalyis(ir); intraSSACFG.compute(new NullProgressMonitor()); Assert.assertEquals(ir.getControlFlowGraph().exit(), intraSSACFG.getCFG().exit()); Assert.assertEquals(returnNode, returnNode(intraSSACFG.getCFG())); final NullPointerState returnState = intraSSACFG.getState(returnNode); Assert.assertNotEquals(State.NOT_NULL, returnState.getState(returnVal)); Assert.assertNotEquals(State.NULL, returnState.getState(returnVal)); } } @Test public void testWhile2() throws UnsoundGraphException, CancelException { MethodReference mr = StringStuff.makeMethodReference( "cfg.exc.intra.FieldAccess.testWhile2(ZLcfg/exc/intra/B;)Lcfg/exc/intra/B"); IMethod m = cha.resolveMethod(mr); AnalysisCacheImpl cache = new AnalysisCacheImpl(); IR ir = cache.getIR(m); final ISSABasicBlock returnNode = returnNode(ir.getControlFlowGraph()); final int returnVal = returnVal(returnNode); { ExceptionPruningAnalysis<SSAInstruction, IExplodedBasicBlock> intraExplodedCFG = NullPointerAnalysis.createIntraproceduralExplodedCFGAnalysis(ir); intraExplodedCFG.compute(new NullProgressMonitor()); final IExplodedBasicBlock returnNodeExploded = returnNodeExploded(returnNode, intraExplodedCFG.getCFG()); final NullPointerState returnState = intraExplodedCFG.getState(returnNodeExploded); Assert.assertEquals(State.NOT_NULL, returnState.getState(returnVal)); } { ExceptionPruningAnalysis<SSAInstruction, ISSABasicBlock> intraSSACFG = NullPointerAnalysis.createIntraproceduralSSACFGAnalyis(ir); intraSSACFG.compute(new NullProgressMonitor()); Assert.assertEquals(ir.getControlFlowGraph().exit(), intraSSACFG.getCFG().exit()); Assert.assertEquals(returnNode, returnNode(intraSSACFG.getCFG())); final NullPointerState returnState = intraSSACFG.getState(returnNode); Assert.assertEquals(State.NOT_NULL, returnState.getState(returnVal)); } } @Test public void testDynamicWhile2() throws UnsoundGraphException, CancelException { MethodReference mr = StringStuff.makeMethodReference( "cfg.exc.intra.FieldAccessDynamic.testWhile2(ZLcfg/exc/intra/B;)Lcfg/exc/intra/B"); IMethod m = cha.resolveMethod(mr); AnalysisCacheImpl cache = new AnalysisCacheImpl(); IR ir = cache.getIR(m); final ISSABasicBlock returnNode = returnNode(ir.getControlFlowGraph()); final int returnVal = returnVal(returnNode); { ExceptionPruningAnalysis<SSAInstruction, IExplodedBasicBlock> intraExplodedCFG = NullPointerAnalysis.createIntraproceduralExplodedCFGAnalysis(ir); intraExplodedCFG.compute(new NullProgressMonitor()); final IExplodedBasicBlock returnNodeExploded = returnNodeExploded(returnNode, intraExplodedCFG.getCFG()); final NullPointerState returnState = intraExplodedCFG.getState(returnNodeExploded); Assert.assertEquals(State.NOT_NULL, returnState.getState(returnVal)); } { ExceptionPruningAnalysis<SSAInstruction, ISSABasicBlock> intraSSACFG = NullPointerAnalysis.createIntraproceduralSSACFGAnalyis(ir); intraSSACFG.compute(new NullProgressMonitor()); Assert.assertEquals(ir.getControlFlowGraph().exit(), intraSSACFG.getCFG().exit()); Assert.assertEquals(returnNode, returnNode(intraSSACFG.getCFG())); final NullPointerState returnState = intraSSACFG.getState(returnNode); Assert.assertEquals(State.NOT_NULL, returnState.getState(returnVal)); } } @Test public void testGet() throws UnsoundGraphException, CancelException { MethodReference mr = StringStuff.makeMethodReference( "cfg.exc.intra.FieldAccess.testGet(ZLcfg/exc/intra/B;)Lcfg/exc/intra/B"); IMethod m = cha.resolveMethod(mr); AnalysisCacheImpl cache = new AnalysisCacheImpl(); IR ir = cache.getIR(m); final ISSABasicBlock returnNode = returnNode(ir.getControlFlowGraph()); final int returnVal = returnVal(returnNode); { ExceptionPruningAnalysis<SSAInstruction, IExplodedBasicBlock> intraExplodedCFG = NullPointerAnalysis.createIntraproceduralExplodedCFGAnalysis(ir); intraExplodedCFG.compute(new NullProgressMonitor()); final IExplodedBasicBlock returnNodeExploded = returnNodeExploded(returnNode, intraExplodedCFG.getCFG()); final NullPointerState returnState = intraExplodedCFG.getState(returnNodeExploded); Assert.assertNotEquals(State.NOT_NULL, returnState.getState(returnVal)); Assert.assertNotEquals(State.NULL, returnState.getState(returnVal)); } { ExceptionPruningAnalysis<SSAInstruction, ISSABasicBlock> intraSSACFG = NullPointerAnalysis.createIntraproceduralSSACFGAnalyis(ir); intraSSACFG.compute(new NullProgressMonitor()); Assert.assertEquals(ir.getControlFlowGraph().exit(), intraSSACFG.getCFG().exit()); Assert.assertEquals(returnNode, returnNode(intraSSACFG.getCFG())); final NullPointerState returnState = intraSSACFG.getState(returnNode); Assert.assertNotEquals(State.NOT_NULL, returnState.getState(returnVal)); Assert.assertNotEquals(State.NULL, returnState.getState(returnVal)); } } @Test public void testDynamicGet() throws UnsoundGraphException, CancelException { MethodReference mr = StringStuff.makeMethodReference( "cfg.exc.intra.FieldAccessDynamic.testGet(ZLcfg/exc/intra/B;)Lcfg/exc/intra/B"); IMethod m = cha.resolveMethod(mr); AnalysisCacheImpl cache = new AnalysisCacheImpl(); IR ir = cache.getIR(m); final ISSABasicBlock returnNode = returnNode(ir.getControlFlowGraph()); final int returnVal = returnVal(returnNode); { ExceptionPruningAnalysis<SSAInstruction, IExplodedBasicBlock> intraExplodedCFG = NullPointerAnalysis.createIntraproceduralExplodedCFGAnalysis(ir); intraExplodedCFG.compute(new NullProgressMonitor()); final IExplodedBasicBlock returnNodeExploded = returnNodeExploded(returnNode, intraExplodedCFG.getCFG()); final NullPointerState returnState = intraExplodedCFG.getState(returnNodeExploded); Assert.assertNotEquals(State.NOT_NULL, returnState.getState(returnVal)); Assert.assertNotEquals(State.NULL, returnState.getState(returnVal)); } { ExceptionPruningAnalysis<SSAInstruction, ISSABasicBlock> intraSSACFG = NullPointerAnalysis.createIntraproceduralSSACFGAnalyis(ir); intraSSACFG.compute(new NullProgressMonitor()); Assert.assertEquals(ir.getControlFlowGraph().exit(), intraSSACFG.getCFG().exit()); Assert.assertEquals(returnNode, returnNode(intraSSACFG.getCFG())); final NullPointerState returnState = intraSSACFG.getState(returnNode); Assert.assertNotEquals(State.NOT_NULL, returnState.getState(returnVal)); Assert.assertNotEquals(State.NULL, returnState.getState(returnVal)); } } public static ISSABasicBlock returnNode(ControlFlowGraph<SSAInstruction, ISSABasicBlock> cfg) { Collection<ISSABasicBlock> returnNodes = cfg.getNormalPredecessors(cfg.exit()); Assert.assertEquals(1, returnNodes.size()); return (ISSABasicBlock) returnNodes.toArray()[0]; } public static int returnVal(ISSABasicBlock returnNode) { final SSAReturnInstruction returnInst = (SSAReturnInstruction) returnNode.getLastInstruction(); Assert.assertEquals(1, returnInst.getNumberOfUses()); return returnInst.getUse(0); } public static IExplodedBasicBlock returnNodeExploded( ISSABasicBlock returnNode, ControlFlowGraph<SSAInstruction, IExplodedBasicBlock> explodedCfg) { final IExplodedBasicBlock exit = explodedCfg.exit(); for (IExplodedBasicBlock candidate : Iterator2Iterable.make(explodedCfg.getPredNodes(exit))) { if (candidate.getInstruction() == returnNode.getLastInstruction()) { return candidate; } } Assert.fail(); return null; } }
33,840
41.30125
134
java
WALA
WALA-master/core/src/test/java/com/ibm/wala/core/tests/cha/AnalysisScopeTest.java
package com.ibm.wala.core.tests.cha; import com.ibm.wala.core.tests.util.TestConstants; import com.ibm.wala.core.util.config.AnalysisScopeReader; import com.ibm.wala.core.util.io.FileProvider; import com.ibm.wala.ipa.callgraph.AnalysisScope; import com.ibm.wala.ipa.cha.ClassHierarchy; import com.ibm.wala.ipa.cha.ClassHierarchyException; import com.ibm.wala.ipa.cha.ClassHierarchyFactory; import com.ibm.wala.types.ClassLoaderReference; import com.ibm.wala.types.TypeReference; import java.io.FileInputStream; import java.io.IOException; import java.nio.file.Path; import java.nio.file.Paths; import org.junit.Assert; import org.junit.Test; public class AnalysisScopeTest { @Test public void testJarInputStream() throws IOException, ClassHierarchyException { AnalysisScope scope = AnalysisScopeReader.instance.readJavaScope( TestConstants.WALA_TESTDATA, new FileProvider().getFile("J2SEClassHierarchyExclusions.txt"), AnalysisScopeTest.class.getClassLoader()); // assumes com.ibm.wala.core is the current working directory Path bcelJarPath = Paths.get("build", "extractBcel", "bcel-5.2.jar"); scope.addInputStreamForJarToScope( ClassLoaderReference.Application, new FileInputStream(bcelJarPath.toString())); ClassHierarchy cha = ClassHierarchyFactory.make(scope); Assert.assertNotNull( "couldn't find expected class", cha.lookupClass( TypeReference.findOrCreate( ClassLoaderReference.Application, "Lorg/apache/bcel/verifier/Verifier"))); } @Test public void testBaseScope() throws IOException, ClassHierarchyException { AnalysisScope scope = AnalysisScopeReader.instance.readJavaScope( "primordial-base.txt", null, AnalysisScopeTest.class.getClassLoader()); ClassHierarchy cha = ClassHierarchyFactory.make(scope); Assert.assertNotNull( "couldn't find expected class", cha.lookupClass( TypeReference.findOrCreate(ClassLoaderReference.Application, "Ljava/util/ArrayList"))); Assert.assertNull( "found unexpected class", cha.lookupClass( TypeReference.findOrCreate( ClassLoaderReference.Application, "Ljava/awt/AlphaComposite"))); } }
2,277
38.964912
99
java
WALA
WALA-master/core/src/test/java/com/ibm/wala/core/tests/cha/CodeDeletedTest.java
/* * Copyright (c) 2008 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package com.ibm.wala.core.tests.cha; import com.ibm.wala.classLoader.IClass; import com.ibm.wala.classLoader.IMethod; import com.ibm.wala.core.tests.util.TestConstants; import com.ibm.wala.core.tests.util.WalaTestCase; import com.ibm.wala.core.util.config.AnalysisScopeReader; import com.ibm.wala.core.util.io.FileProvider; import com.ibm.wala.ipa.callgraph.AnalysisCacheImpl; import com.ibm.wala.ipa.callgraph.AnalysisScope; import com.ibm.wala.ipa.callgraph.IAnalysisCacheView; import com.ibm.wala.ipa.cha.ClassHierarchy; import com.ibm.wala.ipa.cha.ClassHierarchyException; import com.ibm.wala.ipa.cha.ClassHierarchyFactory; import com.ibm.wala.types.ClassLoaderReference; import com.ibm.wala.types.TypeReference; import com.ibm.wala.util.WalaRuntimeException; import java.io.IOException; import org.junit.Test; public class CodeDeletedTest extends WalaTestCase { /** * Test handling of an invalid class where a non-abstract method has no code. We want to throw an * exception rather than crash. */ @Test(expected = WalaRuntimeException.class) public void testDeletedCode() throws IOException, ClassHierarchyException { AnalysisScope scope = AnalysisScopeReader.instance.readJavaScope( TestConstants.WALA_TESTDATA, new FileProvider().getFile("J2SEClassHierarchyExclusions.txt"), DupFieldsTest.class.getClassLoader()); ClassHierarchy cha = ClassHierarchyFactory.make(scope); TypeReference ref = TypeReference.findOrCreate(ClassLoaderReference.Application, "LCodeDeleted"); IClass klass = cha.lookupClass(ref); IAnalysisCacheView cache = new AnalysisCacheImpl(); for (IMethod m : klass.getDeclaredMethods()) { if (m.toString().contains("foo")) { // should throw WalaRuntimeException cache.getIR(m); } } } }
2,205
37.034483
99
java
WALA
WALA-master/core/src/test/java/com/ibm/wala/core/tests/cha/DupFieldsTest.java
/* * Copyright (c) 2008 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package com.ibm.wala.core.tests.cha; import com.ibm.wala.classLoader.IClass; import com.ibm.wala.classLoader.IField; import com.ibm.wala.core.tests.util.TestConstants; import com.ibm.wala.core.tests.util.WalaTestCase; import com.ibm.wala.core.util.config.AnalysisScopeReader; import com.ibm.wala.core.util.io.FileProvider; import com.ibm.wala.core.util.strings.Atom; import com.ibm.wala.ipa.callgraph.AnalysisScope; import com.ibm.wala.ipa.cha.ClassHierarchy; import com.ibm.wala.ipa.cha.ClassHierarchyException; import com.ibm.wala.ipa.cha.ClassHierarchyFactory; import com.ibm.wala.types.ClassLoaderReference; import com.ibm.wala.types.FieldReference; import com.ibm.wala.types.TypeReference; import java.io.IOException; import org.junit.Assert; import org.junit.Test; public class DupFieldsTest extends WalaTestCase { @Test public void testDupFieldNames() throws IOException, ClassHierarchyException { AnalysisScope scope = AnalysisScopeReader.instance.readJavaScope( TestConstants.WALA_TESTDATA, new FileProvider().getFile("J2SEClassHierarchyExclusions.txt"), DupFieldsTest.class.getClassLoader()); ClassHierarchy cha = ClassHierarchyFactory.make(scope); TypeReference ref = TypeReference.findOrCreate(ClassLoaderReference.Application, "LDupFieldName"); IClass klass = cha.lookupClass(ref); boolean threwException = false; try { klass.getField(Atom.findOrCreateUnicodeAtom("a")); } catch (IllegalStateException e) { threwException = true; } Assert.assertTrue(threwException); IField f = cha.resolveField( FieldReference.findOrCreate(ref, Atom.findOrCreateUnicodeAtom("a"), TypeReference.Int)); Assert.assertEquals(f.getFieldTypeReference(), TypeReference.Int); f = cha.resolveField( FieldReference.findOrCreate( ref, Atom.findOrCreateUnicodeAtom("a"), TypeReference.Boolean)); Assert.assertEquals(f.getFieldTypeReference(), TypeReference.Boolean); } }
2,406
37.206349
100
java
WALA
WALA-master/core/src/test/java/com/ibm/wala/core/tests/cha/ExclusionsTest.java
/* * Copyright (c) 2008 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package com.ibm.wala.core.tests.cha; import com.ibm.wala.core.tests.util.TestConstants; import com.ibm.wala.core.util.config.AnalysisScopeReader; import com.ibm.wala.core.util.io.FileProvider; import com.ibm.wala.core.util.strings.StringStuff; import com.ibm.wala.ipa.callgraph.AnalysisScope; import com.ibm.wala.types.ClassLoaderReference; import com.ibm.wala.types.TypeReference; import java.io.IOException; import org.junit.Assert; import org.junit.Test; public class ExclusionsTest { @Test public void testExclusions() throws IOException { AnalysisScope scope = AnalysisScopeReader.instance.readJavaScope( TestConstants.WALA_TESTDATA, new FileProvider().getFile("GUIExclusions.txt"), ExclusionsTest.class.getClassLoader()); TypeReference buttonRef = TypeReference.findOrCreate( ClassLoaderReference.Application, StringStuff.deployment2CanonicalTypeString("java.awt.Button")); Assert.assertTrue(scope.getExclusions().contains(buttonRef.getName().toString().substring(1))); } }
1,445
35.15
99
java
WALA
WALA-master/core/src/test/java/com/ibm/wala/core/tests/cha/GetTargetsTest.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.cha; import com.ibm.wala.classLoader.ClassLoaderFactory; import com.ibm.wala.classLoader.ClassLoaderFactoryImpl; import com.ibm.wala.classLoader.IClass; import com.ibm.wala.classLoader.IMethod; import com.ibm.wala.core.tests.util.TestConstants; import com.ibm.wala.core.tests.util.WalaTestCase; import com.ibm.wala.core.util.config.AnalysisScopeReader; import com.ibm.wala.core.util.io.FileProvider; import com.ibm.wala.ipa.callgraph.AnalysisScope; import com.ibm.wala.ipa.cha.ClassHierarchy; import com.ibm.wala.ipa.cha.ClassHierarchyException; import com.ibm.wala.ipa.cha.ClassHierarchyFactory; import com.ibm.wala.types.ClassLoaderReference; import com.ibm.wala.types.MethodReference; import com.ibm.wala.types.Selector; import com.ibm.wala.types.TypeReference; import java.util.Collection; import org.junit.AfterClass; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; /** Test ClassHierarchy.getPossibleTargets */ public class GetTargetsTest extends WalaTestCase { private static final ClassLoader MY_CLASSLOADER = GetTargetsTest.class.getClassLoader(); private static AnalysisScope scope; private static ClassHierarchy cha; public static void main(String[] args) { justThisTest(GetTargetsTest.class); } @BeforeClass public static void beforeClass() throws Exception { scope = AnalysisScopeReader.instance.readJavaScope( TestConstants.WALA_TESTDATA, new FileProvider().getFile("J2SEClassHierarchyExclusions.txt"), MY_CLASSLOADER); ClassLoaderFactory factory = new ClassLoaderFactoryImpl(scope.getExclusions()); try { cha = ClassHierarchyFactory.make(scope, factory); } catch (ClassHierarchyException e) { throw new Exception(e); } } /* * (non-Javadoc) * * @see junit.framework.TestCase#tearDown() */ @AfterClass public static void afterClass() throws Exception { scope = null; cha = null; } /** Test for bug 1714480, reported OOM on {@link ClassHierarchy} getPossibleTargets() */ @Test public void testCell() { TypeReference t = TypeReference.findOrCreate(ClassLoaderReference.Application, "Lcell/Cell"); MethodReference m = MethodReference.findOrCreate(t, "<init>", "(Ljava/lang/Object;)V"); Collection<IMethod> c = cha.getPossibleTargets(m); for (IMethod method : c) { System.err.println(method); } Assert.assertEquals(1, c.size()); } /** test that calls to &lt;init&gt; methods are treated specially */ @Test public void testObjInit() { MethodReference m = MethodReference.findOrCreate(TypeReference.JavaLangObject, MethodReference.initSelector); Collection<IMethod> c = cha.getPossibleTargets(m); for (IMethod method : c) { System.err.println(method); } Assert.assertEquals(1, c.size()); } @Test public void testConstructorLookup() { IClass testKlass = cha.lookupClass( TypeReference.findOrCreate( ClassLoaderReference.Application, "LmethodLookup/MethodLookupStuff$B")); IMethod m = testKlass.getMethod(Selector.make("<init>(I)V")); Assert.assertNull(m); } }
3,574
31.5
97
java
WALA
WALA-master/core/src/test/java/com/ibm/wala/core/tests/cha/InnerClassesTest.java
/* * Copyright (c) 20078 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this 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.cha; import com.ibm.wala.classLoader.ClassLoaderFactory; import com.ibm.wala.classLoader.ClassLoaderFactoryImpl; import com.ibm.wala.classLoader.IClass; import com.ibm.wala.classLoader.ShrikeClass; import com.ibm.wala.core.tests.util.TestConstants; import com.ibm.wala.core.tests.util.WalaTestCase; import com.ibm.wala.core.util.config.AnalysisScopeReader; import com.ibm.wala.core.util.io.FileProvider; import com.ibm.wala.ipa.callgraph.AnalysisScope; import com.ibm.wala.ipa.cha.ClassHierarchy; import com.ibm.wala.ipa.cha.ClassHierarchyException; import com.ibm.wala.ipa.cha.ClassHierarchyFactory; import com.ibm.wala.shrike.shrikeCT.InvalidClassFileException; import com.ibm.wala.types.ClassLoaderReference; import com.ibm.wala.types.TypeName; import com.ibm.wala.types.TypeReference; import org.junit.AfterClass; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; /** Test stuff with inner classes */ public class InnerClassesTest extends WalaTestCase { private static final ClassLoader MY_CLASSLOADER = InnerClassesTest.class.getClassLoader(); private static AnalysisScope scope; private static ClassHierarchy cha; public static void main(String[] args) { justThisTest(InnerClassesTest.class); } @BeforeClass public static void beforeClass() throws Exception { scope = AnalysisScopeReader.instance.readJavaScope( TestConstants.WALA_TESTDATA, new FileProvider().getFile("J2SEClassHierarchyExclusions.txt"), MY_CLASSLOADER); ClassLoaderFactory factory = new ClassLoaderFactoryImpl(scope.getExclusions()); try { cha = ClassHierarchyFactory.make(scope, factory); } catch (ClassHierarchyException e) { throw new Exception(e); } } @AfterClass public static void afterClass() throws Exception { scope = null; cha = null; } @Test public void test1() throws InvalidClassFileException { TypeReference t = TypeReference.findOrCreate( ClassLoaderReference.Application, TypeName.string2TypeName("Linner/TestStaticInner")); IClass klass = cha.lookupClass(t); assert klass != null; ShrikeClass s = (ShrikeClass) klass; Assert.assertFalse(s.isInnerClass()); } @Test public void test2() throws InvalidClassFileException { TypeReference t = TypeReference.findOrCreate( ClassLoaderReference.Application, TypeName.string2TypeName("Linner/TestStaticInner$A")); IClass klass = cha.lookupClass(t); assert klass != null; ShrikeClass s = (ShrikeClass) klass; Assert.assertTrue(s.isInnerClass()); Assert.assertTrue(s.isStaticInnerClass()); } @Test public void test3() throws InvalidClassFileException { TypeReference t = TypeReference.findOrCreate( ClassLoaderReference.Application, TypeName.string2TypeName("Linner/TestInner$A")); IClass klass = cha.lookupClass(t); assert klass != null; ShrikeClass s = (ShrikeClass) klass; Assert.assertTrue(s.isInnerClass()); Assert.assertFalse(s.isStaticInnerClass()); } }
3,488
32.228571
100
java
WALA
WALA-master/core/src/test/java/com/ibm/wala/core/tests/cha/InterfaceTest.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.tests.cha; import com.ibm.wala.classLoader.ClassLoaderFactory; import com.ibm.wala.classLoader.ClassLoaderFactoryImpl; import com.ibm.wala.classLoader.IClass; import com.ibm.wala.core.tests.util.TestConstants; import com.ibm.wala.core.tests.util.WalaTestCase; import com.ibm.wala.core.util.config.AnalysisScopeReader; import com.ibm.wala.core.util.io.FileProvider; import com.ibm.wala.ipa.callgraph.AnalysisScope; import com.ibm.wala.ipa.cha.ClassHierarchy; import com.ibm.wala.ipa.cha.ClassHierarchyException; import com.ibm.wala.ipa.cha.ClassHierarchyFactory; import com.ibm.wala.types.ClassLoaderReference; import com.ibm.wala.types.TypeName; import com.ibm.wala.types.TypeReference; import org.junit.AfterClass; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; /** Test interface subtype stuff */ public class InterfaceTest extends WalaTestCase { private static final ClassLoader MY_CLASSLOADER = InterfaceTest.class.getClassLoader(); private static AnalysisScope scope; private static ClassHierarchy cha; public static void main(String[] args) { justThisTest(InterfaceTest.class); } @BeforeClass public static void beforeClass() throws Exception { scope = AnalysisScopeReader.instance.readJavaScope( TestConstants.WALA_TESTDATA, new FileProvider().getFile("J2SEClassHierarchyExclusions.txt"), MY_CLASSLOADER); scope.addJDKModuleToScope("java.sql"); ClassLoaderFactory factory = new ClassLoaderFactoryImpl(scope.getExclusions()); try { cha = ClassHierarchyFactory.make(scope, factory); } catch (ClassHierarchyException e) { throw new Exception(e); } } @AfterClass public static void afterClass() throws Exception { scope = null; cha = null; } /** Test for subtype tests with interfaces; bug reported by Bruno Dufour */ @Test public void test1() { TypeReference prep_stmt_type = TypeReference.findOrCreate( ClassLoaderReference.Primordial, TypeName.string2TypeName("Ljava/sql/PreparedStatement")); TypeReference stmt_type = TypeReference.findOrCreate( ClassLoaderReference.Primordial, TypeName.string2TypeName("Ljava/sql/Statement")); IClass prep_stmt = cha.lookupClass(prep_stmt_type); IClass stmt = cha.lookupClass(stmt_type); Assert.assertNotNull("did not find PreparedStatement", prep_stmt); Assert.assertNotNull("did not find Statement", stmt); Assert.assertTrue(cha.implementsInterface(prep_stmt, stmt)); Assert.assertFalse(cha.implementsInterface(stmt, prep_stmt)); Assert.assertTrue(cha.isAssignableFrom(stmt, prep_stmt)); Assert.assertFalse(cha.isAssignableFrom(prep_stmt, stmt)); } /** check that arrays implement Cloneable and Serializable */ @Test public void test2() { IClass objArrayClass = cha.lookupClass(TypeReference.JavaLangObject.getArrayTypeForElementType()); IClass stringArrayClass = cha.lookupClass(TypeReference.JavaLangString.getArrayTypeForElementType()); IClass cloneableClass = cha.lookupClass(TypeReference.JavaLangCloneable); IClass serializableClass = cha.lookupClass(TypeReference.JavaIoSerializable); Assert.assertTrue(cha.implementsInterface(objArrayClass, cloneableClass)); Assert.assertTrue(cha.implementsInterface(objArrayClass, serializableClass)); Assert.assertTrue(cha.implementsInterface(stringArrayClass, cloneableClass)); Assert.assertTrue(cha.implementsInterface(stringArrayClass, serializableClass)); } }
3,960
36.72381
94
java
WALA
WALA-master/core/src/test/java/com/ibm/wala/core/tests/cha/LibraryVersionTest.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.cha; import com.ibm.wala.core.tests.ir.DeterministicIRTest; import com.ibm.wala.core.tests.util.TestConstants; import com.ibm.wala.core.tests.util.WalaTestCase; import com.ibm.wala.core.util.config.AnalysisScopeReader; import com.ibm.wala.core.util.io.FileProvider; import com.ibm.wala.ipa.callgraph.AnalysisScope; import java.io.IOException; import org.junit.Assert; import org.junit.Test; /** * Test code that attempts to find the library version from the analysis scope. * * @author Julian Dolby (dolby@us.ibm.com) */ public class LibraryVersionTest extends WalaTestCase { private static final ClassLoader MY_CLASSLOADER = DeterministicIRTest.class.getClassLoader(); @Test public void testLibraryVersion() throws IOException { AnalysisScope scope = AnalysisScopeReader.instance.readJavaScope( TestConstants.WALA_TESTDATA, new FileProvider().getFile("J2SEClassHierarchyExclusions.txt"), MY_CLASSLOADER); System.err.println("java library version is " + scope.getJavaLibraryVersion()); Assert.assertTrue( scope.isJava18Libraries() || scope.isJava17Libraries() || scope.isJava16Libraries() || scope.isJava15Libraries() || scope.isJava14Libraries()); } }
1,688
34.1875
95
java
WALA
WALA-master/core/src/test/java/com/ibm/wala/core/tests/cha/MissingMethodRefTest.java
/* * Copyright (c) 2008 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package com.ibm.wala.core.tests.cha; import com.ibm.wala.core.tests.callGraph.CallGraphTestUtil; import com.ibm.wala.core.tests.util.TestConstants; import com.ibm.wala.core.tests.util.WalaTestCase; import com.ibm.wala.core.util.config.AnalysisScopeReader; import com.ibm.wala.core.util.io.FileProvider; import com.ibm.wala.ipa.callgraph.AnalysisCacheImpl; import com.ibm.wala.ipa.callgraph.AnalysisOptions; import com.ibm.wala.ipa.callgraph.AnalysisScope; import com.ibm.wala.ipa.callgraph.Entrypoint; import com.ibm.wala.ipa.cha.ClassHierarchy; import com.ibm.wala.ipa.cha.ClassHierarchyException; import com.ibm.wala.ipa.cha.ClassHierarchyFactory; import com.ibm.wala.util.CancelException; import java.io.IOException; import org.junit.Test; public class MissingMethodRefTest extends WalaTestCase { /** Test handling of a method reference to a method that is missing */ @Test public void testMissingMethodRef() throws IOException, ClassHierarchyException, CancelException { AnalysisScope scope = AnalysisScopeReader.instance.readJavaScope( TestConstants.WALA_TESTDATA, new FileProvider().getFile("J2SEClassHierarchyExclusions.txt"), DupFieldsTest.class.getClassLoader()); ClassHierarchy cha = ClassHierarchyFactory.make(scope); Iterable<Entrypoint> entrypoints = com.ibm.wala.ipa.callgraph.impl.Util.makeMainEntrypoints(cha, "LMissingMethodRef"); AnalysisOptions options = CallGraphTestUtil.makeAnalysisOptions(scope, entrypoints); // should not throw an NPE CallGraphTestUtil.buildZeroCFA(options, new AnalysisCacheImpl(), cha, false); } }
1,999
39.816327
99
java
WALA
WALA-master/core/src/test/java/com/ibm/wala/core/tests/cha/MissingSuperTest.java
/* * Copyright (c) 2008 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package com.ibm.wala.core.tests.cha; import com.ibm.wala.classLoader.IClass; import com.ibm.wala.classLoader.IMethod; import com.ibm.wala.classLoader.PhantomClass; import com.ibm.wala.core.tests.util.TestConstants; import com.ibm.wala.core.tests.util.WalaTestCase; import com.ibm.wala.core.util.config.AnalysisScopeReader; import com.ibm.wala.core.util.io.FileProvider; import com.ibm.wala.ipa.callgraph.AnalysisCacheImpl; import com.ibm.wala.ipa.callgraph.AnalysisScope; import com.ibm.wala.ipa.callgraph.IAnalysisCacheView; import com.ibm.wala.ipa.cha.ClassHierarchy; import com.ibm.wala.ipa.cha.ClassHierarchyException; import com.ibm.wala.ipa.cha.ClassHierarchyFactory; import com.ibm.wala.types.ClassLoaderReference; import com.ibm.wala.types.TypeReference; import java.io.IOException; import java.util.Collection; import org.junit.Assert; import org.junit.Test; public class MissingSuperTest extends WalaTestCase { /** * Test handling of an invalid class where a non-abstract method has no code. We want to throw an * exception rather than crash. */ @Test public void testMissingSuper() throws IOException, ClassHierarchyException { AnalysisScope scope = AnalysisScopeReader.instance.readJavaScope( TestConstants.WALA_TESTDATA, new FileProvider().getFile("J2SEClassHierarchyExclusions.txt"), MissingSuperTest.class.getClassLoader()); TypeReference ref = TypeReference.findOrCreate(ClassLoaderReference.Application, "Lmissingsuper/MissingSuper"); // without phantom classes, won't be able to resolve ClassHierarchy cha = ClassHierarchyFactory.make(scope); Assert.assertNull("lookup should not work", cha.lookupClass(ref)); // with makeWithRoot lookup should succeed and // unresolvable super class "Super" should be replaced by hierarchy root cha = ClassHierarchyFactory.makeWithRoot(scope); IClass klass = cha.lookupClass(ref); Assert.assertNotNull("expected class MissingSuper to load", klass); Assert.assertEquals(cha.getRootClass(), klass.getSuperclass()); // with phantom classes, lookup and IR construction should work cha = ClassHierarchyFactory.makeWithPhantom(scope); klass = cha.lookupClass(ref); Assert.assertNotNull("expected class MissingSuper to load", klass); IAnalysisCacheView cache = new AnalysisCacheImpl(); Collection<? extends IMethod> declaredMethods = klass.getDeclaredMethods(); Assert.assertEquals(declaredMethods.toString(), 2, declaredMethods.size()); for (IMethod m : declaredMethods) { // should succeed cache.getIR(m); } // there should be one PhantomClass in the Application class loader boolean found = false; for (IClass klass2 : cha) { if (klass2 instanceof PhantomClass && klass2.getReference().getClassLoader().equals(ClassLoaderReference.Application)) { Assert.assertEquals("Lmissingsuper/Super", klass2.getReference().getName().toString()); found = true; } } Assert.assertTrue(found); } }
3,426
39.797619
99
java
WALA
WALA-master/core/src/test/java/com/ibm/wala/core/tests/cha/SourceMapTest.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.cha; import com.ibm.wala.classLoader.BytecodeClass; import com.ibm.wala.classLoader.IClass; import com.ibm.wala.classLoader.Module; import com.ibm.wala.core.tests.util.TestConstants; import com.ibm.wala.core.tests.util.WalaTestCase; import com.ibm.wala.core.util.config.AnalysisScopeReader; import com.ibm.wala.ipa.callgraph.AnalysisScope; import com.ibm.wala.ipa.cha.ClassHierarchy; import com.ibm.wala.ipa.cha.ClassHierarchyException; import com.ibm.wala.ipa.cha.ClassHierarchyFactory; import com.ibm.wala.types.TypeReference; import java.io.IOException; import org.junit.Assert; import org.junit.Test; /** A test of support for source file mapping */ public class SourceMapTest extends WalaTestCase { private static final ClassLoader MY_CLASSLOADER = SourceMapTest.class.getClassLoader(); private static final String CLASS_IN_PRIMORDIAL_JAR = "Lcom/ibm/wala/model/SyntheticFactory"; @Test public void testHello() throws ClassHierarchyException, IOException { AnalysisScope scope = AnalysisScopeReader.instance.readJavaScope(TestConstants.HELLO, null, MY_CLASSLOADER); // TODO: it's annoying to have to build a class hierarchy here. // see feature 38676 ClassHierarchy cha = ClassHierarchyFactory.make(scope); TypeReference t = TypeReference.findOrCreate(scope.getApplicationLoader(), TestConstants.HELLO_MAIN); IClass klass = cha.lookupClass(t); Assert.assertNotNull("failed to load " + t, klass); String sourceFile = klass.getSourceFileName(); System.err.println("Source file: " + sourceFile); Assert.assertNotNull(sourceFile); } @Test public void testFromJar() throws ClassHierarchyException, IOException { AnalysisScope scope = AnalysisScopeReader.instance.readJavaScope(TestConstants.HELLO, null, MY_CLASSLOADER); // TODO: it's annoying to have to build a class hierarchy here. // open a feature to fix this ClassHierarchy cha = ClassHierarchyFactory.make(scope); TypeReference t = TypeReference.findOrCreate(scope.getPrimordialLoader(), CLASS_IN_PRIMORDIAL_JAR); IClass klass = cha.lookupClass(t); Assert.assertNotNull(klass); String sourceFile = klass.getSourceFileName(); Assert.assertNotNull(sourceFile); System.err.println("Source file: " + sourceFile); Module container = ((BytecodeClass<?>) klass).getContainer(); Assert.assertNotNull(container); System.err.println("container: " + container); } }
2,866
39.380282
95
java
WALA
WALA-master/core/src/test/java/com/ibm/wala/core/tests/collections/SemiSparseMutableIntSetTest.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 */ /* * Licensed Materials - Property of IBM * 5724-D15 * (C) Copyright IBM Corporation 2008-2009. All Rights Reserved. * Note to U.S. Government Users Restricted Rights: * Use, duplication or disclosure restricted by GSA ADP Schedule Contract with IBM Corp. */ package com.ibm.wala.core.tests.collections; import com.ibm.wala.core.tests.util.WalaTestCase; import com.ibm.wala.util.intset.SemiSparseMutableIntSet; import org.junit.Test; /** * Tests {@link SemiSparseMutableIntSet} class. * * @author egeay */ public final class SemiSparseMutableIntSetTest extends WalaTestCase { public static void main(final String[] args) { justThisTest(SemiSparseMutableIntSetTest.class); } // --- Test cases @Test public void testCase1() { final SemiSparseMutableIntSet ssmIntSet = new SemiSparseMutableIntSet(); ssmIntSet.add(1); final SemiSparseMutableIntSet ssmIntSet2 = SemiSparseMutableIntSet.diff(ssmIntSet, ssmIntSet); ssmIntSet2.max(); } }
1,356
28.5
98
java
WALA
WALA-master/core/src/test/java/com/ibm/wala/core/tests/collections/TwoLevelVectorTest.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 */ /* * Licensed Materials - Property of IBM * 5724-D15 * (C) Copyright IBM Corporation 2008-2009. All Rights Reserved. * Note to U.S. Government Users Restricted Rights: * Use, duplication or disclosure restricted by GSA ADP Schedule Contract with IBM Corp. */ package com.ibm.wala.core.tests.collections; import com.ibm.wala.core.tests.util.WalaTestCase; import com.ibm.wala.util.collections.TwoLevelVector; import java.util.Iterator; import org.junit.Assert; import org.junit.Test; /** * Tests {@link TwoLevelVector} class. * * @author egeay */ public final class TwoLevelVectorTest extends WalaTestCase { public static void main(final String[] args) { justThisTest(TwoLevelVectorTest.class); } // --- Test cases @Test public void testCase1() { final TwoLevelVector<Integer> tlVector = new TwoLevelVector<>(); Iterator<Integer> ignored = tlVector.iterator(); tlVector.set(2147483647, 56); Assert.assertNotNull(tlVector.iterator()); Assert.assertEquals(Integer.valueOf(56), tlVector.get(2147483647)); } }
1,432
28.244898
89
java
WALA
WALA-master/core/src/test/java/com/ibm/wala/core/tests/demandpa/AbstractPtrTest.java
/* * This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html. * * This file is a derivative of code released by the University of * California under the terms listed below. * * Refinement Analysis Tools is Copyright (c) 2007 The Regents of the * University of California (Regents). Provided that this notice and * the following two paragraphs are included in any distribution of * Refinement Analysis Tools or its derivative work, Regents agrees * not to assert any of Regents' copyright rights in Refinement * Analysis Tools against recipient for recipient's reproduction, * preparation of derivative works, public display, public * performance, distribution or sublicensing of Refinement Analysis * Tools and derivative works, in source code and object code form. * This agreement not to assert does not confer, by implication, * estoppel, or otherwise any license or rights in any intellectual * property of Regents, including, but not limited to, any patents * of Regents or Regents' employees. * * IN NO EVENT SHALL REGENTS BE LIABLE TO ANY PARTY FOR DIRECT, * INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, * INCLUDING LOST PROFITS, ARISING OUT OF THE USE OF THIS SOFTWARE * AND ITS DOCUMENTATION, EVEN IF REGENTS HAS BEEN ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * REGENTS SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE AND FURTHER DISCLAIMS ANY STATUTORY * WARRANTY OF NON-INFRINGEMENT. THE SOFTWARE AND ACCOMPANYING * DOCUMENTATION, IF ANY, PROVIDED HEREUNDER IS PROVIDED "AS * IS". REGENTS HAS NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, * UPDATES, ENHANCEMENTS, OR MODIFICATIONS. */ package com.ibm.wala.core.tests.demandpa; import com.ibm.wala.classLoader.IClass; import com.ibm.wala.classLoader.Language; import com.ibm.wala.classLoader.NewSiteReference; import com.ibm.wala.core.tests.callGraph.CallGraphTestUtil; import com.ibm.wala.core.util.strings.Atom; import com.ibm.wala.core.util.strings.StringStuff; import com.ibm.wala.demandpa.alg.DemandRefinementPointsTo; import com.ibm.wala.demandpa.alg.refinepolicy.NeverRefineCGPolicy; import com.ibm.wala.demandpa.alg.refinepolicy.OnlyArraysPolicy; import com.ibm.wala.demandpa.alg.refinepolicy.SinglePassRefinementPolicy; import com.ibm.wala.demandpa.alg.statemachine.DummyStateMachine; import com.ibm.wala.demandpa.alg.statemachine.StateMachineFactory; import com.ibm.wala.demandpa.flowgraph.IFlowLabel; import com.ibm.wala.demandpa.util.MemoryAccessMap; import com.ibm.wala.demandpa.util.PABasedMemoryAccessMap; import com.ibm.wala.ipa.callgraph.AnalysisCacheImpl; import com.ibm.wala.ipa.callgraph.AnalysisOptions; import com.ibm.wala.ipa.callgraph.AnalysisScope; import com.ibm.wala.ipa.callgraph.CGNode; import com.ibm.wala.ipa.callgraph.CallGraph; import com.ibm.wala.ipa.callgraph.CallGraphBuilder; import com.ibm.wala.ipa.callgraph.Entrypoint; import com.ibm.wala.ipa.callgraph.IAnalysisCacheView; import com.ibm.wala.ipa.callgraph.impl.Util; import com.ibm.wala.ipa.callgraph.propagation.HeapModel; import com.ibm.wala.ipa.callgraph.propagation.InstanceKey; import com.ibm.wala.ipa.callgraph.propagation.PointerKey; import com.ibm.wala.ipa.callgraph.propagation.SSAPropagationCallGraphBuilder; import com.ibm.wala.ipa.cha.ClassHierarchyException; import com.ibm.wala.ipa.cha.ClassHierarchyFactory; import com.ibm.wala.ipa.cha.IClassHierarchy; import com.ibm.wala.ssa.IR; import com.ibm.wala.ssa.SSAInstruction; import com.ibm.wala.ssa.SSAInvokeInstruction; import com.ibm.wala.types.ClassLoaderReference; import com.ibm.wala.types.Descriptor; import com.ibm.wala.types.TypeReference; import com.ibm.wala.util.CancelException; import com.ibm.wala.util.collections.Iterator2Iterable; import com.ibm.wala.util.debug.Assertions; import com.ibm.wala.util.intset.IntSet; import java.io.IOException; import java.util.Collection; import org.junit.AfterClass; import org.junit.Assert; public abstract class AbstractPtrTest { protected boolean debug = false; /** file holding analysis scope specification */ protected final String scopeFile; protected AbstractPtrTest(String scopeFile) { this.scopeFile = scopeFile; } private static AnalysisScope cachedScope; private static IClassHierarchy cachedCHA; public static CGNode findMainMethod(CallGraph cg) { Descriptor d = Descriptor.findOrCreateUTF8("([Ljava/lang/String;)V"); Atom name = Atom.findOrCreateUnicodeAtom("main"); for (CGNode n : Iterator2Iterable.make(cg.getSuccNodes(cg.getFakeRootNode()))) { if (n.getMethod().getName().equals(name) && n.getMethod().getDescriptor().equals(d)) { return n; } } Assertions.UNREACHABLE("failed to find method"); return null; } public static CGNode findStaticMethod(CallGraph cg, Atom name, Descriptor args) { for (CGNode n : cg) { // System.err.println(n.getMethod().getName() + " " + // n.getMethod().getDescriptor()); if (n.getMethod().getName().equals(name) && n.getMethod().getDescriptor().equals(args)) { return n; } } Assertions.UNREACHABLE("failed to find method"); return null; } public static CGNode findInstanceMethod( CallGraph cg, IClass declaringClass, Atom name, Descriptor args) { for (CGNode n : cg) { // System.err.println(n.getMethod().getDeclaringClass() + " " + // n.getMethod().getName() + " " + n.getMethod().getDescriptor()); if (n.getMethod().getDeclaringClass().equals(declaringClass) && n.getMethod().getName().equals(name) && n.getMethod().getDescriptor().equals(args)) { return n; } } Assertions.UNREACHABLE("failed to find method"); return null; } public static PointerKey getParam(CGNode n, String methodName, HeapModel heapModel) { IR ir = n.getIR(); for (SSAInstruction s : Iterator2Iterable.make(ir.iterateAllInstructions())) { if (s instanceof SSAInvokeInstruction) { SSAInvokeInstruction call = (SSAInvokeInstruction) s; if (call.getCallSite().getDeclaredTarget().getName().toString().equals(methodName)) { IntSet indices = ir.getCallInstructionIndices(((SSAInvokeInstruction) s).getCallSite()); Assertions.productionAssertion( indices.size() == 1, "expected 1 but got " + indices.size()); SSAInstruction callInstr = ir.getInstructions()[indices.intIterator().next()]; Assertions.productionAssertion( callInstr.getNumberOfUses() == 1, "multiple uses for call"); return heapModel.getPointerKeyForLocal(n, callInstr.getUse(0)); } } } Assertions.UNREACHABLE("failed to find call to " + methodName + " in " + n); return null; } protected void doFlowsToSizeTest(String mainClass, int size) throws ClassHierarchyException, IllegalArgumentException, CancelException, IOException { Collection<PointerKey> flowsTo = getFlowsToSetToTest(mainClass); if (debug) { System.err.println("flows-to for " + mainClass + ": " + flowsTo); } Assert.assertEquals(size, flowsTo.size()); } private Collection<PointerKey> getFlowsToSetToTest(String mainClass) throws ClassHierarchyException, IllegalArgumentException, CancelException, IOException { final DemandRefinementPointsTo dmp = makeDemandPointerAnalysis(mainClass); // find the single allocation site of FlowsToType, make an InstanceKey, and // query it CGNode mainMethod = AbstractPtrTest.findMainMethod(dmp.getBaseCallGraph()); InstanceKey keyToQuery = getFlowsToInstanceKey(mainMethod, dmp.getHeapModel()); Collection<PointerKey> flowsTo = dmp.getFlowsTo(keyToQuery).snd; return flowsTo; } /** returns the instance key corresponding to the single allocation site of type FlowsToType */ private InstanceKey getFlowsToInstanceKey(CGNode mainMethod, HeapModel heapModel) { // TODO Auto-generated method stub TypeReference flowsToTypeRef = TypeReference.findOrCreate( ClassLoaderReference.Application, StringStuff.deployment2CanonicalTypeString("demandpa.FlowsToType")); final IR mainIR = mainMethod.getIR(); if (debug) { System.err.println(mainIR); } for (NewSiteReference n : Iterator2Iterable.make(mainIR.iterateNewSites())) { if (n.getDeclaredType().equals(flowsToTypeRef)) { return heapModel.getInstanceKeyForAllocation(mainMethod, n); } } assert false : "could not find appropriate allocation"; return null; } protected void doPointsToSizeTest(String mainClass, int expectedSize) throws ClassHierarchyException, IllegalArgumentException, CancelException, IOException { Collection<InstanceKey> pointsTo = getPointsToSetToTest(mainClass); if (debug) { System.err.println("points-to for " + mainClass + ": " + pointsTo); } Assert.assertEquals(expectedSize, pointsTo.size()); } private Collection<InstanceKey> getPointsToSetToTest(String mainClass) throws ClassHierarchyException, IllegalArgumentException, CancelException, IOException { final DemandRefinementPointsTo dmp = makeDemandPointerAnalysis(mainClass); // find the testThisVar call, and check the parameter's points-to set CGNode mainMethod = AbstractPtrTest.findMainMethod(dmp.getBaseCallGraph()); PointerKey keyToQuery = AbstractPtrTest.getParam(mainMethod, "testThisVar", dmp.getHeapModel()); Collection<InstanceKey> pointsTo = dmp.getPointsTo(keyToQuery); return pointsTo; } protected DemandRefinementPointsTo makeDemandPointerAnalysis(String mainClass) throws ClassHierarchyException, IllegalArgumentException, CancelException, IOException { AnalysisScope scope = findOrCreateAnalysisScope(); // build a type hierarchy IClassHierarchy cha = findOrCreateCHA(scope); // set up call graph construction options; mainly what should be considered // entrypoints? Iterable<Entrypoint> entrypoints = com.ibm.wala.ipa.callgraph.impl.Util.makeMainEntrypoints(cha, mainClass); AnalysisOptions options = CallGraphTestUtil.makeAnalysisOptions(scope, entrypoints); final IAnalysisCacheView analysisCache = new AnalysisCacheImpl(); CallGraphBuilder<InstanceKey> cgBuilder = Util.makeZeroCFABuilder(Language.JAVA, options, analysisCache, cha); final CallGraph cg = cgBuilder.makeCallGraph(options, null); // System.err.println(cg.toString()); // MemoryAccessMap mam = new SimpleMemoryAccessMap(cg, // cgBuilder.getPointerAnalysis().getHeapModel(), false); MemoryAccessMap mam = new PABasedMemoryAccessMap(cg, cgBuilder.getPointerAnalysis()); SSAPropagationCallGraphBuilder builder = Util.makeVanillaZeroOneCFABuilder(Language.JAVA, options, analysisCache, cha); DemandRefinementPointsTo fullDemandPointsTo = DemandRefinementPointsTo.makeWithDefaultFlowGraph( cg, builder, mam, cha, options, getStateMachineFactory()); // always refine array fields; otherwise, can be very sensitive to differences // in library versions. otherwise, no refinement by default fullDemandPointsTo.setRefinementPolicyFactory( new SinglePassRefinementPolicy.Factory(new OnlyArraysPolicy(), new NeverRefineCGPolicy())); return fullDemandPointsTo; } private static IClassHierarchy findOrCreateCHA(AnalysisScope scope) throws ClassHierarchyException { if (cachedCHA == null) { cachedCHA = ClassHierarchyFactory.make(scope); } return cachedCHA; } private AnalysisScope findOrCreateAnalysisScope() throws IOException { if (cachedScope == null) { cachedScope = CallGraphTestUtil.makeJ2SEAnalysisScope( scopeFile, CallGraphTestUtil.REGRESSION_EXCLUSIONS); } return cachedScope; } @AfterClass public static void cleanup() { cachedScope = null; cachedCHA = null; } protected StateMachineFactory<IFlowLabel> getStateMachineFactory() { return new DummyStateMachine.Factory<>(); } }
12,282
42.556738
100
java
WALA
WALA-master/core/src/test/java/com/ibm/wala/core/tests/demandpa/ContextSensitiveTest.java
/* * This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html. * * This file is a derivative of code released by the University of * California under the terms listed below. * * Refinement Analysis Tools is Copyright (c) 2007 The Regents of the * University of California (Regents). Provided that this notice and * the following two paragraphs are included in any distribution of * Refinement Analysis Tools or its derivative work, Regents agrees * not to assert any of Regents' copyright rights in Refinement * Analysis Tools against recipient for recipient's reproduction, * preparation of derivative works, public display, public * performance, distribution or sublicensing of Refinement Analysis * Tools and derivative works, in source code and object code form. * This agreement not to assert does not confer, by implication, * estoppel, or otherwise any license or rights in any intellectual * property of Regents, including, but not limited to, any patents * of Regents or Regents' employees. * * IN NO EVENT SHALL REGENTS BE LIABLE TO ANY PARTY FOR DIRECT, * INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, * INCLUDING LOST PROFITS, ARISING OUT OF THE USE OF THIS SOFTWARE * AND ITS DOCUMENTATION, EVEN IF REGENTS HAS BEEN ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * REGENTS SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE AND FURTHER DISCLAIMS ANY STATUTORY * WARRANTY OF NON-INFRINGEMENT. THE SOFTWARE AND ACCOMPANYING * DOCUMENTATION, IF ANY, PROVIDED HEREUNDER IS PROVIDED "AS * IS". REGENTS HAS NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, * UPDATES, ENHANCEMENTS, OR MODIFICATIONS. */ package com.ibm.wala.core.tests.demandpa; import com.ibm.wala.core.util.strings.Atom; import com.ibm.wala.demandpa.alg.ContextSensitiveStateMachine; import com.ibm.wala.demandpa.alg.DemandRefinementPointsTo; import com.ibm.wala.demandpa.alg.IDemandPointerAnalysis; import com.ibm.wala.demandpa.alg.refinepolicy.AlwaysRefineCGPolicy; import com.ibm.wala.demandpa.alg.refinepolicy.AlwaysRefineFieldsPolicy; import com.ibm.wala.demandpa.alg.refinepolicy.SinglePassRefinementPolicy; import com.ibm.wala.demandpa.alg.statemachine.StateMachineFactory; import com.ibm.wala.demandpa.flowgraph.IFlowLabel; import com.ibm.wala.ipa.callgraph.CGNode; import com.ibm.wala.ipa.callgraph.propagation.InstanceKey; import com.ibm.wala.ipa.callgraph.propagation.PointerKey; import com.ibm.wala.ipa.cha.ClassHierarchyException; import com.ibm.wala.types.ClassLoaderReference; import com.ibm.wala.types.Descriptor; import com.ibm.wala.types.TypeReference; import com.ibm.wala.util.CancelException; import java.io.IOException; import java.util.Collection; import org.junit.Assert; import org.junit.Ignore; import org.junit.Test; public class ContextSensitiveTest extends AbstractPtrTest { public ContextSensitiveTest() { super(TestInfo.SCOPE_FILE); } @Test public void testArraySet() throws ClassHierarchyException, IllegalArgumentException, CancelException, IOException { doPointsToSizeTest(TestInfo.TEST_ARRAY_SET, 1); } @Test public void testClone() throws ClassHierarchyException, IllegalArgumentException, CancelException, IOException { doPointsToSizeTest(TestInfo.TEST_CLONE, 1); } @Test public void testFooId() throws ClassHierarchyException, IllegalArgumentException, CancelException, IOException { doPointsToSizeTest(TestInfo.TEST_ID, 1); } @Test public void testHashtableEnum() throws ClassHierarchyException, IllegalArgumentException, CancelException, IOException { // 3 because // can't tell between key and value enumerators in Hashtable doPointsToSizeTest(TestInfo.TEST_HASHTABLE_ENUM, 2); } @Ignore( "support for this combination of context sensitivity and on-the-fly call graph refinement is not yet implemented") @Test public void testOnTheFlyCS() throws ClassHierarchyException, IllegalArgumentException, CancelException, IOException { String mainClass = TestInfo.TEST_ONTHEFLY_CS; final IDemandPointerAnalysis dmp = makeDemandPointerAnalysis(mainClass); CGNode testMethod = AbstractPtrTest.findInstanceMethod( dmp.getBaseCallGraph(), dmp.getClassHierarchy() .lookupClass( TypeReference.findOrCreate( ClassLoaderReference.Application, "Ldemandpa/TestOnTheFlyCS$C2")), Atom.findOrCreateUnicodeAtom("doSomething"), Descriptor.findOrCreateUTF8("(Ljava/lang/Object;)V")); PointerKey keyToQuery = AbstractPtrTest.getParam(testMethod, "testThisVar", dmp.getHeapModel()); Collection<InstanceKey> pointsTo = dmp.getPointsTo(keyToQuery); if (debug) { System.err.println("points-to for " + mainClass + ": " + pointsTo); } Assert.assertEquals(1, pointsTo.size()); } @Test public void testWithinMethodCall() throws ClassHierarchyException, IllegalArgumentException, CancelException, IOException { String mainClass = TestInfo.TEST_WITHIN_METHOD_CALL; final IDemandPointerAnalysis dmp = makeDemandPointerAnalysis(mainClass); CGNode testMethod = AbstractPtrTest.findStaticMethod( dmp.getBaseCallGraph(), Atom.findOrCreateUnicodeAtom("testMethod"), Descriptor.findOrCreateUTF8("(Ljava/lang/Object;)V")); PointerKey keyToQuery = AbstractPtrTest.getParam(testMethod, "testThisVar", dmp.getHeapModel()); Collection<InstanceKey> pointsTo = dmp.getPointsTo(keyToQuery); if (debug) { System.err.println("points-to for " + mainClass + ": " + pointsTo); } Assert.assertEquals(1, pointsTo.size()); } @Test public void testLinkedListIter() throws ClassHierarchyException, IllegalArgumentException, CancelException, IOException { doPointsToSizeTest(TestInfo.TEST_LINKEDLIST_ITER, 1); } @Test public void testGlobal() throws ClassHierarchyException, IllegalArgumentException, CancelException, IOException { doPointsToSizeTest(TestInfo.TEST_GLOBAL, 1); } @Test public void testHashSet() throws ClassHierarchyException, IllegalArgumentException, CancelException, IOException { doPointsToSizeTest(TestInfo.TEST_HASH_SET, 1); } @Test public void testHashMapGet() throws ClassHierarchyException, IllegalArgumentException, CancelException, IOException { doPointsToSizeTest(TestInfo.TEST_HASHMAP_GET, 1); } @Test public void testMethodRecursion() throws ClassHierarchyException, IllegalArgumentException, CancelException, IOException { doPointsToSizeTest(TestInfo.TEST_METHOD_RECURSION, 2); } @Test public void testArraySetIter() throws ClassHierarchyException, IllegalArgumentException, CancelException, IOException { doPointsToSizeTest(TestInfo.TEST_ARRAY_SET_ITER, 1); } @Ignore @Test public void testArrayList() throws ClassHierarchyException, IllegalArgumentException, CancelException, IOException { doPointsToSizeTest(TestInfo.TEST_ARRAY_LIST, 1); } @Test public void testLinkedList() throws ClassHierarchyException, IllegalArgumentException, CancelException, IOException { doPointsToSizeTest(TestInfo.TEST_LINKED_LIST, 1); } @Test public void testFlowsToArraySetIter() throws ClassHierarchyException, IllegalArgumentException, CancelException, IOException { doFlowsToSizeTest(TestInfo.FLOWSTO_TEST_ARRAYSET_ITER, 7); } @Override protected StateMachineFactory<IFlowLabel> getStateMachineFactory() { return new ContextSensitiveStateMachine.Factory(); } @Override protected DemandRefinementPointsTo makeDemandPointerAnalysis(String mainClass) throws ClassHierarchyException, IllegalArgumentException, CancelException, IOException { DemandRefinementPointsTo dmp = super.makeDemandPointerAnalysis(mainClass); dmp.setRefinementPolicyFactory( new SinglePassRefinementPolicy.Factory( new AlwaysRefineFieldsPolicy(), new AlwaysRefineCGPolicy())); return dmp; } }
8,310
38.956731
120
java
WALA
WALA-master/core/src/test/java/com/ibm/wala/core/tests/demandpa/IntraprocTest.java
/* * This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html. * * This file is a derivative of code released by the University of * California under the terms listed below. * * Refinement Analysis Tools is Copyright (c) 2007 The Regents of the * University of California (Regents). Provided that this notice and * the following two paragraphs are included in any distribution of * Refinement Analysis Tools or its derivative work, Regents agrees * not to assert any of Regents' copyright rights in Refinement * Analysis Tools against recipient for recipient's reproduction, * preparation of derivative works, public display, public * performance, distribution or sublicensing of Refinement Analysis * Tools and derivative works, in source code and object code form. * This agreement not to assert does not confer, by implication, * estoppel, or otherwise any license or rights in any intellectual * property of Regents, including, but not limited to, any patents * of Regents or Regents' employees. * * IN NO EVENT SHALL REGENTS BE LIABLE TO ANY PARTY FOR DIRECT, * INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, * INCLUDING LOST PROFITS, ARISING OUT OF THE USE OF THIS SOFTWARE * AND ITS DOCUMENTATION, EVEN IF REGENTS HAS BEEN ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * REGENTS SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE AND FURTHER DISCLAIMS ANY STATUTORY * WARRANTY OF NON-INFRINGEMENT. THE SOFTWARE AND ACCOMPANYING * DOCUMENTATION, IF ANY, PROVIDED HEREUNDER IS PROVIDED "AS * IS". REGENTS HAS NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, * UPDATES, ENHANCEMENTS, OR MODIFICATIONS. */ package com.ibm.wala.core.tests.demandpa; import com.ibm.wala.classLoader.CallSiteReference; import com.ibm.wala.demandpa.alg.DemandRefinementPointsTo; import com.ibm.wala.demandpa.alg.DemandRefinementPointsTo.PointsToResult; import com.ibm.wala.demandpa.alg.IntraProcFilter; import com.ibm.wala.demandpa.alg.statemachine.StateMachineFactory; import com.ibm.wala.demandpa.flowgraph.IFlowLabel; import com.ibm.wala.ipa.callgraph.CGNode; import com.ibm.wala.ipa.callgraph.propagation.InstanceKey; import com.ibm.wala.ipa.callgraph.propagation.PointerKey; import com.ibm.wala.ipa.cha.ClassHierarchyException; import com.ibm.wala.ssa.IR; import com.ibm.wala.ssa.SSAAbstractInvokeInstruction; import com.ibm.wala.types.ClassLoaderReference; import com.ibm.wala.util.CancelException; import com.ibm.wala.util.collections.Pair; import java.io.IOException; import java.util.Collection; import java.util.Iterator; import org.junit.Test; public class IntraprocTest extends AbstractPtrTest { public IntraprocTest() { super(TestInfo.SCOPE_FILE); } @Test public void testId() throws ClassHierarchyException, IllegalArgumentException, CancelException, IOException { doPointsToSizeTest(TestInfo.TEST_ID, 0); } @Test public void testMissingClassMetadataRef() throws ClassHierarchyException, IllegalArgumentException, CancelException, IOException { DemandRefinementPointsTo drpt = makeDemandPointerAnalysis("Lmissingmetadata/MissingClassRef"); // find the call to toString() in the application code and make sure we can get the points-to // set for its receiver for (CGNode node : drpt.getBaseCallGraph()) { if (!node.getMethod() .getDeclaringClass() .getClassLoader() .getReference() .equals(ClassLoaderReference.Application)) { continue; } IR ir = node.getIR(); if (ir == null) continue; Iterator<CallSiteReference> callSites = ir.iterateCallSites(); while (callSites.hasNext()) { CallSiteReference site = callSites.next(); if (site.getDeclaredTarget().getName().toString().equals("toString")) { System.out.println(site + " in " + node); SSAAbstractInvokeInstruction[] calls = ir.getCalls(site); PointerKey pk = drpt.getHeapModel().getPointerKeyForLocal(node, calls[0].getUse(0)); Pair<PointsToResult, Collection<InstanceKey>> pointsTo = drpt.getPointsTo(pk, k -> true); System.out.println("POINTS TO RESULT: " + pointsTo); } } } } @Override protected StateMachineFactory<IFlowLabel> getStateMachineFactory() { return new IntraProcFilter.Factory(); } }
4,592
41.925234
99
java