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/core/util/ssa/TypeSafeInstructionFactory.java
/* * Copyright (c) 2002 - 2014 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ /* * Copyright (c) 2013, * Tobias Blaschke <code@tobiasblaschke.de> * All rights reserved. * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The names of the contributors may not be used to endorse or promote * products derived from this software without specific prior written * permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ package com.ibm.wala.core.util.ssa; import com.ibm.wala.classLoader.CallSiteReference; import com.ibm.wala.classLoader.JavaLanguage.JavaInstructionFactory; import com.ibm.wala.classLoader.NewSiteReference; import com.ibm.wala.ipa.cha.IClassHierarchy; import com.ibm.wala.shrike.shrikeBT.IConditionalBranchInstruction; import com.ibm.wala.shrike.shrikeBT.IInvokeInstruction; import com.ibm.wala.ssa.SSAAbstractInvokeInstruction; import com.ibm.wala.ssa.SSAArrayLoadInstruction; import com.ibm.wala.ssa.SSAArrayStoreInstruction; import com.ibm.wala.ssa.SSAConditionalBranchInstruction; import com.ibm.wala.ssa.SSAGetInstruction; import com.ibm.wala.ssa.SSAGotoInstruction; import com.ibm.wala.ssa.SSANewInstruction; import com.ibm.wala.ssa.SSAPhiInstruction; import com.ibm.wala.ssa.SSAPutInstruction; import com.ibm.wala.ssa.SSAReturnInstruction; import com.ibm.wala.types.FieldReference; import com.ibm.wala.types.MethodReference; import com.ibm.wala.types.TypeReference; import java.util.Collection; import java.util.Collections; import java.util.List; /** * Intended for SyntheticMethods, uses JavaInstructionFactory. * * <p>As the name states this SSAInstructionFactory does type checks. If they pass the actual * instructions are generated using the JavaInstructionFactory. * * <p>Obviously this factory is not complete yet. It's extended on demand. * * @see com.ibm.wala.classLoader.JavaLanguage.JavaInstructionFactory * @author Tobias Blaschke &lt;code@tobiasblaschke.de&gt; * @since 2013-10-20 */ public class TypeSafeInstructionFactory { private static final boolean DEBUG = false; protected final JavaInstructionFactory insts; protected final IClassHierarchy cha; public TypeSafeInstructionFactory(IClassHierarchy cha) { this.cha = cha; this.insts = new JavaInstructionFactory(); } /** * result = site(params). * * <p>Instruction that calls a method which has a return-value. * * <p>All parameters (but exception) are typechecked first. If the check passes they get unpacked * and handed over to the corresponding JavaInstructionFactory.InvokeInstruction. * * <p>Calls result.setAssigned() * * @see com.ibm.wala.classLoader.JavaLanguage.JavaInstructionFactory#InvokeInstruction(int, int, * int[], int, CallSiteReference, * com.ibm.wala.shrike.shrikeCT.BootstrapMethodsReader.BootstrapMethod) * @param iindex Zero or a positive number unique to any instruction of the same method * @param result Where to place the return-value of the called method. Is SSAValue.setAssigned() * automatically. * @param params Parameters to the call starting with the implicit this-pointer if necessary * @param exception An SSAValue receiving the exception-object when something in the method throws * unhandled * @param site The CallSiteReference to this call. */ public SSAAbstractInvokeInstruction InvokeInstruction( final int iindex, final SSAValue result, List<? extends SSAValue> params, final SSAValue exception, final CallSiteReference site) { info("Now: InvokeInstruction to {} using {}", site, params); if (iindex < 0) { throw new IllegalArgumentException("The iIndex may not be negative"); } if (result == null) { throw new IllegalArgumentException("The result may not be null"); } if (exception == null) { throw new IllegalArgumentException("The parameter exception may not be null"); } if (params == null) { params = Collections.emptyList(); } if (site == null) { throw new IllegalArgumentException("The CallSite may not be null"); } final ParameterAccessor acc = new ParameterAccessor(site.getDeclaredTarget(), this.cha); if (acc.hasImplicitThis()) { if (params.size() != (acc.getNumberOfParameters() + 1)) { throw new IllegalArgumentException( "The callee takes " + acc.getNumberOfParameters() + " + 1 (implicit this) " + "parameters. The given parameter-list has length " + params.size() + ". They are: " + params); } if (site.getInvocationCode() == IInvokeInstruction.Dispatch.STATIC) { // TODO use Dispatch.hasImplicitThis throw new IllegalArgumentException( "A function expecting an implicit this can not be invoked static."); } } else { if (params.size() != acc.getNumberOfParameters()) { throw new IllegalArgumentException( "The callee takes " + acc.getNumberOfParameters() + " parameters (no implicit this)." + "The given parameter-list has length " + params.size() + ". They are: " + params); } if (site.getInvocationCode() != IInvokeInstruction.Dispatch.STATIC) { throw new IllegalArgumentException( "A function without implicit this can only be invoked static."); } } // final MethodReference mRef = site.getDeclaredTarget(); // *********** // Params cosher, start typechecks { // Return-Value final TypeReference retType = acc.getReturnType(); if (!isAssignableFrom(retType, result.getType())) { throw new IllegalArgumentException( "The return-value does not stand the TypeCheck! " + retType + " is not assignable to " + result); } } final int[] aParams = new int[params.size()]; if (acc.hasImplicitThis()) { // Implicit This final SSAValue targetThis = acc.getThis(); final SSAValue givenThis = params.get(0); aParams[0] = givenThis.getNumber(); if (!isAssignableFrom(givenThis.getType(), targetThis.getType())) { throw new IllegalArgumentException( "Parameter 'this' is not assignable from\n\t" + givenThis + " to\n\t" + targetThis + "\n----------"); } for (int i = 1; i < params.size(); ++i) { // "regular" parameters final SSAValue givenParam = params.get(i); final SSAValue targetParam = acc.getParameter(i); aParams[i] = givenParam.getNumber(); if (!isAssignableFrom(givenParam.getType(), targetParam.getType())) { throw new IllegalArgumentException( "Parameter " + i + " is not assignable from " + givenParam + " to " + targetParam); } if (result.equals(givenParam)) { throw new IllegalArgumentException( result + " can't be the result and parameter " + i + " at the same time in " + site); } } } else { for (int i = 0; i < params.size(); ++i) { // "regular" parameters final SSAValue givenParam = params.get(i); final SSAValue targetParam = acc.getParameter(i + 1); aParams[i] = givenParam.getNumber(); if (!isAssignableFrom(givenParam.getType(), targetParam.getType())) { throw new IllegalArgumentException( "Parameter " + (i + 1) + " is not assignable from " + givenParam + " to " + targetParam + " in call " + site); } if (result.equals(givenParam)) { throw new IllegalArgumentException( result + " can't be the result and parameter " + i + " at the same time in " + site); } } } // TODO somehow check exception? result.setAssigned(); return insts.InvokeInstruction( iindex, result.getNumber(), aParams, exception.getNumber(), site, null); } /** * Instruction that calls a void-method. * * <p>All parameters (but exception) are typechecked first. If the check passes they get unpacked * and handed over to the corresponding JavaInstructionFactory.InvokeInstruction. * * @see com.ibm.wala.classLoader.JavaLanguage.JavaInstructionFactory#InvokeInstruction(int, int[], * int, CallSiteReference, * com.ibm.wala.shrike.shrikeCT.BootstrapMethodsReader.BootstrapMethod) * @param iindex Zero or a positive number unique to any instruction of the same method * @param params Parameters to the call starting with the implicit this-pointer if necessary * @param exception An SSAValue receiving the exception-object when something in the method throws * unhandled * @param site The CallSiteReference to this call. * @return the invocation instruction */ public SSAAbstractInvokeInstruction InvokeInstruction( final int iindex, List<? extends SSAValue> params, final SSAValue exception, final CallSiteReference site) { info("Now: InvokeInstruction to {} using {}", site, params); if (iindex < 0) { throw new IllegalArgumentException("The iIndex may not be negative"); } if (exception == null) { throw new IllegalArgumentException("The parameter exception may not be null"); } if (params == null) { params = Collections.emptyList(); } if (site == null) { throw new IllegalArgumentException("The CallSite may not be null"); } final ParameterAccessor acc = new ParameterAccessor(site.getDeclaredTarget(), this.cha); if (acc.hasImplicitThis()) { if (params.size() != (acc.getNumberOfParameters() + 1)) { throw new IllegalArgumentException( "The callee takes " + acc.getNumberOfParameters() + " + 1 (implicit this) " + "parameters. The given parameter-list has length " + params.size() + ". They are: " + params); } if (site.getInvocationCode() == IInvokeInstruction.Dispatch.STATIC) { // TODO use Dispatch.hasImplicitThis throw new IllegalArgumentException( "A function expecting an implicit this can not be invoked static."); } } else { if (params.size() != acc.getNumberOfParameters()) { throw new IllegalArgumentException( "The callee takes " + acc.getNumberOfParameters() + " parameters (no implicit this)." + "The given parameter-list has length " + params.size() + ". They are: " + params); } if (site.getInvocationCode() != IInvokeInstruction.Dispatch.STATIC) { throw new IllegalArgumentException( "A function without implicit this can only be invoked static."); } } final MethodReference mRef = site.getDeclaredTarget(); // *********** // Params cosher, start typechecks { // Return-Value if (acc.hasReturn()) { throw new IllegalArgumentException( "This InvokeInstruction only works on void-functions but " + mRef + " returns a value."); } } final int[] aParams = new int[params.size()]; if (acc.hasImplicitThis()) { // Implicit This // final SSAValue targetThis = acc.getThis(); final SSAValue givenThis = params.get(0); aParams[0] = givenThis.getNumber(); /*if (! isAssignableFrom(givenThis.getType(), targetThis.getType())) { throw new IllegalArgumentException("Parameter 'this' is not assignable from " + givenThis + " to " + targetThis); }*/ for (int i = 1; i < params.size(); ++i) { // "regular" parameters final SSAValue givenParam = params.get(i); final SSAValue targetParam = acc.getParameter(i); aParams[i] = givenParam.getNumber(); if (!isAssignableFrom(givenParam.getType(), targetParam.getType())) { throw new IllegalArgumentException( "Parameter " + i + " is not assignable from\n\t" + givenParam + " to\n\t" + targetParam + "\nin call " + site + "\n---------"); } } } else { for (int i = 0; i < params.size(); ++i) { // "regular" parameters final SSAValue givenParam = params.get(i); final SSAValue targetParam = acc.getParameter(i + 1); aParams[i] = givenParam.getNumber(); if (!isAssignableFrom(givenParam.getType(), targetParam.getType())) { throw new IllegalArgumentException( "Parameter " + (i + 1) + " is not assignable from " + givenParam + " to " + targetParam); } } } // TODO somehow check exception? return insts.InvokeInstruction(iindex, aParams, exception.getNumber(), site, null); } /** * Check if the type of the SSAValue is assignable to the return-value of the method it's valid * in. * * <p>If type check passes the corresponding ReturnInstruction of the JavaInstructionFactory is * called. * * @see com.ibm.wala.classLoader.JavaLanguage.JavaInstructionFactory#ReturnInstruction(int, int, * boolean) * @param iindex Zero or a positive number unique to any instruction of the same method * @param result SSAValue to return _with_ validIn _set_! * @throws IllegalArgumentException if result has no validIn set */ public SSAReturnInstruction ReturnInstruction(final int iindex, final SSAValue result) { info("Now: ReturnInstruction using {}", result); if (iindex < 0) { throw new IllegalArgumentException("iIndex may not be negative"); } if (!isAssignableFrom(result.getType(), result.getValidIn().getReturnType())) { throw new IllegalArgumentException( "Return type not assignable from " + result.getType() + " to " + result.getValidIn().getReturnType()); } return insts.ReturnInstruction(iindex, result.getNumber(), result.getType().isPrimitiveType()); } /** * targetValue = containingInstance.field. * * <p>Reads field from containingInstance into targetValue. If type check passes the corresponding * GetInstruction of the JavaInstructionFactory is called. Calls targetValue.setAssigned() * * @see com.ibm.wala.classLoader.JavaLanguage.JavaInstructionFactory#GetInstruction(int, int, int, * FieldReference) * @param iindex Zero or a positive number unique to any instruction of the same method * @param targetValue the result of the GetInstruction is placed there * @param containingInstance The Object instance to read the field from * @param field The description of the field */ public SSAGetInstruction GetInstruction( final int iindex, final SSAValue targetValue, final SSAValue containingInstance, FieldReference field) { info("Now: Get {} from {} into {}", field, containingInstance, targetValue); if (iindex < 0) { throw new IllegalArgumentException("iIndex may not be negative"); } if (targetValue == null) { throw new IllegalArgumentException("targetValue may not be null"); } if (containingInstance == null) { throw new IllegalArgumentException("containingInstance may not be null"); } if (field == null) { throw new IllegalArgumentException("field may not be null"); } if (!isSuperclassOf(field.getDeclaringClass(), containingInstance.getType())) { throw new IllegalArgumentException( "The targetInstance " + containingInstance + " is not equal or a " + " super-class of " + field.getDeclaringClass()); } if (!isAssignableFrom(field.getFieldType(), targetValue.getType())) { throw new IllegalArgumentException( "The field " + targetValue + " is not assignable from " + field); } final MethodReference targetValueValidIn = targetValue.getValidIn(); final MethodReference instValidIn = containingInstance.getValidIn(); if ((targetValueValidIn != null) && (instValidIn != null) && !targetValueValidIn.equals(instValidIn)) { throw new IllegalArgumentException( "containingInstance " + containingInstance + "and targetValue " + targetValue + " are valid in different scopes"); } targetValue.setAssigned(); return insts.GetInstruction( iindex, targetValue.getNumber(), containingInstance.getNumber(), field); } /** * Reads static field into targetValue. * * <p>If type check passes the corresponding GetInstruction of the JavaInstructionFactory is * called. Calls targetValue.setAssigned() * * @see com.ibm.wala.classLoader.JavaLanguage.JavaInstructionFactory#GetInstruction(int, int, int, * FieldReference) * @param iindex Zero or a positive number unique to any instruction of the same method * @param targetValue the result of the GetInstruction is placed there * @param field The description of the field */ public SSAGetInstruction GetInstruction( final int iindex, final SSAValue targetValue, FieldReference field) { info("Now: Get {} into {}", field, targetValue); if (iindex < 0) { throw new IllegalArgumentException("iIndex may not be negative"); } if (targetValue == null) { throw new IllegalArgumentException("targetValue may not be null"); } if (field == null) { throw new IllegalArgumentException("field may not be null"); } if (!isAssignableFrom(field.getFieldType(), targetValue.getType())) { throw new IllegalArgumentException( "The field " + targetValue + " is not assignable from " + field); } targetValue.setAssigned(); return insts.GetInstruction(iindex, targetValue.getNumber(), field); } /** * Writes newValue to field of targetInstance. * * <p>If type check passes the corresponding PutInstruction of the JavaInstructionFactory is * called. * * @see com.ibm.wala.classLoader.JavaLanguage.JavaInstructionFactory#PutInstruction(int, int, int, * FieldReference) * @param iindex Zero or a psitive number unique to any instruction of the same method * @param targetInstance the instance of the object to write a field of * @param newValue The value to write to the field * @param field The description of the target */ public SSAPutInstruction PutInstruction( final int iindex, final SSAValue targetInstance, final SSAValue newValue, FieldReference field) { info("Now: Put {} to {}", newValue, field); if (iindex < 0) { throw new IllegalArgumentException("iIndex may not be negative"); } if (targetInstance == null) { throw new IllegalArgumentException("targetInstance may not be null"); } if (newValue == null) { throw new IllegalArgumentException("newValue may not be null"); } if (field == null) { throw new IllegalArgumentException("field may not be null"); } if (!isSuperclassOf(field.getDeclaringClass(), targetInstance.getType())) { throw new IllegalArgumentException( "The targetInstance " + targetInstance + " is not equal or a " + " super-class of " + field.getDeclaringClass()); } if (!isAssignableFrom(newValue.getType(), field.getFieldType())) { throw new IllegalArgumentException( "The field " + field + " is not assignable from " + newValue); } final MethodReference newValueValidIn = newValue.getValidIn(); final MethodReference instValidIn = targetInstance.getValidIn(); if ((newValueValidIn != null) && (instValidIn != null) && !newValueValidIn.equals(instValidIn)) { throw new IllegalArgumentException( "targetInstance " + targetInstance + "and newValue " + newValue + " are valid in different scopes"); } return insts.PutInstruction(iindex, targetInstance.getNumber(), newValue.getNumber(), field); } /** * Writes newValue to static field. * * <p>If type check passes the corresponding PutInstruction of the JavaInstructionFactory is * called. * * @see com.ibm.wala.classLoader.JavaLanguage.JavaInstructionFactory#PutInstruction(int, int, int, * FieldReference) * @param iindex Zero or a psitive number unique to any instruction of the same method * @param newValue The value to write to the field * @param field The description of the target */ public SSAPutInstruction PutInstruction( final int iindex, final SSAValue newValue, FieldReference field) { info("Now: Put {} to {}", newValue, field); if (iindex < 0) { throw new IllegalArgumentException("iIndex may not be negative"); } if (newValue == null) { throw new IllegalArgumentException("newValue may not be null"); } if (field == null) { throw new IllegalArgumentException("field may not be null"); } if (!isAssignableFrom(newValue.getType(), field.getFieldType())) { throw new IllegalArgumentException( "The field " + field + " is not assignable from " + newValue); } // final MethodReference newValueValidIn = newValue.getValidIn(); return insts.PutInstruction(iindex, newValue.getNumber(), field); } public SSANewInstruction NewInstruction(int iindex, SSAValue result, NewSiteReference site) { info("Now: New {}", result); if (iindex < 0) { throw new IllegalArgumentException("iIndex may not be negative"); } if (result == null) { throw new IllegalArgumentException("result may not be null"); } if (site == null) { throw new IllegalArgumentException("site may not be null"); } if (!isAssignableFrom(site.getDeclaredType(), result.getType())) { throw new IllegalArgumentException("type mismatch"); } result.setAssigned(); return insts.NewInstruction(iindex, result.getNumber(), site); } public SSANewInstruction NewInstruction( int iindex, SSAValue result, NewSiteReference site, Collection<? extends SSAValue> params) { info("Now: New {}", result); if (iindex < 0) { throw new IllegalArgumentException("iIndex may not be negative"); } if (result == null) { throw new IllegalArgumentException("result may not be null"); } if (site == null) { throw new IllegalArgumentException("site may not be null"); } if (!isAssignableFrom(site.getDeclaredType(), result.getType())) { throw new IllegalArgumentException("type mismatch"); } final MethodReference resultValidIn = result.getValidIn(); final int[] aParams = new int[params.size()]; int i = 0; for (final SSAValue param : params) { final MethodReference paramValidIn = param.getValidIn(); if ((resultValidIn != null) && (paramValidIn != null) && !paramValidIn.equals(resultValidIn)) { throw new IllegalArgumentException( "The parameter " + param + " is valid in another scope than" + result); } aParams[i] = param.getNumber(); i++; } result.setAssigned(); return insts.NewInstruction(iindex, result.getNumber(), site, aParams); } /** * Combine SSA-Values into a newone. * * <p>If type check passes the corresponding PhiInstruction of the JavaInstructionFactory is * called. Calls result.setAssigned(). * * @see com.ibm.wala.classLoader.JavaLanguage.JavaInstructionFactory#PhiInstruction(int, int, * int[]) * @param iindex Zero or a positive number unique to any instruction of the same method * @param result Where to write result to * @param params at least one SSAValue to read from */ public SSAPhiInstruction PhiInstruction( int iindex, SSAValue result, Collection<? extends SSAValue> params) { info("Now: Phi into {} from {}", result, params); if (iindex < 0) { throw new IllegalArgumentException("iIndex may not be negative"); } if (result == null) { throw new IllegalArgumentException("result may not be null"); } if (params == null) { throw new IllegalArgumentException("params may not be null"); } if (params.size() < 1) { throw new IllegalArgumentException( "Phi needs at least one source value. Type is " + result.getType()); } final MethodReference resultValidIn = result.getValidIn(); final TypeReference resultType = result.getType(); final int[] aParams = new int[params.size()]; int i = 0; for (final SSAValue param : params) { final MethodReference paramValidIn = param.getValidIn(); if ((resultValidIn != null) && (paramValidIn != null) && !paramValidIn.equals(resultValidIn)) { throw new IllegalArgumentException( "The parameter " + param + " is valid in another scope than" + result); } if (!isAssignableFrom(param.getType(), resultType)) { throw new IllegalArgumentException("Param " + param + " is not assignable to " + result); } if (result.equals(param)) { throw new IllegalArgumentException("Cannot phi to myself: " + result); } aParams[i] = param.getNumber(); i++; // TODO: Assert no parameter appears twice } result.setAssigned(); return insts.PhiInstruction(iindex, result.getNumber(), aParams); } @SuppressWarnings("unused") private static boolean isSuperclassOf( final TypeReference superClass, final TypeReference subClass) { return true; // TODO } public boolean isAssignableFrom(final TypeReference from, final TypeReference to) { try { return ParameterAccessor.isAssignable(from, to, this.cha); } catch (ClassLookupException e) { return true; } } // ************ // Instructions simply handed through follow /** * Return from a void-function. * * <p>Handed through to JavaInstructionFactory directly (unless the iindex is negative). * * @param iindex Zero or a positive number unique to any instruction of the same method */ public SSAReturnInstruction ReturnInstruction(final int iindex) { if (iindex < 0) { throw new IllegalArgumentException("The iindex may not be negative"); } return insts.ReturnInstruction(iindex); } /** * Unconditionally jump to a (non-Phi) Instruction. * * @param target the iindex of the instruction to jump to */ public SSAGotoInstruction GotoInstruction(final int iindex, final int target) { if (iindex < 0) { throw new IllegalArgumentException("The iindex may not be negative"); } if (target < 0) { throw new IllegalArgumentException("The target-iindex may not be negative"); } return insts.GotoInstruction(iindex, target); } public SSAConditionalBranchInstruction ConditionalBranchInstruction( final int iindex, final IConditionalBranchInstruction.IOperator operator, final TypeReference type, final int val1, final int val2, final int target) { return insts.ConditionalBranchInstruction(iindex, operator, type, val1, val2, target); } /** * result = array[index]. * * <p>Load a a reference from an array. * * @param result The SSAValue to store the loaded stuff in * @param array The array to load from * @param index Te position in array to load from */ public SSAArrayLoadInstruction ArrayLoadInstruction( final int iindex, final SSAValue result, final SSAValue array, final int index) { if (iindex < 0) { throw new IllegalArgumentException("The iindex may not be negative. It's " + iindex); } if (result == null) { throw new IllegalArgumentException("Can't use null for the result"); } if (array == null) { throw new IllegalArgumentException("Can't load from array null"); } if (index < 0) { throw new IllegalArgumentException( "The index in the array may not be negative. It's " + index); } if (!array.getType().isArrayType()) { throw new IllegalArgumentException( "The array to read from is expected to be ... well ... an array. The given value was " + array); } final TypeReference innerType = array.getType().getArrayElementType(); if (!isAssignableFrom(innerType, result.getType())) { throw new IllegalArgumentException( "Can't assign from an array of " + innerType.getName() + " to " + result.getType().getName()); } result.setAssigned(); return insts.ArrayLoadInstruction( iindex, result.getNumber(), array.getNumber(), index, innerType); } /** * array[index] = value. * * <p>Save a value to a specific position in an Array. * * @param array the array to store to * @param index the position in the array to place value at * @param value The SSAValue to store in the array */ public SSAArrayStoreInstruction ArrayStoreInstruction( final int iindex, final SSAValue array, final int index, final SSAValue value) { if (iindex < 0) { throw new IllegalArgumentException("The iindex may not be negative. It's " + iindex); } if (value == null) { throw new IllegalArgumentException("Can't use null for the value to put"); } if (array == null) { throw new IllegalArgumentException("Can't write to array null"); } if (index < 0) { throw new IllegalArgumentException( "The index in the array may not be negative. It's " + index); } if (!array.getType().isArrayType()) { throw new IllegalArgumentException( "The array to write to is expected to be ... well ... an array. The given value was " + array); } final TypeReference innerType = array.getType().getArrayElementType(); if (!isAssignableFrom(value.getType(), innerType)) { throw new IllegalArgumentException( "Can't assign to an array of " + innerType.getName() + " from " + value.getType().getName()); } return insts.ArrayStoreInstruction( iindex, array.getNumber(), index, value.getNumber(), innerType); } private static void info(String s, Object... args) { if (DEBUG) { System.err.printf(s, args); } } }
32,499
36.185355
123
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/core/util/ssa/package-info.java
/* * Copyright (c) 2002 - 2014 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ /* * Copyright (c) 2013, * Tobias Blaschke <code@tobiasblaschke.de> * All rights reserved. * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The names of the contributors may not be used to endorse or promote * products derived from this software without specific prior written * permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ /** * A set of classes facilitating the construction of synthetic methods. * * <p>The usual methods of creating SummarizedMethods are error-prone and sometimes a bit * Inflexible. The tools provided in this package can be used to generate summarized methods in a * Type-Safe manner and assure all used methods are resolvable. * * <p>Needless to say that this method of generating synthetic methods is much slower than the * regular one. * * @since 2013-10-25 * @author Tobias Blaschke &lt;code@tobiasblaschke.de&gt; */ package com.ibm.wala.core.util.ssa;
2,513
43.105263
97
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/core/util/strings/Atom.java
/* * Copyright (c) 2002 - 2006 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package com.ibm.wala.core.util.strings; import com.ibm.wala.util.collections.HashMapFactory; import java.io.Serializable; import java.util.Arrays; import java.util.HashMap; /** * An utf8-encoded byte string. * * <p>Atom's are interned (canonicalized) so they may be compared for equality using the "==" * operator. * * <p>Atoms are used to represent names, descriptors, and string literals appearing in a class's * constant pool. */ public final class Atom implements Serializable { /* Serial version */ private static final long serialVersionUID = -3256390509887654329L; /** * Used to canonicalize Atoms, a mapping from AtomKey -&gt; Atom. AtomKeys are not canonical, but * Atoms are. */ private static final HashMap<AtomKey, Atom> dictionary = HashMapFactory.make(); /** The utf8 value this atom represents */ private final byte val[]; /** Cached hash code for this atom key. */ private final int hash; /** * Find or create an atom. * * @param str atom value, as string literal whose characters are unicode * @return atom */ public static Atom findOrCreateUnicodeAtom(String str) { byte[] utf8 = UTF8Convert.toUTF8(str); return findOrCreate(utf8); } /** * Find or create an atom. * * @param str atom value, as string literal whose characters are from ascii subset of unicode (not * including null) * @return atom * @throws IllegalArgumentException if str is null */ public static Atom findOrCreateAsciiAtom(String str) { if (str == null) { throw new IllegalArgumentException("str is null"); } byte[] ascii = str.getBytes(); return findOrCreate(ascii); } /** * Find or create an atom. * * @param utf8 atom value, as utf8 encoded bytes * @return atom * @throws IllegalArgumentException if utf8 is null */ public static Atom findOrCreateUtf8Atom(byte[] utf8) { if (utf8 == null) { throw new IllegalArgumentException("utf8 is null"); } return findOrCreate(utf8); } /** * create an Atom from utf8[off] of length len * * @throws IllegalArgumentException if utf8.length &lt;= off */ public static Atom findOrCreate(byte utf8[], int off, int len) throws IllegalArgumentException, IllegalArgumentException, IllegalArgumentException { if (utf8 == null) { throw new IllegalArgumentException("utf8 == null"); } if (len < 0) { throw new IllegalArgumentException("len must be >= 0, " + len); } if (off < 0) { throw new IllegalArgumentException("off must be >= 0, " + off); } if (utf8.length < off + len) { throw new IllegalArgumentException("utf8.length < off + len"); } if (off + len < 0) { throw new IllegalArgumentException("off + len is too big: " + off + " + " + len); } byte val[] = new byte[len]; for (int i = 0; i < len; ++i) { val[i] = utf8[off++]; } return findOrCreate(val); } public static synchronized Atom findOrCreate(byte[] bytes) { if (bytes == null) { throw new IllegalArgumentException("bytes is null"); } AtomKey key = new AtomKey(bytes); Atom val = dictionary.get(key); if (val != null) { return val; } val = new Atom(key); dictionary.put(key, val); return val; } public static synchronized Atom findOrCreate(ImmutableByteArray b) { if (b == null) { throw new IllegalArgumentException("b is null"); } return findOrCreate(b.b); } public static synchronized Atom findOrCreate(ImmutableByteArray b, int start, int length) { if (b == null) { throw new IllegalArgumentException("b is null"); } return findOrCreate(b.b, start, length); } /** Return printable representation of "this" atom. Does not correctly handle UTF8 translation. */ @Override public String toString() { return new String(val); } /** Return printable representation of "this" atom. */ public String toUnicodeString() throws java.io.UTFDataFormatException { return UTF8Convert.fromUTF8(val); } /** New Atom containing first count bytes */ public Atom left(int count) { return findOrCreate(val, 0, count); } /** New Atom containing last count bytes */ public Atom right(int count) { return findOrCreate(val, val.length - count, count); } public boolean startsWith(Atom start) { assert (start != null); // can't start with something that's longer. if (val.length < start.val.length) return false; // otherwise, we know that this length is greater than or equal to the length of start. for (int i = 0; i < start.val.length; ++i) { if (val[i] != start.val[i]) return false; } return true; } /** * Return array descriptor corresponding to "this" array-element descriptor. this: array-element * descriptor - something like "I" or "Ljava/lang/Object;" * * @return array descriptor - something like "[I" or "[Ljava/lang/Object;" */ public Atom arrayDescriptorFromElementDescriptor() { byte sig[] = new byte[1 + val.length]; sig[0] = (byte) '['; for (int i = 0, n = val.length; i < n; ++i) sig[i + 1] = val[i]; return findOrCreate(sig); } /** * Is "this" atom a reserved member name? Note: Sun has reserved all member names starting with * '&lt;' for future use. At present, only &lt;init&gt; and &lt;clinit&gt; are used. */ public boolean isReservedMemberName() { if (length() == 0) { return false; } return val[0] == '<'; } /** Is "this" atom a class descriptor? */ public boolean isClassDescriptor() { if (length() == 0) { return false; } return val[0] == 'L'; } /** Is "this" atom an array descriptor? */ public boolean isArrayDescriptor() { if (length() == 0) { return false; } return val[0] == '['; } /** Is "this" atom a method descriptor? */ public boolean isMethodDescriptor() throws IllegalArgumentException { if (length() == 0) { return false; } return val[0] == '('; } public int length() { return val.length; } /** Create atom from given utf8 sequence. */ private Atom(AtomKey key) { this.val = key.val; this.hash = key.hash; } /** * Parse "this" array descriptor to obtain descriptor for array's element type. this: array * descriptor - something like "[I" * * @return array element descriptor - something like "I" */ public Atom parseForArrayElementDescriptor() throws IllegalArgumentException { if (val.length == 0) { throw new IllegalArgumentException("empty atom is not an array"); } return findOrCreate(val, 1, val.length - 1); } /** * Parse "this" array descriptor to obtain number of dimensions in corresponding array type. this: * descriptor - something like "[Ljava/lang/String;" or "[[I" * * @return dimensionality - something like "1" or "2" * @throws IllegalStateException if this Atom does not represent an array */ public int parseForArrayDimensionality() throws IllegalArgumentException { if (val.length == 0) { throw new IllegalArgumentException("empty atom is not an array"); } try { for (int i = 0; ; ++i) { if (val[i] != '[') { return i; } } } catch (ArrayIndexOutOfBoundsException e) { throw new IllegalStateException("not an array: " + this, e); } } /** * Return the innermost element type reference for an array * * @throws IllegalStateException if this Atom does not represent an array descriptor */ public Atom parseForInnermostArrayElementDescriptor() throws IllegalArgumentException { if (val.length == 0) { throw new IllegalArgumentException("empty atom is not an array"); } try { int i = 0; while (val[i] == '[') { i++; } return findOrCreate(val, i, val.length - i); } catch (ArrayIndexOutOfBoundsException e) { throw new IllegalStateException("not an array: " + this, e); } } /** key for the dictionary. */ private static final class AtomKey { /** The utf8 value this atom key represents */ private final byte val[]; /** Cached hash code for this atom key. */ private final int hash; /** Create atom from given utf8 sequence. */ private AtomKey(byte utf8[]) { int tmp = 99989; for (int i = utf8.length; --i >= 0; ) { tmp = 99991 * tmp + utf8[i]; } this.val = utf8; this.hash = tmp; } @Override public boolean equals(Object other) { assert (other != null && this.getClass().equals(other.getClass())); if (this == other) { return true; } AtomKey that = (AtomKey) other; if (hash != that.hash) return false; if (val.length != that.val.length) return false; for (int i = 0; i < val.length; i++) { if (val[i] != that.val[i]) return false; } return true; } /** * Return printable representation of "this" atom. Does not correctly handle UTF8 translation. */ @Override public String toString() { return new String(val); } @Override public int hashCode() { return hash; } } @Override public int hashCode() { return hash; } /* * These are canonical * * @see java.lang.Object#equals(java.lang.Object) */ @Override public boolean equals(Object obj) { return this == obj; } /** return an array of bytes representing the utf8 characters in this */ public byte[] getValArray() { return val.clone(); } public byte getVal(int i) throws IllegalArgumentException { try { return val[i]; } catch (ArrayIndexOutOfBoundsException e) { throw new IllegalArgumentException("Illegal index: " + i + " length is " + val.length, e); } } /** @return true iff this atom contains the specified byte */ public boolean contains(byte b) { for (byte element : val) { if (element == b) { return true; } } return false; } public int rIndex(byte b) { for (int i = val.length - 1; i >= 0; --i) { if (val[i] == b) { return val.length - i; } } return -1; } private static Atom concat(byte c, byte[] bs) { byte[] val = new byte[bs.length + 1]; val[0] = c; System.arraycopy(bs, 0, val, 1, bs.length); return findOrCreate(val); } public static Atom concat(byte c, ImmutableByteArray b) { if (b == null) { throw new IllegalArgumentException("b is null"); } return concat(c, b.b); } public static Atom concat(Atom ma, Atom mb) { if ((ma == null) || (mb == null)) { throw new IllegalArgumentException("argument may not be null!"); } byte[] val = Arrays.copyOf(ma.val, ma.val.length + mb.val.length); System.arraycopy(mb.val, 0, val, ma.val.length, mb.val.length); return findOrCreate(val); } public static boolean isArrayDescriptor(ImmutableByteArray b) { if (b == null) { throw new IllegalArgumentException("b is null"); } if (b.length() == 0) { return false; } return b.get(0) == '['; } /** * Special method that is called by Java deserialization process. Any HashCons'ed object should * implement it, in order to make sure that all equal objects are consolidated. */ private Object readResolve() { return findOrCreate(this.val); } }
11,828
26.445476
100
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/core/util/strings/ImmutableByteArray.java
/* * Copyright (c) 2002 - 2006 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package com.ibm.wala.core.util.strings; /** A read-only byte array. */ public final class ImmutableByteArray { // allow "friends" in this package to access final byte[] b; public ImmutableByteArray(byte[] b) { if (b == null) { throw new IllegalArgumentException("b is null"); } this.b = b; } public ImmutableByteArray(byte[] b, int start, int length) { if (b == null) { throw new IllegalArgumentException("b is null"); } if (start < 0) { throw new IllegalArgumentException("invalid start: " + start); } if (length < 0) { throw new IllegalArgumentException("null length"); } this.b = new byte[length]; try { System.arraycopy(b, start, this.b, 0, length); } catch (ArrayIndexOutOfBoundsException e) { throw new IllegalArgumentException( "illegal parameters " + b.length + ' ' + start + ' ' + length, e); } } public int length() { return b.length; } public byte get(int i) throws IllegalArgumentException { if (i < 0 || i >= b.length) { throw new IllegalArgumentException("index out of bounds " + b.length + ' ' + i); } return b[i]; } public byte[] substring(int i, int length) { if (length < 0) { throw new IllegalArgumentException("illegal length: " + length); } if (i < 0) { throw new IllegalArgumentException("illegal i: " + i); } byte[] result = new byte[length]; try { System.arraycopy(b, i, result, 0, length); } catch (ArrayIndexOutOfBoundsException e) { throw new IllegalArgumentException("Invalid combination: " + i + ' ' + length, e); } return result; } public static ImmutableByteArray concat(byte b, ImmutableByteArray b1) { if (b1 == null) { throw new IllegalArgumentException("b1 is null"); } byte[] arr = new byte[b1.length() + 1]; arr[0] = b; System.arraycopy(b1.b, 0, arr, 1, b1.b.length); return new ImmutableByteArray(arr); } @Override public String toString() { return new String(b); } public static ImmutableByteArray make(String s) { return new ImmutableByteArray(UTF8Convert.toUTF8(s)); } }
2,553
27.065934
88
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/core/util/strings/StringStuff.java
/* * Copyright (c) 2002 - 2006 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package com.ibm.wala.core.util.strings; import static com.ibm.wala.types.TypeName.ArrayMask; import static com.ibm.wala.types.TypeName.ElementBits; import static com.ibm.wala.types.TypeName.PointerMask; import static com.ibm.wala.types.TypeName.ReferenceMask; import static com.ibm.wala.types.TypeReference.ArrayTypeCode; import static com.ibm.wala.types.TypeReference.PointerTypeCode; import static com.ibm.wala.types.TypeReference.ReferenceTypeCode; import com.ibm.wala.classLoader.Language; import com.ibm.wala.types.ClassLoaderReference; import com.ibm.wala.types.MethodReference; import com.ibm.wala.types.TypeName; import com.ibm.wala.types.TypeReference; import com.ibm.wala.util.collections.HashMapFactory; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; /** Some simple utilities used to manipulate Strings */ public class StringStuff { private static final HashMap<String, String> primitiveClassNames; static { primitiveClassNames = HashMapFactory.make(10); primitiveClassNames.put("int", "I"); primitiveClassNames.put("long", "J"); primitiveClassNames.put("short", "S"); primitiveClassNames.put("byte", "B"); primitiveClassNames.put("char", "C"); primitiveClassNames.put("double", "D"); primitiveClassNames.put("float", "F"); primitiveClassNames.put("boolean", "Z"); primitiveClassNames.put("void", "V"); } public static void padWithSpaces(StringBuilder b, int length) { if (b == null) { throw new IllegalArgumentException("b is null"); } if (b.length() < length) { b.append(" ".repeat(length - b.length())); } } /** * Translate a type from a deployment descriptor string into the internal JVM format * * <p>eg. [[java/lang/String * * @throws IllegalArgumentException if dString is null */ public static String deployment2CanonicalTypeString(String dString) { if (dString == null) { throw new IllegalArgumentException("dString is null"); } dString = dString.replace('.', '/'); int arrayIndex = dString.indexOf("[]"); if (arrayIndex > -1) { String baseType = dString.substring(0, arrayIndex); int dim = (dString.length() - arrayIndex) / 2; baseType = deployment2CanonicalTypeString(baseType); StringBuilder result = new StringBuilder("[".repeat(dim)); result.append(baseType); return result.toString(); } else { if (primitiveClassNames.get(dString) != null) { return primitiveClassNames.get(dString); } else { return 'L' + dString; } } } /** * Translate a type from a deployment descriptor string into the type expected for use in a method * descriptor * * <p>eg. [[Ljava.lang.String; * * @throws IllegalArgumentException if dString is null */ public static String deployment2CanonicalDescriptorTypeString(String dString) { if (dString == null) { throw new IllegalArgumentException("dString is null"); } dString = dString.replace('.', '/'); int arrayIndex = dString.indexOf("[]"); if (arrayIndex > -1) { String baseType = dString.substring(0, arrayIndex); int dim = (dString.length() - arrayIndex) / 2; baseType = deployment2CanonicalDescriptorTypeString(baseType); StringBuilder result = new StringBuilder("[".repeat(dim)); result.append(baseType); return result.toString(); } else { if (primitiveClassNames.get(dString) != null) { return primitiveClassNames.get(dString); } else { return 'L' + dString + ';'; } } } public static final TypeName parseForReturnTypeName(String desc) throws IllegalArgumentException { return parseForReturnTypeName(Language.JAVA, ImmutableByteArray.make(desc)); } public static final TypeName parseForReturnTypeName(Language l, String desc) throws IllegalArgumentException { return parseForReturnTypeName(l, ImmutableByteArray.make(desc)); } /** * Parse method descriptor to obtain description of method's return type. TODO: tune this .. * probably combine with parseForParameters. * * @param b method descriptor - something like "(III)V" * @return type description * @throws IllegalArgumentException if b is null */ public static final TypeName parseForReturnTypeName(Language l, ImmutableByteArray b) throws IllegalArgumentException { if (b == null) { throw new IllegalArgumentException("b is null"); } if (b.length() <= 2) { throw new IllegalArgumentException("invalid descriptor: " + b); } if (b.get(0) != '(') { throw new IllegalArgumentException("invalid descriptor: " + b); } int i = 0; while (b.get(i++) != ')') ; if (b.length() < i + 1) { throw new IllegalArgumentException("invalid descriptor: " + b); } switch (b.get(i)) { case TypeReference.VoidTypeCode: return TypeReference.Void.getName(); case TypeReference.BooleanTypeCode: return TypeReference.Boolean.getName(); case TypeReference.ByteTypeCode: return TypeReference.Byte.getName(); case TypeReference.ShortTypeCode: return TypeReference.Short.getName(); case TypeReference.IntTypeCode: return TypeReference.Int.getName(); case TypeReference.LongTypeCode: return TypeReference.Long.getName(); case TypeReference.FloatTypeCode: return TypeReference.Float.getName(); case TypeReference.DoubleTypeCode: return TypeReference.Double.getName(); case TypeReference.CharTypeCode: return TypeReference.Char.getName(); case TypeReference.OtherPrimitiveTypeCode: if (b.get(b.length() - 1) == ';') { return l.lookupPrimitiveType(new String(b.substring(i + 1, b.length() - i - 2))); } else { return l.lookupPrimitiveType(new String(b.substring(i + 1, b.length() - i - 1))); } case TypeReference.ClassTypeCode: // fall through case TypeReference.ArrayTypeCode: if (b.get(b.length() - 1) == ';') { return TypeName.findOrCreate(b, i, b.length() - i - 1); } else { return TypeName.findOrCreate(b, i, b.length() - i); } default: throw new IllegalArgumentException("unexpected type in descriptor " + b); } } public static final TypeName[] parseForParameterNames(String descriptor) throws IllegalArgumentException { return parseForParameterNames(Language.JAVA, ImmutableByteArray.make(descriptor)); } public static final TypeName[] parseForParameterNames(Language l, String descriptor) throws IllegalArgumentException { return parseForParameterNames(l, ImmutableByteArray.make(descriptor)); } /** * Parse method descriptor to obtain descriptions of method's parameters. * * @return parameter descriptions, or null if there are no parameters * @throws IllegalArgumentException if b is null */ public static final TypeName[] parseForParameterNames(Language l, ImmutableByteArray b) throws IllegalArgumentException { if (b == null) { throw new IllegalArgumentException("b is null"); } if (b.length() <= 2) { throw new IllegalArgumentException("invalid descriptor: " + b); } if (b.get(0) != '(') { throw new IllegalArgumentException("invalid descriptor: " + b); } ArrayList<TypeName> sigs = new ArrayList<>(10); int i = 1; while (true) { switch (b.get(i++)) { case TypeReference.VoidTypeCode: sigs.add(TypeReference.VoidName); continue; case TypeReference.BooleanTypeCode: sigs.add(TypeReference.BooleanName); continue; case TypeReference.ByteTypeCode: sigs.add(TypeReference.ByteName); continue; case TypeReference.ShortTypeCode: sigs.add(TypeReference.ShortName); continue; case TypeReference.IntTypeCode: sigs.add(TypeReference.IntName); continue; case TypeReference.LongTypeCode: sigs.add(TypeReference.LongName); continue; case TypeReference.FloatTypeCode: sigs.add(TypeReference.FloatName); continue; case TypeReference.DoubleTypeCode: sigs.add(TypeReference.DoubleName); continue; case TypeReference.CharTypeCode: sigs.add(TypeReference.CharName); continue; case TypeReference.OtherPrimitiveTypeCode: { int off = i - 1; while (b.get(i++) != ';') ; sigs.add(l.lookupPrimitiveType(new String(b.substring(off + 1, i - off - 2)))); continue; } case TypeReference.ClassTypeCode: { int off = i - 1; while (b.get(i++) != ';') ; sigs.add(TypeName.findOrCreate(b, off, i - off - 1)); continue; } case TypeReference.ArrayTypeCode: case TypeReference.PointerTypeCode: case TypeReference.ReferenceTypeCode: { int off = i - 1; while (StringStuff.isTypeCodeChar(b, i)) { ++i; } TypeName T = null; byte c = b.get(i++); if (c == TypeReference.ClassTypeCode || c == TypeReference.OtherPrimitiveTypeCode) { while (b.get(i++) != ';') ; T = TypeName.findOrCreate(b, off, i - off - 1); } else { T = TypeName.findOrCreate(b, off, i - off); } sigs.add(T); continue; } case (byte) ')': // end of parameter list int size = sigs.size(); if (size == 0) { return null; } Iterator<TypeName> it = sigs.iterator(); TypeName[] result = new TypeName[size]; for (int j = 0; j < size; j++) { result[j] = it.next(); } return result; default: assert false : "bad descriptor " + b; } } } public static boolean isTypeCodeChar(ImmutableByteArray name, int i) { return name.b[i] == TypeReference.ArrayTypeCode || name.b[i] == TypeReference.PointerTypeCode || name.b[i] == TypeReference.ReferenceTypeCode; } /** * Given that name[start:start+length] is a Type name in JVM format, parse it for the package * * @return an ImmutableByteArray that represents the package, or null if it's the unnamed package * @throws IllegalArgumentException if name == null */ public static ImmutableByteArray parseForPackage(ImmutableByteArray name, int start, int length) throws IllegalArgumentException { try { if (name == null) { throw new IllegalArgumentException("name == null"); } int lastSlash = -1; for (int i = start; i < start + length; i++) { if (name.b[i] == '/') { lastSlash = i; } } if (lastSlash == -1) { return null; } short dim = 0; while (isTypeCodeChar(name, start + dim)) { dim++; } return new ImmutableByteArray(name.b, start + 1 + dim, lastSlash - start - 1 - dim); } catch (ArrayIndexOutOfBoundsException e) { throw new IllegalArgumentException( "invalid name " + name + " start: " + start + " length: " + length, e); } } /** * Given that name[start:start+length] is a Type name in JVM format, parse it for the package * * @return an ImmutableByteArray that represents the package, or null if it's the unnamed package * @throws IllegalArgumentException if name is null */ public static ImmutableByteArray parseForPackage(ImmutableByteArray name) { if (name == null) { throw new IllegalArgumentException("name is null"); } return parseForPackage(name, 0, name.length()); } /** * Given that name[start:start+length] is a Type name in JVM format, strip the package and return * the "package-free" class name * * <p>TODO: inefficient; needs tuning. * * @return an ImmutableByteArray that represents the package, or null if it's the unnamed package * @throws IllegalArgumentException if name is null or malformed */ public static ImmutableByteArray parseForClass(ImmutableByteArray name, int start, int length) throws IllegalArgumentException { if (name == null) { throw new IllegalArgumentException("name is null"); } if (name.length() == 0) { throw new IllegalArgumentException("invalid class name: zero length"); } try { if (parseForPackage(name, start, length) == null) { while (isTypeCodeChar(name, start)) { start++; length--; } if (name.b[start] == 'L') { start++; length--; } return new ImmutableByteArray(name.b, start, length); } else { int lastSlash = 0; for (int i = start; i < start + length; i++) { if (name.b[i] == '/') { lastSlash = i; } } int L = length - (lastSlash - start + 1); return new ImmutableByteArray(name.b, lastSlash + 1, L); } } catch (ArrayIndexOutOfBoundsException e) { throw new IllegalArgumentException("Malformed name: " + name + ' ' + start + ' ' + length, e); } } /** * Given that name[start:start+length] is a Type name in JVM format, strip the package and return * the "package-free" class name * * @return an ImmutableByteArray that represents the package, or null if it's the unnamed package * @throws IllegalArgumentException if name is null */ public static ImmutableByteArray parseForClass(ImmutableByteArray name) throws IllegalArgumentException { if (name == null) { throw new IllegalArgumentException("name is null"); } return parseForClass(name, 0, name.length()); } /** * Parse an array descriptor to obtain number of dimensions in corresponding array type. b: * descriptor - something like "[Ljava/lang/String;" or "[[I" * * @return dimensionality - something like "1" or "2" * @throws IllegalArgumentException if b == null */ public static int parseForArrayDimensionality(ImmutableByteArray b, int start, int length) throws IllegalArgumentException, IllegalArgumentException { if (b == null) { throw new IllegalArgumentException("b == null"); } try { int code = 0; for (int i = start; i < start + length; ++i) { if (isTypeCodeChar(b, i)) { code <<= ElementBits; switch (b.b[i]) { case ArrayTypeCode: code |= ArrayMask; break; case PointerTypeCode: code |= PointerMask; break; case ReferenceTypeCode: code |= ReferenceMask; break; default: throw new IllegalArgumentException("ill-formed array descriptor " + b); } } else { // type codes must be at the start of the descriptor; if we see something else, stop break; } } return code; } catch (ArrayIndexOutOfBoundsException e) { throw new IllegalArgumentException("ill-formed array descriptor " + b, e); } } /** * Parse an array descriptor to obtain number of dimensions in corresponding array type. b: * descriptor - something like "[Ljava/lang/String;" or "[[I" * * @return dimensionality - something like "Ljava/lang/String;" or "I" * @throws IllegalArgumentException if b is null */ public static ImmutableByteArray parseForInnermostArrayElementDescriptor( ImmutableByteArray b, int start, int length) { if (b == null) { throw new IllegalArgumentException("b is null"); } try { int i = start; for (; i < start + length; ++i) { if (!isTypeCodeChar(b, i)) { break; } } return new ImmutableByteArray(b.b, i, length - (i - start)); } catch (ArrayIndexOutOfBoundsException e) { throw new IllegalArgumentException("invalid element desciptor: " + b, e); } } /** * Parse an array descriptor to obtain number of dimensions in corresponding array type. b: * descriptor - something like "[Ljava/lang/String;" or "[[I" * * @return dimensionality - something like "Ljava/lang/String;" or "I" * @throws IllegalArgumentException if a is null */ public static ImmutableByteArray parseForInnermostArrayElementDescriptor(Atom a) { if (a == null) { throw new IllegalArgumentException("a is null"); } ImmutableByteArray b = new ImmutableByteArray(a.getValArray()); return parseForInnermostArrayElementDescriptor(b, 0, b.length()); } /** * @return true iff the class returned by parseForClass is primitive * @throws IllegalArgumentException if name is null */ public static boolean classIsPrimitive(ImmutableByteArray name, int start, int length) throws IllegalArgumentException { if (name == null) { throw new IllegalArgumentException("name is null"); } try { while (length > 0 && isTypeCodeChar(name, start)) { start++; length--; } if (start >= name.b.length) { throw new IllegalArgumentException("ill-formed type name: " + name); } return name.b[start] != 'L'; } catch (ArrayIndexOutOfBoundsException e) { throw new IllegalArgumentException(name.toString(), e); } } /** * @param methodSig something like "java_cup.lexer.advance()V" * @throws IllegalArgumentException if methodSig is null */ public static MethodReference makeMethodReference(String methodSig) throws IllegalArgumentException { return makeMethodReference(Language.JAVA, methodSig); } public static MethodReference makeMethodReference(Language l, String methodSig) throws IllegalArgumentException { if (methodSig == null) { throw new IllegalArgumentException("methodSig is null"); } if (methodSig.lastIndexOf('.') < 0) { throw new IllegalArgumentException("ill-formed sig " + methodSig); } String type = methodSig.substring(0, methodSig.lastIndexOf('.')); type = deployment2CanonicalTypeString(type); TypeReference t = TypeReference.findOrCreate(ClassLoaderReference.Application, type); String methodName = methodSig.substring(methodSig.lastIndexOf('.') + 1, methodSig.indexOf('(')); String desc = methodSig.substring(methodSig.indexOf('(')); return MethodReference.findOrCreate(l, t, methodName, desc); } /** * Convert a JVM encoded type name to a readable type name. * * @param jvmType a String containing a type name in JVM internal format. * @return the same type name in readable (source code) format. * @throws IllegalArgumentException if jvmType is null */ public static String jvmToReadableType(final String jvmType) throws IllegalArgumentException { if (jvmType == null) { throw new IllegalArgumentException("jvmType is null"); } StringBuilder readable = new StringBuilder(); // human readable version int numberOfDimensions = 0; // the number of array dimensions if (jvmType.length() == 0) { throw new IllegalArgumentException("ill-formed type : " + jvmType); } // cycle through prefixes of '[' char prefix = jvmType.charAt(0); while (prefix == '[') { numberOfDimensions++; prefix = jvmType.charAt(numberOfDimensions); } switch (prefix) { case 'V': readable.append("void"); break; case 'B': readable.append("byte"); break; case 'C': readable.append("char"); break; case 'D': readable.append("double"); break; case 'F': readable.append("float"); break; case 'I': readable.append("int"); break; case 'J': readable.append("long"); break; case 'S': readable.append("short"); break; case 'Z': readable.append("boolean"); break; case 'L': readable.append( jvmType.substring( numberOfDimensions + 1, // strip // all // leading // '[' & // 'L' jvmType.length()) // Trim off the trailing ';' ); // Convert to standard Java dot-notation readable = new StringBuilder(slashToDot(readable.toString())); readable = new StringBuilder(dollarToDot(readable.toString())); break; } // append trailing "[]" for each array dimension readable.append("[]".repeat(numberOfDimensions)); return readable.toString(); } /** * Convert a JVM encoded type name to a binary type name. This version does not call dollarToDot. * * @param jvmType a String containing a type name in JVM internal format. * @return the same type name in readable (source code) format. * @throws IllegalArgumentException if jvmType is null */ public static String jvmToBinaryName(String jvmType) throws IllegalArgumentException { if (jvmType == null) { throw new IllegalArgumentException("jvmType is null"); } StringBuilder readable = new StringBuilder(); // human readable version int numberOfDimensions = 0; // the number of array dimensions if (jvmType.length() == 0) { throw new IllegalArgumentException("ill-formed type : " + jvmType); } // cycle through prefixes of '[' char prefix = jvmType.charAt(0); while (prefix == '[') { numberOfDimensions++; prefix = jvmType.charAt(numberOfDimensions); } switch (prefix) { case 'V': readable.append("void"); break; case 'B': readable.append("byte"); break; case 'C': readable.append("char"); break; case 'D': readable.append("double"); break; case 'F': readable.append("float"); break; case 'I': readable.append("int"); break; case 'J': readable.append("long"); break; case 'S': readable.append("short"); break; case 'Z': readable.append("boolean"); break; case 'L': readable.append( jvmType.substring( numberOfDimensions + 1, // strip // all // leading // '[' & // 'L' jvmType.length()) // Trim off the trailing ';' ); // Convert to standard Java dot-notation readable = new StringBuilder(slashToDot(readable.toString())); break; } // append trailing "[]" for each array dimension readable.append("[]".repeat(numberOfDimensions)); return readable.toString(); } /** * Convert '/' to '.' in names. * * @return a String object obtained by replacing the forward slashes ('/') in the String passed as * argument with ('.'). * @throws IllegalArgumentException if path is null */ public static String slashToDot(String path) { if (path == null) { throw new IllegalArgumentException("path is null"); } StringBuilder dotForm = new StringBuilder(path); // replace all '/' in the path with '.' for (int i = 0; i < dotForm.length(); ++i) { if (dotForm.charAt(i) == '/') { dotForm.setCharAt(i, '.'); // replace '/' with '.' } } return dotForm.toString(); } /** * Convert '$' to '.' in names. * * @param path a string object in which dollar signs('$') must be converted to dots ('.'). * @return a String object obtained by replacing the dollar signs ('S') in the String passed as * argument with ('.'). * @throws IllegalArgumentException if path is null */ public static String dollarToDot(String path) { if (path == null) { throw new IllegalArgumentException("path is null"); } StringBuilder dotForm = new StringBuilder(path); // replace all '$' in the path with '.' for (int i = 0; i < dotForm.length(); ++i) { if (dotForm.charAt(i) == '$') { dotForm.setCharAt(i, '.'); // replace '$' with '.' } } return dotForm.toString(); } /** * Convert '.' to '$' in names. * * @param path String object in which dollar signs('$') must be converted to dots ('.'). * @return a String object obtained by replacing the dollar signs ('S') in the String passed as * argument with ('.'). * @throws IllegalArgumentException if path is null */ public static String dotToDollar(String path) { if (path == null) { throw new IllegalArgumentException("path is null"); } StringBuilder dotForm = new StringBuilder(path); // replace all '.' in the path with '$' for (int i = 0; i < dotForm.length(); ++i) { if (dotForm.charAt(i) == '.') { dotForm.setCharAt(i, '$'); // replace '$' with '.' } } return dotForm.toString(); } /** Return the right position of the string up to '.' or '/' stripping ';' */ public static String toBasename(String typeName) { int start = 0; int stop = typeName.length() - 1; if (typeName.contains(".")) { start = typeName.lastIndexOf('.'); } else if (typeName.contains("/")) { start = typeName.lastIndexOf('/'); } if (typeName.endsWith(";")) { stop--; } return typeName.substring(start, stop); } }
25,969
32.639896
100
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/core/util/strings/UTF8Convert.java
/* * Copyright (c) 2002 - 2006 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package com.ibm.wala.core.util.strings; import com.ibm.wala.util.debug.Assertions; import java.io.UTFDataFormatException; /** * Abstract class that contains conversion routines to/from utf8 and/or pseudo-utf8. It does not * support utf8 encodings of more than 3 bytes. * * <p>The difference between utf8 and pseudo-utf8 is the special treatment of null. In utf8, null is * encoded as a single byte directly, whereas in pseudo-utf8, it is encoded as a two-byte sequence. * See the JVM spec for more information. */ public abstract class UTF8Convert { /** Strictly check the format of the utf8/pseudo-utf8 byte array in fromUTF8. */ static final boolean STRICTLY_CHECK_FORMAT = false; /** Set fromUTF8 to not throw an exception when given a normal utf8 byte array. */ static final boolean ALLOW_NORMAL_UTF8 = false; /** Set fromUTF8 to not throw an exception when given a pseudo utf8 byte array. */ static final boolean ALLOW_PSEUDO_UTF8 = true; /** Set toUTF8 to write in pseudo-utf8 (rather than normal utf8). */ static final boolean WRITE_PSEUDO_UTF8 = true; /** * Convert the given sequence of (pseudo-)utf8 formatted bytes into a String. * * <p>The acceptable input formats are controlled by the STRICTLY_CHECK_FORMAT, ALLOW_NORMAL_UTF8, * and ALLOW_PSEUDO_UTF8 flags. * * @param utf8 (pseudo-)utf8 byte array * @throws UTFDataFormatException if the (pseudo-)utf8 byte array is not valid (pseudo-)utf8 * @return unicode string * @throws IllegalArgumentException if utf8 is null */ @SuppressWarnings("unused") public static String fromUTF8(byte[] utf8) throws UTFDataFormatException { if (utf8 == null) { throw new IllegalArgumentException("utf8 is null"); } char[] result = new char[utf8.length]; int result_index = 0; for (int i = 0, n = utf8.length; i < n; ) { byte b = utf8[i++]; if (STRICTLY_CHECK_FORMAT && !ALLOW_NORMAL_UTF8) if (b == 0) throw new UTFDataFormatException("0 byte encountered at location " + (i - 1)); if (b >= 0) { // < 0x80 unsigned // in the range '\001' to '\177' result[result_index++] = (char) b; continue; } try { byte nb = utf8[i++]; if (b < -32) { // < 0xe0 unsigned // '\000' or in the range '\200' to '\u07FF' char c = result[result_index++] = (char) (((b & 0x1f) << 6) | (nb & 0x3f)); if (STRICTLY_CHECK_FORMAT) { if (((b & 0xe0) != 0xc0) || ((nb & 0xc0) != 0x80)) throw new UTFDataFormatException( "invalid marker bits for double byte char at location " + (i - 2)); if (c < '\200') { if (!ALLOW_PSEUDO_UTF8 || (c != '\000')) throw new UTFDataFormatException( "encountered double byte char that should have been single byte at location " + (i - 2)); } else if (c > '\u07FF') throw new UTFDataFormatException( "encountered double byte char that should have been triple byte at location " + (i - 2)); } } else { byte nnb = utf8[i++]; // in the range '\u0800' to '\uFFFF' char c = result[result_index++] = (char) (((b & 0x0f) << 12) | ((nb & 0x3f) << 6) | (nnb & 0x3f)); if (STRICTLY_CHECK_FORMAT) { if (((b & 0xf0) != 0xe0) || ((nb & 0xc0) != 0x80) || ((nnb & 0xc0) != 0x80)) throw new UTFDataFormatException( "invalid marker bits for triple byte char at location " + (i - 3)); if (c < '\u0800') throw new UTFDataFormatException( "encountered triple byte char that should have been fewer bytes at location " + (i - 3)); } } } catch (ArrayIndexOutOfBoundsException e) { throw new UTFDataFormatException("unexpected end at location " + i); } } return new String(result, 0, result_index); } /** * Convert the given String into a sequence of (pseudo-)utf8 formatted bytes. * * <p>The output format is controlled by the WRITE_PSEUDO_UTF8 flag. * * @param s String to convert * @return array containing sequence of (pseudo-)utf8 formatted bytes * @throws IllegalArgumentException if s is null */ public static byte[] toUTF8(String s) { if (s == null) { throw new IllegalArgumentException("s is null"); } byte[] result = new byte[utfLength(s)]; int result_index = 0; for (int i = 0, n = s.length(); i < n; ++i) { char c = s.charAt(i); // in all shifts below, c is an (unsigned) char, // so either >>> or >> is ok if ((!WRITE_PSEUDO_UTF8 || (c >= 0x0001)) && (c <= 0x007F)) result[result_index++] = (byte) c; else if (c > 0x07FF) { result[result_index++] = (byte) (0xe0 | (byte) (c >> 12)); result[result_index++] = (byte) (0x80 | ((c & 0xfc0) >> 6)); result[result_index++] = (byte) (0x80 | (c & 0x3f)); } else { result[result_index++] = (byte) (0xc0 | (byte) (c >> 6)); result[result_index++] = (byte) (0x80 | (c & 0x3f)); } } return result; } /** * Returns the length of a string's UTF encoded form. * * @throws IllegalArgumentException if s is null */ public static int utfLength(String s) { if (s == null) { throw new IllegalArgumentException("s is null"); } int utflen = 0; for (int i = 0, n = s.length(); i < n; ++i) { int c = s.charAt(i); if ((!WRITE_PSEUDO_UTF8 || (c >= 0x0001)) && (c <= 0x007F)) ++utflen; else if (c > 0x07FF) utflen += 3; else utflen += 2; } return utflen; } /** * Check whether the given sequence of bytes is valid (pseudo-)utf8. * * @param bytes byte array to check * @return true iff the given sequence is valid (pseudo-)utf8. * @throws IllegalArgumentException if bytes is null */ public static boolean check(byte[] bytes) { if (bytes == null) { throw new IllegalArgumentException("bytes is null"); } for (int i = 0, n = bytes.length; i < n; ) { byte b = bytes[i++]; if (!ALLOW_NORMAL_UTF8) if (b == 0) return false; if (b >= 0) { // < 0x80 unsigned // in the range '\001' to '\177' continue; } try { byte nb = bytes[i++]; if (b < -32) { // < 0xe0 unsigned // '\000' or in the range '\200' to '\u07FF' char c = (char) (((b & 0x1f) << 6) | (nb & 0x3f)); if (((b & 0xe0) != 0xc0) || ((nb & 0xc0) != 0x80)) return false; if (c < '\200') { if (!ALLOW_PSEUDO_UTF8 || (c != '\000')) return false; } else if (c > '\u07FF') return false; } else { byte nnb = bytes[i++]; // in the range '\u0800' to '\uFFFF' char c = (char) (((b & 0x0f) << 12) | ((nb & 0x3f) << 6) | (nnb & 0x3f)); if (((b & 0xf0) != 0xe0) || ((nb & 0xc0) != 0x80) || ((nnb & 0xc0) != 0x80)) return false; if (c < '\u0800') return false; } } catch (ArrayIndexOutOfBoundsException e) { return false; } } return true; } public static String fromUTF8(ImmutableByteArray s) { if (s == null) { throw new IllegalArgumentException("s is null"); } try { return fromUTF8(s.b); } catch (UTFDataFormatException e) { e.printStackTrace(); Assertions.UNREACHABLE(); return null; } } }
7,944
36.300469
100
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/core/util/warnings/Warning.java
/* * Copyright (c) 2002 - 2006 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package com.ibm.wala.core.util.warnings; import com.ibm.wala.util.debug.Assertions; /** A warning message. These are ordered first by severity, and then by lexicographic order. */ public abstract class Warning implements Comparable<Warning> { public static final byte MILD = 0; public static final byte MODERATE = 1; public static final byte SEVERE = 2; public static final byte CLIENT_MILD = 3; public static final byte CLIENT_MODERATE = 4; public static final byte CLIENT_SEVERE = 5; public static final byte N_LEVELS = 6; private byte level; public Warning(byte level) { this.level = level; } public Warning() { this.level = MILD; } @Override public int compareTo(Warning other) { if (other == null) { return -1; } if (level < other.level) { return -1; } else if (level > other.level) { return 1; } else { return getMsg().compareTo(other.getMsg()); } } @Override public final boolean equals(Object obj) { if (obj instanceof Warning) { Warning other = (Warning) obj; return (getMsg().equals(other.getMsg()) && getLevel() == other.getLevel()); } else { return false; } } @Override public final int hashCode() { return 1499 * getMsg().hashCode() + getLevel(); } @Override public String toString() { return '[' + severityString() + "] " + getMsg(); } protected String severityString() { switch (level) { case MILD: return "mild"; case MODERATE: return "Moderate"; case SEVERE: return "SEVERE"; case CLIENT_MILD: return "Client mild"; case CLIENT_MODERATE: return "Client moderate"; case CLIENT_SEVERE: return "Client severe"; default: Assertions.UNREACHABLE(); return null; } } public byte getLevel() { return level; } /** Must return the same String always -- this is required by the implementation of hashCode. */ public abstract String getMsg(); public void setLevel(byte b) { level = b; } }
2,469
22.084112
98
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/core/util/warnings/Warnings.java
/* * Copyright (c) 2002 - 2006 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package com.ibm.wala.core.util.warnings; import com.ibm.wala.util.collections.HashSetFactory; import java.util.Collection; import java.util.Iterator; import java.util.TreeSet; /** A global, static dictionary of warnings */ public class Warnings { private static final Collection<Warning> warnings = HashSetFactory.make(); public static synchronized boolean add(Warning w) { return warnings.add(w); } public static synchronized void clear() { warnings.clear(); } public static synchronized String asString() { TreeSet<Warning> T = new TreeSet<>(warnings); Iterator<Warning> it = T.iterator(); StringBuilder result = new StringBuilder(); for (int i = 1; i <= T.size(); i++) { result.append(i).append(". "); result.append(it.next()); result.append('\n'); } return result.toString(); } public static synchronized Iterator<Warning> iterator() { return warnings.iterator(); } }
1,326
27.234043
76
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/core/viz/PDFViewUtil.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.viz; import com.ibm.wala.cfg.CFGSanitizer; import com.ibm.wala.core.util.strings.StringStuff; import com.ibm.wala.ipa.cha.IClassHierarchy; import com.ibm.wala.ssa.IR; import com.ibm.wala.ssa.ISSABasicBlock; import com.ibm.wala.ssa.SSACFG; import com.ibm.wala.ssa.SSACFG.BasicBlock; 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.util.WalaException; 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.viz.DotUtil; import com.ibm.wala.util.viz.NodeDecorator; import com.ibm.wala.util.viz.PDFViewLauncher; import java.util.HashMap; /** utilities for integrating with ghostview (or another PS/PDF viewer) */ public class PDFViewUtil { /** * spawn a process to view a WALA IR * * @return a handle to the ghostview process */ public static Process ghostviewIR( IClassHierarchy cha, IR ir, String pdfFile, String dotFile, String dotExe, String pdfViewExe) throws WalaException { return ghostviewIR(cha, ir, pdfFile, dotFile, dotExe, pdfViewExe, null); } /** * spawn a process to view a WALA IR * * @return a handle to the pdf viewer process * @throws IllegalArgumentException if ir is null */ public static Process ghostviewIR( IClassHierarchy cha, IR ir, String pdfFile, String dotFile, String dotExe, String pdfViewExe, NodeDecorator<ISSABasicBlock> annotations) throws WalaException { if (ir == null) { throw new IllegalArgumentException("ir is null"); } NodeDecorator<ISSABasicBlock> labels = makeIRDecorator(ir); if (annotations != null) { labels = new ConcatenatingNodeDecorator<>(annotations, labels); } Graph<ISSABasicBlock> g = CFGSanitizer.sanitize(ir, cha); DotUtil.<ISSABasicBlock>dotify(g, labels, dotFile, pdfFile, dotExe); return launchPDFView(pdfFile, pdfViewExe); } public static NodeDecorator<ISSABasicBlock> makeIRDecorator(IR ir) { if (ir == null) { throw new IllegalArgumentException("ir is null"); } final HashMap<ISSABasicBlock, String> labelMap = HashMapFactory.make(); for (ISSABasicBlock issaBasicBlock : ir.getControlFlowGraph()) { SSACFG.BasicBlock bb = (SSACFG.BasicBlock) issaBasicBlock; labelMap.put(bb, getNodeLabel(ir, bb)); } NodeDecorator<ISSABasicBlock> labels = labelMap::get; return labels; } /** * A node decorator which concatenates the labels from two other node decorators * * @param <T> the type of the node */ private static final class ConcatenatingNodeDecorator<T> implements NodeDecorator<T> { private final NodeDecorator<T> A; private final NodeDecorator<T> B; ConcatenatingNodeDecorator(NodeDecorator<T> A, NodeDecorator<T> B) { this.A = A; this.B = B; } @Override public String getLabel(T n) throws WalaException { return A.getLabel(n) + B.getLabel(n); } } private static String getNodeLabel(IR ir, BasicBlock bb) { StringBuilder result = new StringBuilder(); int start = bb.getFirstInstructionIndex(); int end = bb.getLastInstructionIndex(); result.append("BB").append(bb.getNumber()); if (bb.isEntryBlock()) { result.append(" (en)\\n"); } else if (bb.isExitBlock()) { result.append(" (ex)\\n"); } if (bb instanceof ExceptionHandlerBasicBlock) { result.append("<Handler>"); } result.append("\\n"); for (SSAPhiInstruction phi : Iterator2Iterable.make(bb.iteratePhis())) { if (phi != null) { result.append(" ").append(phi.toString(ir.getSymbolTable())).append("\\l"); } } if (bb instanceof ExceptionHandlerBasicBlock) { ExceptionHandlerBasicBlock ebb = (ExceptionHandlerBasicBlock) bb; SSAGetCaughtExceptionInstruction s = ebb.getCatchInstruction(); if (s != null) { result.append(" ").append(s.toString(ir.getSymbolTable())).append("\\l"); } else { result.append(" " + " No catch instruction. Unreachable?\\l"); } } SSAInstruction[] instructions = ir.getInstructions(); for (int j = start; j <= end; j++) { if (instructions[j] != null) { StringBuilder x = new StringBuilder(j + " " + instructions[j].toString(ir.getSymbolTable())); StringStuff.padWithSpaces(x, 35); result.append(x); result.append("\\l"); } } for (SSAPiInstruction pi : Iterator2Iterable.make(bb.iteratePis())) { if (pi != null) { result.append(" ").append(pi.toString(ir.getSymbolTable())).append("\\l"); } } return result.toString(); } /** Launch a process to view a PDF file */ public static Process launchPDFView(String pdfFile, String gvExe) throws WalaException { // set up a viewer for the ps file. if (gvExe == null) { throw new IllegalArgumentException("null gvExe"); } if (pdfFile == null) { throw new IllegalArgumentException("null psFile"); } final PDFViewLauncher gv = new PDFViewLauncher(); gv.setGvExe(gvExe); gv.setPDFFile(pdfFile); gv.run(); if (gv.getProcess() == null) { throw new WalaException(" problem spawning process "); } return gv.getProcess(); } }
5,959
31.928177
99
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/core/viz/viewer/CgPanel.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.viz.viewer; import com.ibm.wala.classLoader.CallSiteReference; import com.ibm.wala.ipa.callgraph.CGNode; import com.ibm.wala.ipa.callgraph.CallGraph; import com.ibm.wala.ssa.IR; import com.ibm.wala.util.collections.Iterator2Iterable; import java.util.ArrayList; import java.util.List; import java.util.Set; import javax.swing.JScrollPane; import javax.swing.JSplitPane; import javax.swing.JTree; import javax.swing.event.TreeExpansionEvent; import javax.swing.event.TreeExpansionListener; import javax.swing.event.TreeSelectionEvent; import javax.swing.event.TreeSelectionListener; import javax.swing.tree.DefaultMutableTreeNode; import javax.swing.tree.TreePath; public class CgPanel extends JSplitPane { private static final long serialVersionUID = -4094408933344852549L; private final CallGraph cg; public CgPanel(CallGraph cg) { this.cg = cg; this.setDividerLocation(250); JTree tree = buildTree(); this.setLeftComponent(new JScrollPane(tree)); final IrAndSourceViewer irViewer = new IrAndSourceViewer(); this.setRightComponent(irViewer.getComponent()); //noinspection Convert2Lambda tree.addTreeSelectionListener( new TreeSelectionListener() { @Override public void valueChanged(TreeSelectionEvent e) { TreePath newLeadSelectionPath = e.getNewLeadSelectionPath(); if (null == newLeadSelectionPath) { return; } DefaultMutableTreeNode treeNode = (DefaultMutableTreeNode) newLeadSelectionPath.getLastPathComponent(); Object userObject = treeNode.getUserObject(); if (userObject instanceof CGNode) { CGNode node = (CGNode) userObject; IR ir1 = node.getIR(); irViewer.setIR(ir1); } else if (userObject instanceof CallSiteReference) { CGNode parentNode = (CGNode) ((DefaultMutableTreeNode) treeNode.getParent()).getUserObject(); IR ir2 = parentNode.getIR(); irViewer.setIRAndPc(ir2, ((CallSiteReference) userObject).getProgramCounter()); } } }); } private JTree buildTree() { CGNode cgRoot = cg.getFakeRootNode(); DefaultMutableTreeNode root = new DefaultMutableTreeNode(cgRoot); expandNode(root); JTree tree = new JTree(root); tree.addTreeExpansionListener( new TreeExpansionListener() { @Override public void treeExpanded(TreeExpansionEvent event) { TreePath path = event.getPath(); if (path == null) { return; } DefaultMutableTreeNode lastNode = (DefaultMutableTreeNode) path.getLastPathComponent(); expandNode(lastNode); } @Override public void treeCollapsed(TreeExpansionEvent event) {} }); return tree; } private void expandNode(DefaultMutableTreeNode treeNode) { expandNode(treeNode, 3); } private void expandNode(DefaultMutableTreeNode treeNode, int rec) { if (rec == 0) { return; } if (treeNode.getChildCount() == 0) { List<DefaultMutableTreeNode> newChilds = new ArrayList<>(); Object userObject = treeNode.getUserObject(); if (userObject instanceof CGNode) { CGNode cgNode = (CGNode) userObject; for (CallSiteReference csr : Iterator2Iterable.make(cgNode.iterateCallSites())) { newChilds.add(new DefaultMutableTreeNode(csr)); } } else { assert userObject instanceof CallSiteReference; CallSiteReference csr = (CallSiteReference) userObject; CGNode cgNode = (CGNode) ((DefaultMutableTreeNode) treeNode.getParent()).getUserObject(); Set<CGNode> successors = cg.getPossibleTargets(cgNode, csr); for (CGNode successor : successors) { newChilds.add(new DefaultMutableTreeNode(successor)); } } for (DefaultMutableTreeNode newChild : newChilds) { treeNode.add(newChild); } } for (int i = 0; i < treeNode.getChildCount(); i++) { DefaultMutableTreeNode child = (DefaultMutableTreeNode) treeNode.getChildAt(i); expandNode(child, rec - 1); } } }
4,636
32.601449
99
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/core/viz/viewer/ChaPanel.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.viz.viewer; import com.ibm.wala.classLoader.IClass; import com.ibm.wala.classLoader.IMethod; import com.ibm.wala.ipa.cha.IClassHierarchy; import java.util.Collection; import javax.swing.DefaultListModel; import javax.swing.JList; import javax.swing.JScrollPane; import javax.swing.JSplitPane; import javax.swing.JTree; import javax.swing.event.TreeExpansionEvent; import javax.swing.event.TreeExpansionListener; import javax.swing.event.TreeSelectionEvent; import javax.swing.event.TreeSelectionListener; import javax.swing.tree.DefaultMutableTreeNode; import javax.swing.tree.TreePath; public class ChaPanel extends JSplitPane { private static final long serialVersionUID = -9058908127737757320L; private final IClassHierarchy cha; public ChaPanel(IClassHierarchy cha) { this.cha = cha; this.setDividerLocation(250); JTree tree = buildTree(); this.setLeftComponent(new JScrollPane(tree)); final DefaultListModel<String> methodListModel = new DefaultListModel<>(); JList<String> methodList = new JList<>(methodListModel); this.setRightComponent(methodList); //noinspection Convert2Lambda tree.addTreeSelectionListener( new TreeSelectionListener() { @Override public void valueChanged(TreeSelectionEvent e) { TreePath newLeadSelectionPath = e.getNewLeadSelectionPath(); if (null == newLeadSelectionPath) { return; } DefaultMutableTreeNode treeNode = (DefaultMutableTreeNode) newLeadSelectionPath.getLastPathComponent(); IClass klass = (IClass) treeNode.getUserObject(); methodListModel.clear(); for (IMethod m : klass.getDeclaredMethods()) { methodListModel.addElement(m.toString()); } } }); } private JTree buildTree() { IClass rootClass = cha.getRootClass(); DefaultMutableTreeNode root = new DefaultMutableTreeNode(rootClass); expandNode(root); JTree tree = new JTree(root); tree.addTreeExpansionListener( new TreeExpansionListener() { @Override public void treeExpanded(TreeExpansionEvent event) { TreePath path = event.getPath(); if (path == null) { return; } DefaultMutableTreeNode lastNode = (DefaultMutableTreeNode) path.getLastPathComponent(); expandNode(lastNode); } @Override public void treeCollapsed(TreeExpansionEvent event) {} }); return tree; } private void expandNode(DefaultMutableTreeNode treeNode) { expandNode(treeNode, 3); } private void expandNode(DefaultMutableTreeNode treeNode, int rec) { if (rec == 0) { return; } if (treeNode.getChildCount() == 0) { IClass klass = (IClass) treeNode.getUserObject(); Collection<IClass> immediateSubclasses = cha.getImmediateSubclasses(klass); for (IClass immediateSubclass : immediateSubclasses) { treeNode.add(new DefaultMutableTreeNode(immediateSubclass)); } } for (int i = 0; i < treeNode.getChildCount(); i++) { DefaultMutableTreeNode child = (DefaultMutableTreeNode) treeNode.getChildAt(i); expandNode(child, rec - 1); } } }
3,686
30.784483
99
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/core/viz/viewer/DualTreeCellRenderer.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.viz.viewer; import com.ibm.wala.ipa.callgraph.propagation.InstanceKey; import com.ibm.wala.ipa.callgraph.propagation.PointerKey; import java.awt.Component; import javax.swing.ImageIcon; import javax.swing.JTree; import javax.swing.tree.DefaultMutableTreeNode; import javax.swing.tree.DefaultTreeCellRenderer; import javax.swing.tree.TreeCellRenderer; /** * Renderer for the heap tree. Gives non default icons for pointer keys and instance keys. * * @author yinnonh */ class DualTreeCellRenderer implements TreeCellRenderer { private final DefaultTreeCellRenderer defaultTreeCellRenderer; private final DefaultTreeCellRenderer ikTreeCellRenderer; private final DefaultTreeCellRenderer pkTreeCellRenderer; public DualTreeCellRenderer() { defaultTreeCellRenderer = new DefaultTreeCellRenderer(); ikTreeCellRenderer = new DefaultTreeCellRenderer(); ikTreeCellRenderer.setOpenIcon(createImageIcon("images/ik_open.png")); ikTreeCellRenderer.setClosedIcon(createImageIcon("images/ik_closed.png")); ikTreeCellRenderer.setLeafIcon(createImageIcon("images/ik_leaf.png")); pkTreeCellRenderer = new DefaultTreeCellRenderer(); pkTreeCellRenderer.setOpenIcon(createImageIcon("images/pk_open.png")); pkTreeCellRenderer.setClosedIcon(createImageIcon("images/pk_closed.png")); pkTreeCellRenderer.setLeafIcon(createImageIcon("images/pk_leaf.png")); } @Override public Component getTreeCellRendererComponent( JTree tree, Object value, boolean selected, boolean expanded, boolean leaf, int row, boolean hasFocus) { TreeCellRenderer delegate = getTreeCellRenderer(value); return delegate.getTreeCellRendererComponent( tree, value, selected, expanded, leaf, row, hasFocus); } private TreeCellRenderer getTreeCellRenderer(Object value) { if (value instanceof DefaultMutableTreeNode) { value = ((DefaultMutableTreeNode) value).getUserObject(); } if (value instanceof PointerKey) { return pkTreeCellRenderer; } else if (value instanceof InstanceKey) { return ikTreeCellRenderer; } else { return defaultTreeCellRenderer; } } /** Returns an ImageIcon, or null if the path was invalid. */ protected ImageIcon createImageIcon(String path) { java.net.URL imgURL = DualTreeCellRenderer.class.getResource(path); if (imgURL != null) { return new ImageIcon(imgURL); } else { System.err.println("Couldn't find file: " + path); return null; } } }
2,920
33.364706
90
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/core/viz/viewer/IrAndSourceViewer.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.viz.viewer; import com.ibm.wala.classLoader.IClassLoader; import com.ibm.wala.classLoader.IMethod; import com.ibm.wala.ssa.IR; import java.awt.Component; import java.io.File; import java.net.MalformedURLException; import java.net.URL; import javax.swing.JSplitPane; public class IrAndSourceViewer { private IrViewer irViewer; private SourceViewer sourceViewer; private IR ir; public Component getComponent() { JSplitPane splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT); irViewer = new IrViewer(); splitPane.setLeftComponent(irViewer); sourceViewer = new SourceViewer(); splitPane.setRightComponent(sourceViewer); irViewer.addSelectedPcListner( pc -> { IMethod method = ir.getMethod(); int sourceLineNumber = IrViewer.NA; String sourceFileName = null; if (pc != IrViewer.NA) { try { sourceLineNumber = method.getLineNumber(pc); IClassLoader loader = method.getDeclaringClass().getClassLoader(); sourceFileName = loader.getSourceFileName(method, pc); } catch (Exception e1) { e1.printStackTrace(); } } if (sourceFileName != null) { URL url; try { url = new File(sourceFileName).toURI().toURL(); sourceViewer.setSource(url, sourceLineNumber); } catch (MalformedURLException e2) { e2.printStackTrace(); } } else { sourceViewer.removeSource(); } }); return splitPane; } public void setIRAndPc(IR ir, int pc) { this.ir = ir; irViewer.setIRAndPc(ir, pc); } public void setIR(IR ir) { this.ir = ir; irViewer.setIR(ir); } }
2,178
26.935897
80
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/core/viz/viewer/IrViewer.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.viz.viewer; import com.ibm.wala.classLoader.IMethod; import com.ibm.wala.ssa.IR; import com.ibm.wala.util.collections.HashMapFactory; import java.awt.BorderLayout; import java.io.BufferedReader; import java.io.IOException; import java.io.StringReader; import java.util.HashSet; import java.util.Map; import java.util.Set; import javax.swing.DefaultListModel; import javax.swing.JList; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTextField; import javax.swing.ScrollPaneConstants; import javax.swing.event.ListSelectionEvent; import javax.swing.event.ListSelectionListener; public class IrViewer extends JPanel { private static final long serialVersionUID = -5668847442988389016L; private final JTextField methodName; private final DefaultListModel<String> irLineList = new DefaultListModel<>(); private final JList<String> irLines; // mapping from ir viewer list line to source code line number. private Map<Integer, Integer> lineToPosition = null; // Mapping for pc to line in the ir viewer list. private Map<Integer, Integer> pcToLine = null; private Map<Integer, Integer> lineToPc = null; public interface SelectedPcListner { void valueChanged(int pc); } Set<SelectedPcListner> selectedPcListners = new HashSet<>(); public IrViewer() { super(new BorderLayout()); irLines = new JList<>(irLineList); methodName = new JTextField("IR"); this.add(methodName, BorderLayout.PAGE_START); this.add( new JScrollPane( irLines, ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED, ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED), BorderLayout.CENTER); //noinspection Convert2Lambda irLines.addListSelectionListener( new ListSelectionListener() { @Override public void valueChanged(ListSelectionEvent e) { int index = irLines.getSelectedIndex(); Integer pc = lineToPc.get(index); if (pc == null) { pc = NA; } for (SelectedPcListner selectedPcListner : selectedPcListners) { selectedPcListner.valueChanged(pc); } } }); } public void setIR(IR ir) { this.lineToPosition = HashMapFactory.make(); this.pcToLine = HashMapFactory.make(); this.lineToPc = HashMapFactory.make(); int firstLineWithPosition = NA; try { methodName.setText("IR: " + ir.getMethod()); irLineList.clear(); BufferedReader br = new BufferedReader(new StringReader(ir.toString())); int lineNum = 0; int position = NA; String line; while ((line = br.readLine()) != null) { irLineList.addElement(line); int pc = parseIrLine(line); if (pc != NA) { IMethod m = ir.getMethod(); int newPosition = m.getLineNumber(pc); if (newPosition != -1) { position = newPosition; } lineToPc.put(lineNum, pc); pcToLine.put(pc, lineNum); if (position != NA) { lineToPosition.put(lineNum, position); if (firstLineWithPosition == NA) { firstLineWithPosition = lineNum; } } } lineNum++; } } catch (IOException e) { // ??? assert false; } // focusing on the first line with position if (firstLineWithPosition != NA) { irLines.setSelectedIndex(firstLineWithPosition); irLines.ensureIndexIsVisible(firstLineWithPosition); } } static final int NA = -1; private static int parseIrLine(String line) { int firstSpace = line.indexOf(' '); if (firstSpace > 0) { String pcString = line.substring(0, firstSpace); try { return Integer.parseInt(pcString); } catch (NumberFormatException e) { return NA; } } else { return NA; } } public void addSelectedPcListner(SelectedPcListner selectedPcListner) { this.selectedPcListners.add(selectedPcListner); } public void setPc(int pc) { Integer lineNum = pcToLine.get(pc); if (lineNum != null) { irLines.ensureIndexIsVisible(lineNum); irLines.setSelectedIndex(lineNum); } else { removeSelection(); } } public void setIRAndPc(IR ir, int pc) { setIR(ir); if (pc != NA) { setPc(pc); } else { removeSelection(); } } private void removeSelection() { int curSelectedIndex = irLines.getSelectedIndex(); irLines.removeSelectionInterval(curSelectedIndex, curSelectedIndex); } }
4,992
28.02907
79
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/core/viz/viewer/PaPanel.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.viz.viewer; import com.ibm.wala.analysis.pointers.HeapGraph; import com.ibm.wala.ipa.callgraph.CGNode; import com.ibm.wala.ipa.callgraph.CallGraph; import com.ibm.wala.ipa.callgraph.propagation.InstanceFieldPointerKey; import com.ibm.wala.ipa.callgraph.propagation.InstanceKey; import com.ibm.wala.ipa.callgraph.propagation.LocalPointerKey; import com.ibm.wala.ipa.callgraph.propagation.NormalAllocationInNode; import com.ibm.wala.ipa.callgraph.propagation.PointerAnalysis; import com.ibm.wala.ipa.callgraph.propagation.PointerKey; import com.ibm.wala.ipa.callgraph.propagation.ReturnValueKey; import com.ibm.wala.ssa.IR; import com.ibm.wala.ssa.SSAInstruction; import com.ibm.wala.util.intset.MutableMapping; import com.ibm.wala.util.intset.OrdinalSetMapping; import java.awt.BorderLayout; import java.util.ArrayList; import java.util.Collections; import java.util.List; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JSplitPane; import javax.swing.JTextField; import javax.swing.JTree; import javax.swing.event.TreeExpansionEvent; import javax.swing.event.TreeExpansionListener; import javax.swing.event.TreeSelectionEvent; import javax.swing.event.TreeSelectionListener; import javax.swing.tree.DefaultMutableTreeNode; import javax.swing.tree.TreeNode; import javax.swing.tree.TreePath; /** * Panel for showing the Pointer Analysis results. Shows the heap graph on the left, and the ir * viewer on the right. Sets the IR of and pc according to the chosen pointer/instance key when * possible (e.g., allocation side for NormalAllocationInNode instance keys. Can be customized for * clients that use different their own pointer / instance keys (see JsPaPanel) * * <p>Note the two steps initialization require (calling init()) * * @author yinnonh */ public class PaPanel extends JSplitPane { private static final long serialVersionUID = 8120735305334110889L; protected final PointerAnalysis<InstanceKey> pa; protected final CallGraph cg; private JTextField fullName; private IrAndSourceViewer irViewer; private final MutableMapping<List<LocalPointerKey>> cgNodeIdToLocalPointers = MutableMapping.<List<LocalPointerKey>>make(); private final MutableMapping<List<ReturnValueKey>> cgNodeIdToReturnValue = MutableMapping.<List<ReturnValueKey>>make(); private final MutableMapping<List<InstanceFieldPointerKey>> instanceKeyIdToInstanceFieldPointers = MutableMapping.<List<InstanceFieldPointerKey>>make(); public PaPanel(CallGraph cg, PointerAnalysis<InstanceKey> pa) { super(JSplitPane.HORIZONTAL_SPLIT); this.pa = pa; this.cg = cg; initDataStructures(pa); } /** * Two steps initialization is required here is our deriver can choose the roots for the heap * tree. */ public void init() { this.setDividerLocation(250); DefaultMutableTreeNode root = new DefaultMutableTreeNode(); for (Object rootChildNode : getRootNodes()) { DefaultMutableTreeNode n = new DefaultMutableTreeNode(rootChildNode); root.add(n); expandNodeRec(n, 1); } JTree heapTree = new JTree(root); heapTree.setCellRenderer(new DualTreeCellRenderer()); this.setLeftComponent(new JScrollPane(heapTree)); JPanel rightPanel = new JPanel(new BorderLayout()); this.setRightComponent(rightPanel); fullName = new JTextField(""); rightPanel.add(fullName, BorderLayout.PAGE_START); irViewer = new IrAndSourceViewer(); rightPanel.add(irViewer.getComponent(), BorderLayout.CENTER); heapTree.addTreeExpansionListener( new TreeExpansionListener() { @Override public void treeExpanded(TreeExpansionEvent event) { TreePath path = event.getPath(); if (path == null) { return; } DefaultMutableTreeNode lastNode = (DefaultMutableTreeNode) path.getLastPathComponent(); expandNodeRec(lastNode, 2); } @Override public void treeCollapsed(TreeExpansionEvent event) {} }); //noinspection Convert2Lambda heapTree.addTreeSelectionListener( new TreeSelectionListener() { @Override public void valueChanged(TreeSelectionEvent e) { TreePath newLeadSelectionPath = e.getNewLeadSelectionPath(); if (null == newLeadSelectionPath) { return; } DefaultMutableTreeNode treeNode = (DefaultMutableTreeNode) newLeadSelectionPath.getLastPathComponent(); Object userObject = treeNode.getUserObject(); fullName.setText(userObject.toString()); if (userObject instanceof LocalPointerKey) { LocalPointerKey lpk = (LocalPointerKey) userObject; IR ir1 = lpk.getNode().getIR(); SSAInstruction def = lpk.getNode().getDU().getDef(lpk.getValueNumber()); int pc1 = IrViewer.NA; if (def != null) { SSAInstruction[] instructions = ir1.getInstructions(); for (int i = 0; i < instructions.length; i++) { SSAInstruction instruction = instructions[i]; if (def == instruction) { pc1 = i; } } } irViewer.setIRAndPc(ir1, pc1); } else if (userObject instanceof InstanceFieldPointerKey) { InstanceKey ik = ((InstanceFieldPointerKey) userObject).getInstanceKey(); if (ik instanceof NormalAllocationInNode) { NormalAllocationInNode normalIk1 = (NormalAllocationInNode) ik; IR ir2 = normalIk1.getNode().getIR(); int pc2 = normalIk1.getSite().getProgramCounter(); irViewer.setIRAndPc(ir2, pc2); } } else if (userObject instanceof NormalAllocationInNode) { NormalAllocationInNode normalIk2 = (NormalAllocationInNode) userObject; IR ir3 = normalIk2.getNode().getIR(); int pc3 = normalIk2.getSite().getProgramCounter(); irViewer.setIRAndPc(ir3, pc3); } else if (userObject instanceof CGNode) { irViewer.setIR(((CGNode) userObject).getIR()); } } }); } private void initDataStructures(PointerAnalysis<InstanceKey> pa) { HeapGraph<InstanceKey> heapGraph = pa.getHeapGraph(); OrdinalSetMapping<InstanceKey> instanceKeyMapping = pa.getInstanceKeyMapping(); for (Object n : heapGraph) { if (heapGraph.getPredNodeCount(n) == 0) { // considering only roots of the heap graph. if (n instanceof PointerKey) { if (n instanceof LocalPointerKey) { LocalPointerKey lpk = (LocalPointerKey) n; int nodeId = lpk.getNode().getGraphNodeId(); mapUsingMutableMapping(cgNodeIdToLocalPointers, nodeId, lpk); } else if (n instanceof ReturnValueKey) { ReturnValueKey rvk = (ReturnValueKey) n; int nodeId = rvk.getNode().getGraphNodeId(); mapUsingMutableMapping(cgNodeIdToReturnValue, nodeId, rvk); } else if (n instanceof InstanceFieldPointerKey) { InstanceFieldPointerKey ifpk = (InstanceFieldPointerKey) n; int instanceKeyId = instanceKeyMapping.getMappedIndex(ifpk.getInstanceKey()); mapUsingMutableMapping(instanceKeyIdToInstanceFieldPointers, instanceKeyId, ifpk); } } else { System.err.println("Non Pointer key root: " + n); } } } } /** Override if you want different roots for your heap tree. */ protected List<Object> getRootNodes() { List<Object> ret = new ArrayList<>(); for (CGNode n : cg) { ret.add(n); } return ret; } /** expands the given "treeNode" "rec" levels. */ private void expandNodeRec(DefaultMutableTreeNode treeNode, int rec) { if (rec == 0) { return; } if (treeNode.getChildCount() == 0) { // may be expandable. List<Object> children = getChildrenFor(treeNode.getUserObject()); for (Object child : children) { treeNode.add(new DefaultMutableTreeNode(child)); } } for (int i = 0; i < treeNode.getChildCount(); i++) { TreeNode child = treeNode.getChildAt(i); expandNodeRec((DefaultMutableTreeNode) child, rec - 1); } } /** * Used for filling the tree dynamically. Override and handle your own nodes / different links. */ protected List<Object> getChildrenFor(Object node) { List<Object> ret = new ArrayList<>(); if (node instanceof InstanceKey) { ret.addAll(getPointerKeysUnderInstanceKey((InstanceKey) node)); } else if (node instanceof PointerKey) { for (InstanceKey ik : pa.getPointsToSet((PointerKey) node)) { ret.add(ik); } } else if (node instanceof CGNode) { int nodeId = ((CGNode) node).getGraphNodeId(); ret.addAll(nonNullList(cgNodeIdToLocalPointers.getMappedObject(nodeId))); ret.addAll(nonNullList(cgNodeIdToReturnValue.getMappedObject(nodeId))); } else { assert false : "Unhandled Node : " + node; } return ret; } /** * Get the set of pointer keys that should be presented below an instance key in the heap tree. * Override if you have special pointer keys (not just for fields) */ protected List<? extends PointerKey> getPointerKeysUnderInstanceKey(InstanceKey ik) { int ikIndex = pa.getInstanceKeyMapping().getMappedIndex(ik); List<? extends PointerKey> ret; if (ikIndex <= instanceKeyIdToInstanceFieldPointers.getMaximumIndex()) { ret = nonNullList(instanceKeyIdToInstanceFieldPointers.getMappedObject(ikIndex)); } else { ret = Collections.emptyList(); } return ret; } /** Utility method for mutable mapping. map[index] U= o */ protected static <T> void mapUsingMutableMapping(MutableMapping<List<T>> map, int index, T o) { List<T> set; if (index <= map.getMaximumIndex()) { set = map.getMappedObject(index); } else { set = null; } if (null == set) { set = new ArrayList<>(); map.put(index, set); } set.add(o); } protected <T> List<T> nonNullList(List<T> l) { if (null == l) { return Collections.emptyList(); } else { return l; } } }
10,738
36.680702
100
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/core/viz/viewer/SourceViewer.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.viz.viewer; import java.awt.BorderLayout; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.URL; import javax.swing.DefaultListModel; import javax.swing.JList; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTextField; public class SourceViewer extends JPanel { private static final long serialVersionUID = -1688405955293925453L; private URL sourceURL; private final JTextField sourceCodeLocation; private final DefaultListModel<String> sourceCodeLinesList = new DefaultListModel<>(); private final JList<String> sourceCodeLines; public SourceViewer() { super(new BorderLayout()); sourceURL = null; sourceCodeLines = new JList<>(sourceCodeLinesList); sourceCodeLocation = new JTextField("Source code"); this.add(sourceCodeLocation, BorderLayout.PAGE_START); this.add(new JScrollPane(sourceCodeLines), BorderLayout.CENTER); } public void setSource(URL url) { setSource(url, IrViewer.NA); } public void setSource(URL url, int sourceLine) { boolean succsess = loadSource(url); if (succsess) { sourceCodeLocation.setText("Source code: " + url); if (sourceLine != IrViewer.NA) { sourceCodeLines.ensureIndexIsVisible(sourceLine - 1); sourceCodeLines.setSelectedIndex(sourceLine - 1); sourceCodeLines.validate(); } } else { sourceCodeLocation.setText("Error loading source code from: " + url); } } private boolean loadSource(URL url) { if (url == null) { if (sourceURL != null) { // easing the current code. sourceCodeLinesList.clear(); } return false; // nothing to load } else { if (url.toString().equals(sourceURL.toString())) { return true; // already loaded } else { sourceCodeLinesList.clear(); try { BufferedReader br = new BufferedReader(new InputStreamReader(url.openStream())); String line; while ((line = br.readLine()) != null) { sourceCodeLinesList.addElement(line.replaceAll("\t", " ")); } br.close(); return true; } catch (IOException e) { System.err.println("Could not load source at " + url); return false; } } } } public void removeSelection() { int curSelectedIndex = sourceCodeLines.getSelectedIndex(); sourceCodeLines.removeSelectionInterval(curSelectedIndex, curSelectedIndex); } public void removeSource() { sourceURL = null; sourceCodeLocation.setText("Source code"); sourceCodeLinesList.clear(); sourceCodeLines.validate(); } }
3,086
30.5
90
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/core/viz/viewer/WalaViewer.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.viz.viewer; import com.ibm.wala.ipa.callgraph.CallGraph; import com.ibm.wala.ipa.callgraph.propagation.InstanceKey; import com.ibm.wala.ipa.callgraph.propagation.PointerAnalysis; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import javax.swing.JFrame; import javax.swing.JTabbedPane; import javax.swing.UIManager; /** * Viewer for ClassHeirarcy, CallGraph and Pointer Analysis results. A driver for example can be * found in com.ibm.wala.js.rhino.vis.JsViewer. * * @author yinnonh */ public class WalaViewer extends JFrame { private static final long serialVersionUID = -8580178580211053765L; protected static final String DefaultMutableTreeNode = null; public WalaViewer(CallGraph cg, PointerAnalysis<InstanceKey> pa) { setNativeLookAndFeel(); JTabbedPane tabbedPane = new JTabbedPane(); tabbedPane.add("Call Graph", new CgPanel(cg)); tabbedPane.add("Class Hierarchy", new ChaPanel(cg.getClassHierarchy())); PaPanel paPanel = createPaPanel(cg, pa); paPanel.init(); tabbedPane.add("Pointer Analysis", paPanel); setSize(600, 800); setExtendedState(MAXIMIZED_BOTH); addWindowListener(new ExitListener()); this.setTitle("Wala viewer"); add(tabbedPane); setVisible(true); } protected PaPanel createPaPanel(CallGraph cg, PointerAnalysis<InstanceKey> pa) { return new PaPanel(cg, pa); } public static void setNativeLookAndFeel() { try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (Exception e) { e.printStackTrace(); } } private static class ExitListener extends WindowAdapter { @Override public void windowClosing(WindowEvent event) { System.exit(0); } } }
2,140
28.736111
96
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/dataflow/IFDS/BackwardsSupergraph.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.dataflow.IFDS; import com.ibm.wala.util.collections.FilterIterator; import com.ibm.wala.util.collections.Iterator2Collection; import com.ibm.wala.util.debug.Assertions; import com.ibm.wala.util.debug.UnimplementedError; import com.ibm.wala.util.graph.Graph; import com.ibm.wala.util.intset.IntSet; import java.util.Iterator; import java.util.function.Predicate; import java.util.stream.Stream; /** * A "reversed" supergraph for backwards analysis. * * <p>In this view, a return is treated like a call, and vice-versa. All normal edges are reversed. */ public class BackwardsSupergraph<T, P> implements ISupergraph<T, P> { /** * DEBUG_LEVEL: * * <ul> * <li>0 No output * <li>1 Print some simple stats and warning information * <li>2 Detailed debugging * </ul> */ static final int DEBUG_LEVEL = 0; private final ISupergraph<T, P> delegate; private final ExitFilter exitFilter = new ExitFilter(); /** @param forwardGraph the graph to ``reverse'' */ protected BackwardsSupergraph(ISupergraph<T, P> forwardGraph) { if (forwardGraph == null) { throw new IllegalArgumentException("null forwardGraph"); } this.delegate = forwardGraph; } public static <T, P> BackwardsSupergraph<T, P> make(ISupergraph<T, P> forwardGraph) { return new BackwardsSupergraph<>(forwardGraph); } /** TODO: for now, this is not inverted. */ @Override public Graph<P> getProcedureGraph() { return delegate.getProcedureGraph(); } @Override public boolean isCall(T n) { return delegate.isReturn(n); } /** a filter that accepts only exit nodes from the original graph. */ private class ExitFilter implements Predicate<T> { @Override public boolean test(T o) { return delegate.isExit(o); } } /** * get the "called" (sic) nodes for a return site; i.e., the exit nodes that flow directly to this * return site. */ @SuppressWarnings("unused") @Override public Iterator<T> getCalledNodes(T ret) { if (DEBUG_LEVEL > 1) { System.err.println(getClass() + " getCalledNodes " + ret); System.err.println( "called nodes: " + Iterator2Collection.toSet(new FilterIterator<>(getSuccNodes(ret), exitFilter))); } return new FilterIterator<>(getSuccNodes(ret), exitFilter); } /** * get the "normal" successors (sic) for a return site; i.e., the "normal" CFG predecessors that * are not call nodes. * * @see com.ibm.wala.dataflow.IFDS.ISupergraph#getCalledNodes(java.lang.Object) */ @Override public Iterator<T> getNormalSuccessors(final T ret) { Iterator<T> allPreds = delegate.getPredNodes(ret); Predicate<T> sameProc = o -> getProcOf(ret).equals(getProcOf(o)) && !delegate.isExit(o); Iterator<T> sameProcPreds = new FilterIterator<>(allPreds, sameProc); Predicate<T> notCall = o -> !delegate.isCall(o); return new FilterIterator<>(sameProcPreds, notCall); } @Override public Iterator<? extends T> getReturnSites(T c, P callee) { return delegate.getCallSites(c, callee); } @Override public boolean isExit(T n) { return delegate.isEntry(n); } @Override public P getProcOf(T n) { return delegate.getProcOf(n); } /** @see com.ibm.wala.util.graph.Graph#removeNodeAndEdges(java.lang.Object) */ @Override public void removeNodeAndEdges(Object N) throws UnsupportedOperationException { throw new UnsupportedOperationException(); } @Override public Iterator<T> iterator() { return delegate.iterator(); } @Override public Stream<T> stream() { return delegate.stream(); } /** @see com.ibm.wala.util.graph.NodeManager#getNumberOfNodes() */ @Override public int getNumberOfNodes() { return delegate.getNumberOfNodes(); } /** @see com.ibm.wala.util.graph.NodeManager#addNode(java.lang.Object) */ @Override public void addNode(Object n) throws UnsupportedOperationException { throw new UnsupportedOperationException(); } /** @see com.ibm.wala.util.graph.NodeManager#removeNode(java.lang.Object) */ @Override public void removeNode(Object n) throws UnsupportedOperationException { throw new UnsupportedOperationException(); } /** @see com.ibm.wala.util.graph.NodeManager#containsNode(java.lang.Object) */ @Override public boolean containsNode(T N) { return delegate.containsNode(N); } /** @see com.ibm.wala.util.graph.EdgeManager#getPredNodes(java.lang.Object) */ @Override public Iterator<T> getPredNodes(T N) { return delegate.getSuccNodes(N); } /** @see com.ibm.wala.util.graph.EdgeManager#getPredNodeCount(java.lang.Object) */ @Override public int getPredNodeCount(T N) { return delegate.getSuccNodeCount(N); } /** @see com.ibm.wala.util.graph.EdgeManager#getSuccNodes(java.lang.Object) */ @Override public Iterator<T> getSuccNodes(T N) { return delegate.getPredNodes(N); } @Override public boolean hasEdge(T src, T dst) { return delegate.hasEdge(dst, src); } /** @see com.ibm.wala.util.graph.EdgeManager#getSuccNodeCount(java.lang.Object) */ @Override public int getSuccNodeCount(T N) { return delegate.getPredNodeCount(N); } /** @see com.ibm.wala.util.graph.EdgeManager#addEdge(java.lang.Object, java.lang.Object) */ @Override public void addEdge(Object src, Object dst) throws UnsupportedOperationException { throw new UnsupportedOperationException(); } @Override public void removeEdge(Object src, Object dst) throws UnsupportedOperationException { throw new UnsupportedOperationException(); } /** @see com.ibm.wala.util.graph.EdgeManager#removeAllIncidentEdges(Object) */ @Override public void removeAllIncidentEdges(Object node) throws UnsupportedOperationException { throw new UnsupportedOperationException(); } @Override public T[] getEntriesForProcedure(P object) { return delegate.getExitsForProcedure(object); } /** @see com.ibm.wala.dataflow.IFDS.ISupergraph#getEntriesForProcedure(java.lang.Object) */ @Override public T[] getExitsForProcedure(P object) { return delegate.getEntriesForProcedure(object); } @Override public boolean isReturn(T n) throws UnimplementedError { return delegate.isCall(n); } @Override public Iterator<? extends T> getCallSites(T r, P callee) { return delegate.getReturnSites(r, callee); } @Override public boolean isEntry(T n) { return delegate.isExit(n); } @Override public byte classifyEdge(T src, T dest) { byte d = delegate.classifyEdge(dest, src); switch (d) { case CALL_EDGE: return RETURN_EDGE; case RETURN_EDGE: return CALL_EDGE; case OTHER: return OTHER; case CALL_TO_RETURN_EDGE: return CALL_TO_RETURN_EDGE; default: Assertions.UNREACHABLE(); return -1; } } @Override public String toString() { return "Backwards of delegate\n" + delegate; } @Override public void removeIncomingEdges(Object node) throws UnsupportedOperationException { throw new UnsupportedOperationException(); } @Override public void removeOutgoingEdges(T node) throws UnsupportedOperationException { throw new UnsupportedOperationException(); } @Override public int getNumberOfBlocks(P procedure) { return delegate.getNumberOfBlocks(procedure); } @Override public int getLocalBlockNumber(T n) { return delegate.getLocalBlockNumber(n); } @Override public T getLocalBlock(P procedure, int i) { return delegate.getLocalBlock(procedure, i); } @Override public int getNumber(T N) { return delegate.getNumber(N); } @Override public T getNode(int number) { return delegate.getNode(number); } @Override public int getMaxNumber() { return delegate.getMaxNumber(); } @Override public Iterator<T> iterateNodes(IntSet s) throws UnimplementedError { Assertions.UNREACHABLE(); return null; } @Override public IntSet getSuccNodeNumbers(T node) { return delegate.getPredNodeNumbers(node); } @Override public IntSet getPredNodeNumbers(Object node) throws UnimplementedError { Assertions.UNREACHABLE(); return null; } }
8,610
26.423567
100
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/dataflow/IFDS/BoundedPartiallyBalancedSolver.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.dataflow.IFDS; import com.ibm.wala.util.MonitorUtil.IProgressMonitor; /** * A {@link TabulationSolver} that gives up after a finite bound. * * @param <T> type of node in the supergraph * @param <P> type of a procedure (like a box in an RSM) * @param <F> type of factoids propagated when solving this problem */ public class BoundedPartiallyBalancedSolver<T, P, F> extends PartiallyBalancedTabulationSolver<T, P, F> { private static final boolean VERBOSE = false; public static <T, P, F> BoundedPartiallyBalancedSolver<T, P, F> createdBoundedPartiallyBalancedSolver( PartiallyBalancedTabulationProblem<T, P, F> p, int bound, IProgressMonitor monitor) { return new BoundedPartiallyBalancedSolver<>(p, bound, monitor); } private final int bound; private int numSteps = 0; protected BoundedPartiallyBalancedSolver( PartiallyBalancedTabulationProblem<T, P, F> p, int bound, IProgressMonitor monitor) { super(p, monitor); this.bound = bound; } @Override protected boolean propagate(T s_p, int i, T n, int j) { if (numSteps < bound) { numSteps++; return super.propagate(s_p, i, n, j); } else { if (VERBOSE) { System.err.println( "Suppressing propagation; reached bound " + s_p + ' ' + i + ' ' + n + ' ' + j); } return false; } } public int getNumSteps() { return numSteps; } public void resetBound() { numSteps = 0; } }
1,854
27.538462
95
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/dataflow/IFDS/BoundedTabulationSolver.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.dataflow.IFDS; import com.ibm.wala.util.MonitorUtil.IProgressMonitor; /** * A {@link TabulationSolver} that gives up after a finite bound. * * @param <T> type of node in the supergraph * @param <P> type of a procedure (like a box in an RSM) * @param <F> type of factoids propagated when solving this problem */ public class BoundedTabulationSolver<T, P, F> extends TabulationSolver<T, P, F> { public static <T, P, F> BoundedTabulationSolver<T, P, F> createBoundedTabulationSolver( TabulationProblem<T, P, F> p, int bound, IProgressMonitor monitor) { return new BoundedTabulationSolver<>(p, bound, monitor); } private final int bound; private int numSteps = 0; protected BoundedTabulationSolver( TabulationProblem<T, P, F> p, int bound, IProgressMonitor monitor) { super(p, monitor); this.bound = bound; } @Override protected boolean propagate(T s_p, int i, T n, int j) { if (numSteps < bound) { numSteps++; return super.propagate(s_p, i, n, j); } return false; } public int getNumSteps() { return numSteps; } public void resetBound() { numSteps = 0; } }
1,540
26.517857
89
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/dataflow/IFDS/CallFlowEdges.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.dataflow.IFDS; import com.ibm.wala.util.collections.SparseVector; import com.ibm.wala.util.intset.BasicNaturalRelation; import com.ibm.wala.util.intset.BimodalMutableIntSet; import com.ibm.wala.util.intset.IBinaryNaturalRelation; import com.ibm.wala.util.intset.IntSet; import com.ibm.wala.util.intset.MutableIntSet; import com.ibm.wala.util.intset.MutableSparseIntSet; import com.ibm.wala.util.intset.SparseIntSet; /** A set of call flow edges which lead to a particular procedure entry s_p. */ public class CallFlowEdges { /** * A map from integer -&gt; (IBinaryNonNegativeIntRelation) * * <p>For a fact d2, edges[d2] gives a relation R=(c,d1) s.t. (&lt;c, d1&gt; -&gt; &lt;s_p,d2&gt;) * was recorded as a call flow edge. * * <p>Note that we handle paths of the form &lt;c, d1&gt; -&gt; &lt;s_p,d1&gt; specially, below. * * <p>TODO: more representation optimization. A special representation for triples? sparse * representations for CFG? exploit shorts for ints? */ private final SparseVector<IBinaryNaturalRelation> edges = new SparseVector<>(1, 1.1f); /** * a map from integer d1 -&gt; int set. * * <p>for fact d1, identityPaths[d1] gives the set of block numbers C s.t. for c \in C, &lt;c, * d1&gt; -&gt; &lt;s_p, d1&gt; is an edge. */ private final SparseVector<IntSet> identityEdges = new SparseVector<>(1, 1.1f); public CallFlowEdges() {} /** * Record that we've discovered a call edge &lt;c,d1&gt; -&gt; &lt;s_p, d2&gt; * * @param c global number identifying the call site node * @param d1 source fact at the call edge * @param d2 result fact (result of the call flow function) */ @SuppressWarnings("unused") public void addCallEdge(int c, int d1, int d2) { if (TabulationSolver.DEBUG_LEVEL > 0) { System.err.println("addCallEdge " + c + ' ' + d1 + ' ' + d2); } if (d1 == d2) { BimodalMutableIntSet s = (BimodalMutableIntSet) identityEdges.get(d1); if (s == null) { s = new BimodalMutableIntSet(); identityEdges.set(d1, s); } s.add(c); } else { IBinaryNaturalRelation R = edges.get(d2); if (R == null) { // we expect the first dimension of R to be dense, the second sparse R = new BasicNaturalRelation( new byte[] {BasicNaturalRelation.TWO_LEVEL}, BasicNaturalRelation.TWO_LEVEL); edges.set(d2, R); } R.add(c, d1); } } /** * @return set of d1 s.t. {@literal <c, d1> -> <s_p, d2>} was recorded as call flow, or null if * none found. */ @SuppressWarnings("unused") public IntSet getCallFlowSources(int c, int d2) { if (c < 0) { throw new IllegalArgumentException("invalid c : " + c); } if (d2 < 0) { throw new IllegalArgumentException("invalid d2: " + d2); } IntSet s = identityEdges.get(d2); IBinaryNaturalRelation R = edges.get(d2); IntSet result = null; if (R == null) { if (s != null) { result = s.contains(c) ? SparseIntSet.singleton(d2) : null; } } else { if (s == null) { result = R.getRelated(c); } else { if (s.contains(c)) { if (R.getRelated(c) == null) { result = SparseIntSet.singleton(d2); } else { result = MutableSparseIntSet.make(R.getRelated(c)); ((MutableSparseIntSet) result).add(d2); } } else { result = R.getRelated(c); } } } if (TabulationSolver.DEBUG_LEVEL > 0) { System.err.println("getCallFlowSources " + c + ' ' + d2 + ' ' + result); } return result; } /** * @return set of c s.t. {@literal <c, d1> -> <s_p, d2>} was recorded as call flow (for some d1), * or null if none found. */ @SuppressWarnings("unused") public IntSet getCallFlowSourceNodes(int d2) { IntSet s = identityEdges.get(d2); IBinaryNaturalRelation R = edges.get(d2); IntSet result = null; if (R == null) { if (s != null) { result = s; } } else { if (s == null) { result = getDomain(R); } else { result = MutableSparseIntSet.make(s); ((MutableSparseIntSet) result).addAll(getDomain(R)); } } if (TabulationSolver.DEBUG_LEVEL > 0) { System.err.println("getCallFlowSources " + d2 + ' ' + result); } return result; } // TODO optimize private static IntSet getDomain(IBinaryNaturalRelation r) { MutableIntSet result = MutableSparseIntSet.makeEmpty(); int maxKeyValue = r.maxKeyValue(); for (int i = 0; i <= maxKeyValue; i++) { if (r.getRelated(i) != null) { result.add(i); } } return result; } }
5,126
31.04375
100
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/dataflow/IFDS/IBinaryReturnFlowFunction.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.dataflow.IFDS; import com.ibm.wala.util.intset.SparseIntSet; /** * A binary flow function corresponding to a return statements combining information from the call * site and the exit site. * * <p>This function should be pairwise distributive for use with the Tabulation algorithm. * * <p>SJF: I have made this extend IFlowFunction to minimize damage to the extant class hierarchy. * But calling super.getTargets() will be a problem, so be very careful in how you implement and use * this. The Tabulation solver will do the right thing. */ public interface IBinaryReturnFlowFunction extends IFlowFunction { /** * @param call_d factoid of the caller at the call site * @param exit_d factoid of the callee at the exit site * @return set of ret_d such that ({@literal <call_d, exit_d>}, ret_d) is an edge in this * distributive function's graph representation, or null if there are none */ SparseIntSet getTargets(int call_d, int exit_d); }
1,368
38.114286
100
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/dataflow/IFDS/ICFGSupergraph.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 * * "Restricted Materials of IBM" * * Copyright (c) 2008 IBM Corporation. * * Contributors: * IBM Corporation - initial API and implementation */ package com.ibm.wala.dataflow.IFDS; import com.ibm.wala.cfg.ControlFlowGraph; import com.ibm.wala.ipa.callgraph.CGNode; import com.ibm.wala.ipa.callgraph.CallGraph; import com.ibm.wala.ipa.cfg.BasicBlockInContext; import com.ibm.wala.ipa.cfg.ExplodedInterproceduralCFG; import com.ibm.wala.ipa.cha.IClassHierarchy; import com.ibm.wala.ssa.SSAAbstractInvokeInstruction; import com.ibm.wala.ssa.SSAInstruction; import com.ibm.wala.ssa.analysis.IExplodedBasicBlock; import com.ibm.wala.util.collections.EmptyIterator; import com.ibm.wala.util.collections.FilterIterator; import com.ibm.wala.util.debug.Assertions; import com.ibm.wala.util.graph.Graph; import com.ibm.wala.util.intset.IntSet; import java.util.Iterator; import java.util.function.Predicate; import java.util.stream.Stream; /** * Forward supergraph induced over an {@link ExplodedInterproceduralCFG} * * <p>This should lazily build the supergraph as it is explored. * * @author sjfink */ public class ICFGSupergraph implements ISupergraph<BasicBlockInContext<IExplodedBasicBlock>, CGNode> { private final ExplodedInterproceduralCFG icfg; protected ICFGSupergraph(ExplodedInterproceduralCFG icfg) { this.icfg = icfg; } public static ICFGSupergraph make(CallGraph cg) { ICFGSupergraph w = new ICFGSupergraph(ExplodedInterproceduralCFG.make(cg)); return w; } @Override public Graph<CGNode> getProcedureGraph() { return icfg.getCallGraph(); } public IClassHierarchy getClassHierarchy() { return icfg.getCallGraph().getClassHierarchy(); } @Override public byte classifyEdge( BasicBlockInContext<IExplodedBasicBlock> src, BasicBlockInContext<IExplodedBasicBlock> dest) { if (isCall(src)) { if (isEntry(dest)) { return CALL_EDGE; } else { return CALL_TO_RETURN_EDGE; } } else if (isExit(src)) { return RETURN_EDGE; } else { return OTHER; } } @Override public Iterator<BasicBlockInContext<IExplodedBasicBlock>> getCallSites( BasicBlockInContext<IExplodedBasicBlock> r, CGNode callee) { return icfg.getCallSites(r, callee); } @Override public Iterator<? extends BasicBlockInContext<IExplodedBasicBlock>> getCalledNodes( BasicBlockInContext<IExplodedBasicBlock> call) { final Predicate<BasicBlockInContext<IExplodedBasicBlock>> isEntryFilter = BasicBlockInContext::isEntryBlock; return new FilterIterator<>(getSuccNodes(call), isEntryFilter); } @Override @SuppressWarnings("unchecked") public BasicBlockInContext<IExplodedBasicBlock>[] getEntriesForProcedure(CGNode procedure) { return new BasicBlockInContext[] {icfg.getEntry(procedure)}; } @Override @SuppressWarnings("unchecked") public BasicBlockInContext<IExplodedBasicBlock>[] getExitsForProcedure(CGNode procedure) { return new BasicBlockInContext[] {icfg.getExit(procedure)}; } @Override public BasicBlockInContext<IExplodedBasicBlock> getLocalBlock(CGNode procedure, int i) { IExplodedBasicBlock b = icfg.getCFG(procedure).getNode(i); return new BasicBlockInContext<>(procedure, b); } @Override public int getLocalBlockNumber(BasicBlockInContext<IExplodedBasicBlock> n) { return n.getDelegate().getNumber(); } public BasicBlockInContext<IExplodedBasicBlock> getMainEntry() { Assertions.UNREACHABLE(); return null; } @Override public Iterator<BasicBlockInContext<IExplodedBasicBlock>> getNormalSuccessors( BasicBlockInContext<IExplodedBasicBlock> call) { return EmptyIterator.instance(); } @Override public int getNumberOfBlocks(CGNode procedure) { Assertions.UNREACHABLE(); return 0; } @Override public CGNode getProcOf(BasicBlockInContext<IExplodedBasicBlock> n) { return icfg.getCGNode(n); } @Override public Iterator<? extends BasicBlockInContext<IExplodedBasicBlock>> getReturnSites( BasicBlockInContext<IExplodedBasicBlock> call, CGNode callee) { return icfg.getReturnSites(call); } @Override public boolean isCall(BasicBlockInContext<IExplodedBasicBlock> n) { return n.getDelegate().getInstruction() instanceof SSAAbstractInvokeInstruction; } @Override public boolean isEntry(BasicBlockInContext<IExplodedBasicBlock> n) { return n.getDelegate().isEntryBlock(); } @Override public boolean isExit(BasicBlockInContext<IExplodedBasicBlock> n) { return n.getDelegate().isExitBlock(); } @Override public boolean isReturn(BasicBlockInContext<IExplodedBasicBlock> n) { return icfg.isReturn(n); } @Override public void removeNodeAndEdges(BasicBlockInContext<IExplodedBasicBlock> N) throws UnsupportedOperationException { Assertions.UNREACHABLE(); } @Override public void addNode(BasicBlockInContext<IExplodedBasicBlock> n) { Assertions.UNREACHABLE(); } @Override public boolean containsNode(BasicBlockInContext<IExplodedBasicBlock> N) { return icfg.containsNode(N); } @Override public int getNumberOfNodes() { return icfg.getNumberOfNodes(); } @Override public Iterator<BasicBlockInContext<IExplodedBasicBlock>> iterator() { return icfg.iterator(); } @Override public Stream<BasicBlockInContext<IExplodedBasicBlock>> stream() { return icfg.stream(); } @Override public void removeNode(BasicBlockInContext<IExplodedBasicBlock> n) { Assertions.UNREACHABLE(); } @Override public void addEdge( BasicBlockInContext<IExplodedBasicBlock> src, BasicBlockInContext<IExplodedBasicBlock> dst) { Assertions.UNREACHABLE(); } @Override public int getPredNodeCount(BasicBlockInContext<IExplodedBasicBlock> N) { return icfg.getPredNodeCount(N); } @Override public Iterator<BasicBlockInContext<IExplodedBasicBlock>> getPredNodes( BasicBlockInContext<IExplodedBasicBlock> N) { return icfg.getPredNodes(N); } @Override public int getSuccNodeCount(BasicBlockInContext<IExplodedBasicBlock> N) { return icfg.getSuccNodeCount(N); } @Override public Iterator<BasicBlockInContext<IExplodedBasicBlock>> getSuccNodes( BasicBlockInContext<IExplodedBasicBlock> N) { return icfg.getSuccNodes(N); } @Override public boolean hasEdge( BasicBlockInContext<IExplodedBasicBlock> src, BasicBlockInContext<IExplodedBasicBlock> dst) { return icfg.hasEdge(src, dst); } @Override public void removeAllIncidentEdges(BasicBlockInContext<IExplodedBasicBlock> node) throws UnsupportedOperationException { Assertions.UNREACHABLE(); } @Override public void removeEdge( BasicBlockInContext<IExplodedBasicBlock> src, BasicBlockInContext<IExplodedBasicBlock> dst) throws UnsupportedOperationException { Assertions.UNREACHABLE(); } @Override public void removeIncomingEdges(BasicBlockInContext<IExplodedBasicBlock> node) throws UnsupportedOperationException { Assertions.UNREACHABLE(); } @Override public void removeOutgoingEdges(BasicBlockInContext<IExplodedBasicBlock> node) throws UnsupportedOperationException { Assertions.UNREACHABLE(); } @Override public int getMaxNumber() { return icfg.getMaxNumber(); } @Override public BasicBlockInContext<IExplodedBasicBlock> getNode(int number) { return icfg.getNode(number); } @Override public int getNumber(BasicBlockInContext<IExplodedBasicBlock> N) { return icfg.getNumber(N); } @Override public Iterator<BasicBlockInContext<IExplodedBasicBlock>> iterateNodes(IntSet s) { Assertions.UNREACHABLE(); return null; } @Override public IntSet getPredNodeNumbers(BasicBlockInContext<IExplodedBasicBlock> node) { return icfg.getPredNodeNumbers(node); } @Override public IntSet getSuccNodeNumbers(BasicBlockInContext<IExplodedBasicBlock> node) { return icfg.getSuccNodeNumbers(node); } public ControlFlowGraph<SSAInstruction, IExplodedBasicBlock> getCFG( BasicBlockInContext<IExplodedBasicBlock> node) { return icfg.getCFG(node); } public ExplodedInterproceduralCFG getICFG() { return icfg; } @Override public String toString() { return icfg.toString(); } }
8,730
26.894569
100
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/dataflow/IFDS/IFlowFunction.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.dataflow.IFDS; /** * A flow function corresponding to an edge in the supergraph. * * <p>This function should be distributive for use with the Tabulation algorithm. */ public interface IFlowFunction {}
602
30.736842
81
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/dataflow/IFDS/IFlowFunctionMap.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.dataflow.IFDS; /** * A map from an edge in a supergraph to a flow function * * @param <T> type of node in the supergraph */ public interface IFlowFunctionMap<T> { /** @return the flow function for a "normal" edge in the supergraph from src -&gt; dest */ IUnaryFlowFunction getNormalFlowFunction(T src, T dest); /** * @param src the call block * @param dest the entry of the callee * @param ret the block that will be returned to, in the caller. This can be null .. signifying * that facts can flow into the callee but not return * @return the flow function for a "call" edge in the supergraph from src -&gt; dest */ IUnaryFlowFunction getCallFlowFunction(T src, T dest, T ret); /** * @param call supergraph node of the call instruction for this return edge. * @return the flow function for a "return" edge in the supergraph from src -&gt; dest */ IFlowFunction getReturnFlowFunction(T call, T src, T dest); /** @return the flow function for a "call-to-return" edge in the supergraph from src -&gt; dest */ IUnaryFlowFunction getCallToReturnFlowFunction(T src, T dest); /** * @return the flow function for a "call-to-return" edge in the supergraph from src -&gt; dest, * when the supergraph does not contain any callees of src. This happens via, e.g., slicing. */ IUnaryFlowFunction getCallNoneToReturnFlowFunction(T src, T dest); }
1,802
37.361702
100
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/dataflow/IFDS/IMergeFunction.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.dataflow.IFDS; import com.ibm.wala.util.intset.IntSet; /** * Special case: if supportsMerge(), then the problem is not really IFDS anymore. (TODO: rename * it?). Instead, we perform a merge operation before propagating at every program point. This way, * we can implement standard interprocedural dataflow and ESP-style property simulation, and various * other things. */ public interface IMergeFunction { /** * @param x set of factoid numbers that previously have been established to hold at a program * point * @param j a new factoid number which has been discovered to hold at a program point * @return the factoid number z which should actually be propagated, based on a merge of the new * fact j into the old state represented by x. return -1 if no fact should be propagated. */ int merge(IntSet x, int j); }
1,248
38.03125
100
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/dataflow/IFDS/IPartiallyBalancedFlowFunctions.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.dataflow.IFDS; /** Flow functions for a {@link PartiallyBalancedTabulationProblem} */ public interface IPartiallyBalancedFlowFunctions<T> extends IFlowFunctionMap<T> { /** * This version should work when the "call" instruction was never reached normally. This applies * only when using partially balanced parentheses. * * @return the flow function for a "return" edge in the supergraph from src -&lt; dest */ IFlowFunction getUnbalancedReturnFlowFunction(T src, T dest); }
883
35.833333
98
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/dataflow/IFDS/IReversibleFlowFunction.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.dataflow.IFDS; import com.ibm.wala.util.intset.IntSet; /** * A flow function corresponding to an edge in the supergraph. A reversible flow-function supports a * getSources operation that allows computing backwards flow. At the very least, this is required in * IFDS by call functions for which sources need to be found to handle insertion of summary edges. */ public interface IReversibleFlowFunction extends IUnaryFlowFunction { /** * @return set of d1 such that (d1,d2) is an edge in this distributive function's graph * representation, or null if there are none */ IntSet getSources(int d2); }
1,017
35.357143
100
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/dataflow/IFDS/ISupergraph.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.dataflow.IFDS; import com.ibm.wala.util.graph.Graph; import com.ibm.wala.util.graph.NumberedGraph; import java.util.Iterator; /** * A supergraph as defined by Reps, Horwitz, and Sagiv POPL95 * * <p>In our implementation we don't require explicit entry and exit nodes. So, the first basic * block in a method is implicitly the entry node, but might also be a call node too. Similarly for * exit nodes. The solver is coded to deal with this appropriately. * * <p>Additionally, due to exceptional control flow, each method might have multiple exits or * multiple entries. * * <p>T type of node in the supergraph P type of a procedure (like a box in an RSM) */ public interface ISupergraph<T, P> extends NumberedGraph<T> { byte CALL_EDGE = 0; byte RETURN_EDGE = 1; byte CALL_TO_RETURN_EDGE = 2; byte OTHER = 3; /** @return the graph of procedures (e.g. a call graph) over which this supergraph is induced. */ Graph<P> getProcedureGraph(); /** * @param n a node in this supergraph * @return true iff this node includes a call. */ boolean isCall(T n); /** * @param call a "call" node in the supergraph * @return an Iterator of nodes that are targets of this call. */ Iterator<? extends T> getCalledNodes(T call); /** * @param call a "call" node in the supergraph * @return an Iterator of nodes that are normal (non-call) successors of this call. This should * only apply to backwards problems, where we might have, say, a call and a goto flow into a * return site. */ Iterator<T> getNormalSuccessors(T call); /** * @param call a "call" node in the supergraph * @param callee a "called" "procedure" in the supergraph. if callee is null, answer return sites * for which no callee was found. * @return the corresponding return nodes. There may be many, because of exceptional control flow. */ Iterator<? extends T> getReturnSites(T call, P callee); /** * @param ret a "return" node in the supergraph * @param callee a "called" "procedure" in the supergraph. if callee is null, answer return sites * for which no callee was found. * @return the corresponding call nodes. There may be many. */ Iterator<? extends T> getCallSites(T ret, P callee); /** * @param n a node in the supergraph * @return true iff this node is an exit node */ boolean isExit(T n); /** * @param n a node in the supergraph * @return an object which represents the procedure which contains n */ P getProcOf(T n); /** @return the blocks in the supergraph that represents entry nodes for procedure p */ T[] getEntriesForProcedure(P procedure); /** @return the blocks in the supergraph that represents exit nodes for procedure p */ T[] getExitsForProcedure(P procedure); /** * @param procedure an object that represents a procedure * @return the number of blocks from this procedure in this supergraph */ int getNumberOfBlocks(P procedure); /** * @param n a node in the supergraph * @return the "logical" basic block number of n in its procedure */ int getLocalBlockNumber(T n); /** * @param procedure an object that represents a procedure * @param i the "logical" basic block number of a node in the procedure * @return the corresponding node in the supergraph */ T getLocalBlock(P procedure, int i); /** * @param n a node in this supergraph * @return true iff this node is a return site. */ boolean isReturn(T n); /** @return true iff this node is an entry node s_p for a procedure */ boolean isEntry(T n); /** * @param src node in the supergraph * @param dest a successor of src in the supergraph * @return one of CALL_EDGE, RETURN_EDGE, CALL_TO_RETURN_EDGE, or OTHER */ byte classifyEdge(T src, T dest); }
4,217
31.198473
100
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/dataflow/IFDS/ITabulationWorklist.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.dataflow.IFDS; /** @param <T> represents type of nodes in the supergraph. */ public interface ITabulationWorklist<T> { /** @return the first object in the priority queue */ PathEdge<T> take(); void insert(PathEdge<T> elt); int size(); }
638
26.782609
72
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/dataflow/IFDS/IUnaryFlowFunction.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.dataflow.IFDS; import com.ibm.wala.util.intset.IntSet; /** * A flow function corresponding to an edge in the supergraph. * * <p>This function should be distributive for use with the Tabulation algorithm. */ public interface IUnaryFlowFunction extends IFlowFunction { /** * @return set of d2 such that (d1,d2) is an edge in this distributive function's graph * representation, or null if there are none */ IntSet getTargets(int d1); }
854
29.535714
89
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/dataflow/IFDS/IdentityFlowFunction.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.dataflow.IFDS; import com.ibm.wala.util.intset.SparseIntSet; /** A flow function where out == in */ public class IdentityFlowFunction implements IReversibleFlowFunction { private static final IdentityFlowFunction singleton = new IdentityFlowFunction(); @Override public SparseIntSet getTargets(int i) { return SparseIntSet.singleton(i); } @Override public SparseIntSet getSources(int i) { return SparseIntSet.singleton(i); } public static IdentityFlowFunction identity() { return singleton; } @Override public String toString() { return "Identity Flow"; } }
1,001
24.692308
83
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/dataflow/IFDS/IdentityFlowFunctions.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.dataflow.IFDS; /** A silly debugging aid that always returns the identity flow function */ public class IdentityFlowFunctions<T> implements IFlowFunctionMap<T> { private static final IdentityFlowFunctions<?> SINGLETON = new IdentityFlowFunctions<>(); @SuppressWarnings("unchecked") public static <T> IdentityFlowFunctions<T> singleton() { return (IdentityFlowFunctions<T>) SINGLETON; } private IdentityFlowFunctions() {} @Override public IUnaryFlowFunction getNormalFlowFunction(T src, T dest) { return IdentityFlowFunction.identity(); } @Override public IFlowFunction getReturnFlowFunction(T call, T src, T dest) { return IdentityFlowFunction.identity(); } @Override public IUnaryFlowFunction getCallToReturnFlowFunction(T src, T dest) { return IdentityFlowFunction.identity(); } @Override public IUnaryFlowFunction getCallNoneToReturnFlowFunction(T src, T dest) { return IdentityFlowFunction.identity(); } @Override public IUnaryFlowFunction getCallFlowFunction(T src, T dest, T ret) { return IdentityFlowFunction.identity(); } }
1,501
29.04
90
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/dataflow/IFDS/KillEverything.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 * * "Restricted Materials of IBM" * * Copyright (c) 2007 IBM Corporation. * * Contributors: * IBM Corporation - initial API and implementation */ package com.ibm.wala.dataflow.IFDS; import com.ibm.wala.util.intset.SparseIntSet; /** * A flow function that kills everything (even 0) * * @author sjfink */ public class KillEverything implements IUnaryFlowFunction { private static final KillEverything INSTANCE = new KillEverything(); public static KillEverything singleton() { return INSTANCE; } private KillEverything() {} @Override public SparseIntSet getTargets(int d1) { return null; } }
1,053
21.913043
72
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/dataflow/IFDS/LocalPathEdges.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.dataflow.IFDS; import com.ibm.wala.util.collections.SparseVector; import com.ibm.wala.util.intset.BasicNaturalRelation; import com.ibm.wala.util.intset.BitVectorIntSet; import com.ibm.wala.util.intset.IBinaryNaturalRelation; import com.ibm.wala.util.intset.IntIterator; import com.ibm.wala.util.intset.IntPair; import com.ibm.wala.util.intset.IntSet; import com.ibm.wala.util.intset.MutableSparseIntSet; import com.ibm.wala.util.intset.SparseIntSet; import java.util.Iterator; /** A set of path edges for a particular procedure entry s_p. */ public class LocalPathEdges { /** Do paranoid error checking? (slow) */ private static final boolean PARANOID = false; /** * A map from integer (d2) -&gt; (IBinaryNonNegativeIntRelation) * * <p>For fact d2, paths[d2] gives a relation R=(n,d1) s.t. (&lt;s_p, d1&gt; -&gt; &lt;n,d2&gt;) * is a path edge. * * <p>Note that we handle paths of the form &lt;s_p, d1&gt; -&gt; &lt;n,d1&gt; specially, below. * We also handle paths of the form &lt;s_p, 0&gt; -&gt; &lt;n, d1> specially below. * * <p>We choose this somewhat convoluted representation for the following reasons: 1) of the (n, * d1, d2) tuple-space, we expect the set of n to be dense for a given (d1,d2) pair. However the * pairs should be sparse. So, we set up so n is the first dimension of the int-relations, which * are designed to be dense in the first dimension 2) we need to support getInverse(), so we * design lookup to get the d1's for an (n,d2) pair. * * <p>Note that this representation is not good for merges. See below. * * <p>TODO: more representation optimization. A special representation for triples? sparse * representations for CFG? exploit shorts for ints? */ private final SparseVector<IBinaryNaturalRelation> paths = new SparseVector<>(1, 1.1f); /** * If this is non-null, it holds a redundant representation of the paths information, designed to * make getReachable(II) faster. This is designed for algorithms that want to use frequent merges. * While it's a shame to waste space, I don't want to compromise space or time of the non-merging * IFDS solver, for which the original paths representation works well. Is there a better data * structure tradeoff? * * <p>A map from integer (d1) -&gt; (IBinaryNonNegativeIntRelation) * * <p>For fact d1, paths[d1] gives a relation R=(n,d2) s.t. (&lt;s_p, d1&gt; -&gt; &lt;n,d2&gt;) * is a path edge. * * <p>We choose this somewhat convoluted representation for the following reasons: 1) of the (n, * d1, d2) tuple-space, we expect the set of n to be dense for a given (d1,d2) pair. However the * pairs should be sparse. So, we set up so n is the first dimension of the int-relations, which * are designed to be dense in the first dimension 2) we need to support getReachable(), so we * design lookup to get the d2's for an (n,d1) pair. */ private final SparseVector<IBinaryNaturalRelation> altPaths; /** * a map from integer d1 -&gt; int set. * * <p>for fact d1, identityPaths[d1] gives the set of block numbers N s.t. for n \in N, &lt;s_p, * d1&gt; -&gt; &lt;n, d1&gt; is a path edge. */ private final SparseVector<IntSet> identityPaths = new SparseVector<>(1, 1.1f); /** * a map from integer d2 -&gt; int set * * <p>for fact d2, zeroPaths[d2] gives the set of block numbers N s.t. for n \in N, &lt;s_p, 0&gt; * -&gt; &lt;n, d2&gt; is a path edge. */ private final SparseVector<IntSet> zeroPaths = new SparseVector<>(1, 1.1f); /** * @param fastMerge if true, the representation uses extra space in order to support faster merge * operations */ public LocalPathEdges(boolean fastMerge) { altPaths = fastMerge ? new SparseVector<>(1, 1.1f) : null; } /** * Record that in this procedure we've discovered a same-level realizable path from (s_p,d_i) to * (n,d_j) * * @param n local block number of the basic block n */ @SuppressWarnings("unused") public void addPathEdge(int i, int n, int j) { if (i == 0) { addZeroPathEdge(n, j); } else { if (i == j) { addIdentityPathEdge(i, n); } else { IBinaryNaturalRelation R = paths.get(j); if (R == null) { // we expect the first dimension of R to be dense, the second sparse R = new BasicNaturalRelation( new byte[] {BasicNaturalRelation.SIMPLE_SPACE_STINGY}, BasicNaturalRelation.TWO_LEVEL); paths.set(j, R); } R.add(n, i); if (altPaths != null) { IBinaryNaturalRelation R2 = altPaths.get(i); if (R2 == null) { // we expect the first dimension of R to be dense, the second sparse R2 = new BasicNaturalRelation( new byte[] {BasicNaturalRelation.SIMPLE_SPACE_STINGY}, BasicNaturalRelation.TWO_LEVEL); altPaths.set(i, R2); } R2.add(n, j); } if (TabulationSolver.DEBUG_LEVEL > 1) { // System.err.println("recording path edge, now d2=" + j + " has been reached from " + R); } } } } /** * Record that in this procedure we've discovered a same-level realizable path from (s_p,i) to * (n,i) * * @param n local block number of the basic block n */ @SuppressWarnings("unused") private void addIdentityPathEdge(int i, int n) { BitVectorIntSet s = (BitVectorIntSet) identityPaths.get(i); if (s == null) { s = new BitVectorIntSet(); identityPaths.set(i, s); } s.add(n); if (altPaths != null) { IBinaryNaturalRelation R2 = altPaths.get(i); if (R2 == null) { // we expect the first dimension of R to be dense, the second sparse R2 = new BasicNaturalRelation( new byte[] {BasicNaturalRelation.SIMPLE_SPACE_STINGY}, BasicNaturalRelation.TWO_LEVEL); altPaths.set(i, R2); } R2.add(n, i); } if (TabulationSolver.DEBUG_LEVEL > 1) { System.err.println("recording self-path edge, now d1= " + i + " reaches " + s); } } /** * Record that in this procedure we've discovered a same-level realizable path from (s_p,0) to * (n,d_j) * * @param n local block number of the basic block n */ @SuppressWarnings("unused") private void addZeroPathEdge(int n, int j) { BitVectorIntSet z = (BitVectorIntSet) zeroPaths.get(j); if (z == null) { z = new BitVectorIntSet(); zeroPaths.set(j, z); } z.add(n); if (altPaths != null) { IBinaryNaturalRelation R = altPaths.get(0); if (R == null) { // we expect the first dimension of R to be dense, the second sparse R = new BasicNaturalRelation( new byte[] {BasicNaturalRelation.SIMPLE_SPACE_STINGY}, BasicNaturalRelation.TWO_LEVEL); altPaths.set(0, R); } R.add(n, j); } if (TabulationSolver.DEBUG_LEVEL > 1) { System.err.println("recording 0-path edge, now d2= " + j + " reached at " + z); } } /** * N.B: If we're using the ZERO_PATH_SHORT_CIRCUIT, then we may have &lt;s_p, d1&gt; -&gt; &lt;n, * d2&gt; implicitly represented since we also have &lt;s_p, 0&gt; -&gt; &lt;n,d2&gt;. However, * getInverse() &lt;b&gt; will NOT &lt;/b&gt; return these implicit d1 bits in the result. This * translates to saying that the caller had better not care about any other d1 other than d1==0 if * d1==0 is present. This happens to be true in the single use of getInverse() in the tabulation * solver, which uses getInverse() to propagate flow from an exit node back to the caller's return * site(s). Since we know that we will see flow from fact 0 to the return sites(s), we don't care * about other facts that may induce the same flow to the return site(s). * * @param n local block number of a basic block n * @return the sparse int set of d1 s.t. {@literal <s_p, d1> -> <n, d2>} are recorded as path * edges. null if none found */ public IntSet getInverse(int n, int d2) { IBinaryNaturalRelation R = paths.get(d2); BitVectorIntSet s = (BitVectorIntSet) identityPaths.get(d2); BitVectorIntSet z = (BitVectorIntSet) zeroPaths.get(d2); if (R == null) { if (s == null) { if (z == null) { return null; } else { return z.contains(n) ? SparseIntSet.singleton(0) : null; } } else { if (s.contains(n)) { if (z == null) { return SparseIntSet.singleton(d2); } else { return z.contains(n) ? SparseIntSet.pair(0, d2) : SparseIntSet.singleton(d2); } } else { return null; } } } else { if (s == null) { if (z == null) { return R.getRelated(n); } else { if (z.contains(n)) { IntSet related = R.getRelated(n); if (related == null) { return SparseIntSet.singleton(0); } else { MutableSparseIntSet result = MutableSparseIntSet.make(related); result.add(0); return result; } } else { return R.getRelated(n); } } } else { if (s.contains(n)) { IntSet related = R.getRelated(n); if (related == null) { if (z == null || !z.contains(n)) { return SparseIntSet.singleton(d2); } else { return SparseIntSet.pair(0, d2); } } else { MutableSparseIntSet result = MutableSparseIntSet.make(related); result.add(d2); if (z != null && z.contains(n)) { result.add(0); } return result; } } else { if (z == null || !z.contains(n)) { return R.getRelated(n); } else { IntSet related = R.getRelated(n); MutableSparseIntSet result = (related == null) ? MutableSparseIntSet.makeEmpty() : MutableSparseIntSet.make(related); result.add(0); return result; } } } } } /** * @param n local block number of a basic block n * @return true iff we have a path edge {@literal <s_p,i> -> <n, j>} */ public boolean contains(int i, int n, int j) { if (n < 0) { throw new IllegalArgumentException("invalid n: " + n); } if (i == 0) { BitVectorIntSet z = (BitVectorIntSet) zeroPaths.get(j); if (z != null && z.contains(n)) { return true; } else { return false; } } else { if (i == j) { BitVectorIntSet s = (BitVectorIntSet) identityPaths.get(i); if (s != null && s.contains(n)) { return true; } else { return false; } } else { IBinaryNaturalRelation R = paths.get(j); if (R == null) { return false; } return R.contains(n, i); } } } /** @return set of d2 s.t. d1 -&gt; d2 is a path edge for node n. */ public IntSet getReachable(int n, int d1) { if (PARANOID) { assert getReachableSlow(n, d1).sameValue(getReachableFast(n, d1)); } return (altPaths == null) ? getReachableSlow(n, d1) : getReachableFast(n, d1); } /** * Note that this is really slow!!! * * @return set of d2 s.t. d1 -&gt; d2 is a path edge for node n */ private IntSet getReachableSlow(int n, int d1) { MutableSparseIntSet result = MutableSparseIntSet.makeEmpty(); if (paths.size() > 0) { // this is convoluted on purpose for efficiency: to avoid random access to // the sparse vector, we do parallel iteration with the vector's indices // and contents. TODO: better data structure? Iterator<IBinaryNaturalRelation> contents = paths.iterator(); for (IntIterator it = paths.iterateIndices(); it.hasNext(); ) { int d2 = it.next(); IBinaryNaturalRelation R = contents.next(); if (R != null && R.contains(n, d1)) { result.add(d2); } } } if (identityPaths.size() > 0) { BitVectorIntSet s = (BitVectorIntSet) identityPaths.get(d1); if (s != null && s.contains(n)) { result.add(d1); } } if (d1 == 0 && zeroPaths.size() > 0) { // this is convoluted on purpose for efficiency: to avoid random access to // the sparse vector, we do parallel iteration with the vector's indices // and contents. TODO: better data structure? Iterator<IntSet> contents = zeroPaths.iterator(); for (IntIterator it = zeroPaths.iterateIndices(); it.hasNext(); ) { int d2 = it.next(); IntSet s = contents.next(); if (s != null && s.contains(n)) { result.add(d2); } } } return result; } /** @return set of d2 s.t. d1 -&gt; d2 is a path edge for node n */ private IntSet getReachableFast(int n, int d1) { IBinaryNaturalRelation R = altPaths.get(d1); if (R != null) { return R.getRelated(n); } return null; } /** * TODO: optimize this based on altPaths * * @param n the local block number of a node * @return set of d2 s.t \exists d1 s.t. d1 -&gt; d2 is a path edge for node n */ public IntSet getReachable(int n) { MutableSparseIntSet result = MutableSparseIntSet.makeEmpty(); if (paths.size() > 0) { // this is convoluted on purpose for efficiency: to avoid random access to // the sparse vector, we do parallel iteration with the vector's indices // and contents. TODO: better data structure? Iterator<IBinaryNaturalRelation> contents = paths.iterator(); for (IntIterator it = paths.iterateIndices(); it.hasNext(); ) { int d2 = it.next(); IBinaryNaturalRelation R = contents.next(); if (R != null && R.anyRelated(n)) { result.add(d2); } } } if (identityPaths.size() > 0) { // this is convoluted on purpose for efficiency: to avoid random access to // the sparse vector, we do parallel iteration with the vector's indices // and contents. TODO: better data structure? Iterator<IntSet> contents = identityPaths.iterator(); for (IntIterator it = identityPaths.iterateIndices(); it.hasNext(); ) { int d1 = it.next(); IntSet s = contents.next(); if (s != null && s.contains(n)) { result.add(d1); } } } if (zeroPaths.size() > 0) { // this is convoluted on purpose for efficiency: to avoid random access to // the sparse vector, we do parallel iteration with the vector's indices // and contents. TODO: better data structure? Iterator<IntSet> contents = zeroPaths.iterator(); for (IntIterator it = zeroPaths.iterateIndices(); it.hasNext(); ) { int d2 = it.next(); IntSet s = contents.next(); if (s != null && s.contains(n)) { result.add(d2); } } } return result; } /** * TODO: optimize this * * @return set of node numbers that are reached by any fact */ public IntSet getReachedNodeNumbers() { MutableSparseIntSet result = MutableSparseIntSet.makeEmpty(); if (paths.size() > 0) { for (IBinaryNaturalRelation R : paths) { for (IntPair p : R) { result.add(p.getX()); } } } if (identityPaths.size() > 0) { for (IntSet s : identityPaths) { result.addAll(s); } } if (zeroPaths.size() > 0) { for (IntSet s : zeroPaths) { result.addAll(s); } } return result; } }
16,265
33.905579
100
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/dataflow/IFDS/LocalSummaryEdges.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.dataflow.IFDS; import com.ibm.wala.util.collections.SparseVector; import com.ibm.wala.util.intset.BasicNaturalRelation; 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.MutableSparseIntSet; import com.ibm.wala.util.intset.SparseLongIntVector; import com.ibm.wala.util.math.LongUtil; /** A set of summary edges for a particular procedure. */ public class LocalSummaryEdges { /** * A map from integer n -&gt; (IBinaryNonNegativeIntRelation) * * <p>Let s_p be an entry to this procedure, and x be an exit. n is a integer which uniquely * identifies an (s_p,x) relation. For any such n, summaries[n] gives a relation R=(d1,d2) s.t. * (&lt;s_p, d1&gt; -&gt; &lt;x,d2&gt;) is a summary edge. * * <p>Note that this representation is a little different from the representation described in the * PoPL 95 paper. We cache summary edges at the CALLEE, not at the CALLER!!! This allows us to * avoid eagerly installing summary edges at all call sites to a procedure, which may be a win. * * <p>we don't technically need this class, since this information is redundantly stored in * LocalPathEdges. However, we're keeping it cached for now for more efficient access when looking * up summary edges. * * <p>TODO: more representation optimization. */ private final SparseVector<IBinaryNaturalRelation> summaries = new SparseVector<>(1, 1.1f); /** * Let (s_p,x) be an entry-exit pair, and let l := the long whose high word is s_p and low word is * x. * * <p>Then entryExitMap(l) is an int which uniquely identifies (s_p,x) * * <p>we populate this map on demand! */ private static final int UNASSIGNED = -1; private final SparseLongIntVector entryExitMap = new SparseLongIntVector(UNASSIGNED); private int nextEntryExitIndex = 0; /** */ public LocalSummaryEdges() {} /** * Record a summary edge for the flow d1 -&gt; d2 from an entry s_p to an exit x. * * @param s_p local block number an entry * @param x local block number of an exit block * @param d1 source dataflow fact * @param d2 target dataflow fact */ public void insertSummaryEdge(int s_p, int x, int d1, int d2) { int n = getIndexForEntryExitPair(s_p, x); IBinaryNaturalRelation R = summaries.get(n); if (R == null) { // we expect R to usually be sparse R = new BasicNaturalRelation( new byte[] {BasicNaturalRelation.SIMPLE_SPACE_STINGY}, BasicNaturalRelation.SIMPLE); summaries.set(n, R); } R.add(d1, d2); // if (TabulationSolver.DEBUG_LEVEL > 1) { // // System.err.println("recording summary edge, now n=" + n + " summarized by " + R); // } } /** * Does a particular summary edge exist? * * @param s_p local block number an entry * @param x local block number of an exit block * @param d1 source dataflow fact * @param d2 target dataflow fact */ public boolean contains(int s_p, int x, int d1, int d2) { int n = getIndexForEntryExitPair(s_p, x); IBinaryNaturalRelation R = summaries.get(n); if (R == null) { return false; } else { return R.contains(d1, d2); } } /** * @param s_p local block number an entry * @param x local block number of an exit block * @param d1 source dataflow fact * @return set of d2 s.t. d1 -&gt; d2 recorded as a summary edge for (s_p,x), or null if none */ public IntSet getSummaryEdges(int s_p, int x, int d1) { int n = getIndexForEntryExitPair(s_p, x); IBinaryNaturalRelation R = summaries.get(n); if (R == null) { return null; } else { return R.getRelated(d1); } } /** * Note: This is inefficient. Use with care. * * @param s_p local block number an entry * @param x local block number of an exit block * @param d2 target dataflow fact * @return set of d1 s.t. d1 -&gt; d2 recorded as a summary edge for (s_p,x), or null if none */ public IntSet getInvertedSummaryEdgesForTarget(int s_p, int x, int d2) { int n = getIndexForEntryExitPair(s_p, x); IBinaryNaturalRelation R = summaries.get(n); if (R == null) { return null; } else { MutableSparseIntSet result = MutableSparseIntSet.makeEmpty(); for (IntPair p : R) { if (p.getY() == d2) { result.add(p.getX()); } } return result; } } /** @return unique id n that represents the pair (s_p,x) */ private int getIndexForEntryExitPair(int c, int r) { long id = LongUtil.pack(c, r); int result = entryExitMap.get(id); if (result == UNASSIGNED) { result = nextEntryExitIndex++; entryExitMap.set(id, result); } return result; } }
5,224
32.928571
100
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/dataflow/IFDS/PartiallyBalancedTabulationProblem.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.dataflow.IFDS; /** * A {@link TabulationProblem} with additional support for computing with partially balanced * parentheses. * * @param <T> type of node in the supergraph * @param <P> type of a procedure (like a box in an RSM) * @param <F> type of factoids propagated when solving this problem */ public interface PartiallyBalancedTabulationProblem<T, P, F> extends TabulationProblem<T, P, F> { @Override IPartiallyBalancedFlowFunctions<T> getFunctionMap(); /** * If n is reached by a partially balanced parenthesis, what is the entry node we should use as * the root of the {@link PathEdge} to n? Note that the result <em>must</em> in fact be an entry * node of the procedure containing n. */ T getFakeEntry(T n); }
1,137
33.484848
98
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/dataflow/IFDS/PartiallyBalancedTabulationSolver.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.dataflow.IFDS; import com.ibm.wala.util.MonitorUtil.IProgressMonitor; import com.ibm.wala.util.collections.HashSetFactory; import com.ibm.wala.util.collections.Iterator2Iterable; import com.ibm.wala.util.collections.Pair; import com.ibm.wala.util.debug.Assertions; import com.ibm.wala.util.intset.IntIterator; import com.ibm.wala.util.intset.IntSet; import java.util.Collection; /** * Utilities for dealing with tabulation with partially balanced parentheses. * * @param <T> type of node in the supergraph * @param <P> type of a procedure (like a box in an RSM) * @param <F> type of factoids propagated when solving this problem */ public class PartiallyBalancedTabulationSolver<T, P, F> extends TabulationSolver<T, P, F> { public static <T, P, F> PartiallyBalancedTabulationSolver<T, P, F> createPartiallyBalancedTabulationSolver( PartiallyBalancedTabulationProblem<T, P, F> p, IProgressMonitor monitor) { return new PartiallyBalancedTabulationSolver<>(p, monitor); } private final Collection<Pair<T, Integer>> unbalancedSeeds = HashSetFactory.make(); protected PartiallyBalancedTabulationSolver( PartiallyBalancedTabulationProblem<T, P, F> p, IProgressMonitor monitor) { super(p, monitor); } @Override protected boolean propagate(T s_p, int i, T n, int j) { boolean result = super.propagate(s_p, i, n, j); if (result && wasUsedAsUnbalancedSeed(s_p, i) && supergraph.isExit(n)) { // j was reached from an entry seed. if there are any facts which are reachable from j, even // without // balanced parentheses, we can use these as new seeds. for (T retSite : Iterator2Iterable.make(supergraph.getSuccNodes(n))) { PartiallyBalancedTabulationProblem<T, P, F> problem = (PartiallyBalancedTabulationProblem<T, P, F>) getProblem(); IFlowFunction f = problem.getFunctionMap().getUnbalancedReturnFlowFunction(n, retSite); // for each fact that can be reached by the return flow ... if (f instanceof IUnaryFlowFunction) { IUnaryFlowFunction uf = (IUnaryFlowFunction) f; IntSet facts = uf.getTargets(j); if (facts != null) { for (IntIterator it4 = facts.intIterator(); it4.hasNext(); ) { int d3 = it4.next(); // d3 would be reached if we ignored parentheses. use it as a new seed. T fakeEntry = problem.getFakeEntry(retSite); PathEdge<T> seed = PathEdge.createPathEdge(fakeEntry, d3, retSite, d3); addSeed(seed); newUnbalancedExplodedReturnEdge(s_p, i, n, j); } } } else { Assertions.UNREACHABLE( "Partially balanced logic not supported for binary return flow functions"); } } } return result; } @Override public void addSeed(PathEdge<T> seed) { if (getSeeds().contains(seed)) { return; } unbalancedSeeds.add(Pair.make(seed.entry, seed.d1)); super.addSeed(seed); } /** * Was the fact number i named at node s_p introduced as an "unbalanced" seed during partial * tabulation? If so, any facts "reached" from here can be further propagated with unbalanced * parens. */ private boolean wasUsedAsUnbalancedSeed(T s_p, int i) { return unbalancedSeeds.contains(Pair.make(s_p, i)); } /** * A path edge &lt;s_p, i&gt; -&gt; &lt;n, j&gt; was propagated, and &lt;s_p, i&gt; was an * unbalanced seed. So, we added a new seed callerSeed (to some return site) in the caller. To be * overridden in subclasses. */ @SuppressWarnings("unused") protected void newUnbalancedExplodedReturnEdge(T s_p, int i, T n, int j) {} }
4,091
38.346154
99
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/dataflow/IFDS/PathEdge.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.dataflow.IFDS; /** * an individual edge &lt;entry, d1&gt; -&gt; &lt;target, d2&gt; * * @param <T> node type in the supergraph */ public final class PathEdge<T> { final T entry; final int d1; final T target; final int d2; public static <T> PathEdge<T> createPathEdge(T s_p, int d1, T n, int d2) { if (s_p == null) { throw new IllegalArgumentException("null s_p"); } if (n == null) { throw new IllegalArgumentException("null n"); } return new PathEdge<>(s_p, d1, n, d2); } private PathEdge(T s_p, int d1, T n, int d2) { this.entry = s_p; this.d1 = d1; this.target = n; this.d2 = d2; } @Override public String toString() { return '<' + entry.toString() + ',' + d1 + "> -> <" + target + ',' + d2 + '>'; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + d1; result = prime * result + d2; result = prime * result + ((target == null) ? 0 : target.hashCode()); result = prime * result + ((entry == null) ? 0 : entry.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 PathEdge<?> other = (PathEdge<?>) obj; if (d1 != other.d1) return false; if (d2 != other.d2) return false; if (target == null) { if (other.target != null) return false; } else if (!target.equals(other.target)) return false; if (entry == null) { if (other.entry != null) return false; } else if (!entry.equals(other.entry)) return false; return true; } public int getD1() { return d1; } public int getD2() { return d2; } public T getEntry() { return entry; } public T getTarget() { return target; } }
2,262
23.868132
82
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/dataflow/IFDS/SingletonFlowFunction.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.dataflow.IFDS; import com.ibm.wala.util.intset.SparseIntSet; /** A flow function which has only the edge 0 -&gt; dest */ public class SingletonFlowFunction implements IReversibleFlowFunction { private static final SparseIntSet zeroSet = SparseIntSet.singleton(0); final int dest; private SingletonFlowFunction(int dest) { this.dest = dest; } @Override public SparseIntSet getTargets(int i) { if (i == 0) { return SparseIntSet.add(zeroSet, dest); } else { return null; } } @Override public SparseIntSet getSources(int i) { if (i == dest || i == 0) { return zeroSet; } else { return null; } } public static SingletonFlowFunction create(int dest) { return new SingletonFlowFunction(dest); } }
1,174
23.479167
72
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/dataflow/IFDS/TabulationCancelException.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.dataflow.IFDS; import com.ibm.wala.util.CancelException; /** * A {@link CancelException} thrown during tabulation; holds a pointer to a partial {@link * com.ibm.wala.dataflow.IFDS.TabulationSolver.Result}. Use with care, this can hold on to a lot of * memory. */ public class TabulationCancelException extends CancelException { private static final long serialVersionUID = 4073189707860241945L; private final TabulationSolver<?, ?, ?>.Result result; protected TabulationCancelException(Exception cause, TabulationSolver<?, ?, ?>.Result r) { super(cause); this.result = r; } public TabulationSolver<?, ?, ?>.Result getResult() { return result; } }
1,069
30.470588
99
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/dataflow/IFDS/TabulationDomain.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.dataflow.IFDS; import com.ibm.wala.util.intset.OrdinalSetMapping; /** * Domain of facts for tabulation. * * @param <F> factoid type * @param <T> type of nodes in the supergraph */ public interface TabulationDomain<F, T> extends OrdinalSetMapping<F> { /** * returns {@code true} if p1 should be processed before p2 by the {@link TabulationSolver} * * <p>For example, if this domain supports a partial order on facts, return true if p1.d2 is * weaker than p2.d2 (intuitively p1.d2 meet p2.d2 = p1.d2) * * <p>return false otherwise */ boolean hasPriorityOver(PathEdge<T> p1, PathEdge<T> p2); }
1,020
29.939394
94
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/dataflow/IFDS/TabulationProblem.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.dataflow.IFDS; import java.util.Collection; /** * Representation of a Dyck-language graph reachability problem for the tabulation solver. * * <p>Special case: if supportsMerge(), then the problem is not really IFDS anymore. (TODO: rename * it?). Instead, we perform a merge operation before propagating at every program point. This way, * we can implement standard interprocedural dataflow and ESP-style property simulation, and various * other things. * * <p>Note that at the moment, the data structures in the TabulationSolver are not set up to do * merge efficiently. TODO. * * <p>See Reps, Horwitz, Sagiv POPL 95 * * @param <T> type of node in the supergraph * @param <P> type of a procedure (like a box in an RSM) * @param <F> type of factoids propagated when solving this problem */ public interface TabulationProblem<T, P, F> { ISupergraph<T, P> getSupergraph(); TabulationDomain<F, T> getDomain(); IFlowFunctionMap<T> getFunctionMap(); /** Define the set of path edges to start propagation with. */ Collection<PathEdge<T>> initialSeeds(); /** * Special case: if supportsMerge(), then the problem is not really IFDS anymore. (TODO: rename * it?). Instead, we perform a merge operation before propagating at every program point. This * way, we can implement standard interprocedural dataflow and ESP-style property simulation, and * various other things. * * @return the merge function, or null if !supportsMerge() */ IMergeFunction getMergeFunction(); }
1,915
35.150943
100
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/dataflow/IFDS/TabulationResult.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.dataflow.IFDS; import com.ibm.wala.util.intset.IntSet; import java.util.Collection; /** * The solution of a tabulation problem: a mapping from supergraph node -&gt; bit vector * representing the dataflow facts that hold at the entry to the supergraph node. * * @param <T> type of node in the supergraph * @param <P> type of a procedure, like a box in an RSM * @param <F> type of factoids propagated when solving this problem */ public interface TabulationResult<T, P, F> { /** * get the bitvector of facts that hold at IN for a given node in the supergraph. * * @param node a node in the supergraph * @return SparseIntSet efficiently representing the bitvector */ IntSet getResult(T node); /** @return the governing IFDS problem */ TabulationProblem<T, P, F> getProblem(); /** @return the set of supergraph nodes for which any fact is reached */ Collection<T> getSupergraphNodesReached(); /** * @return set of d2 s.t. (n1,d1) -&gt; (n2,d2) is recorded as a summary edge, or null if none * found */ IntSet getSummaryTargets(T n1, int d1, T n2); /** @return the set of all {@link PathEdge}s that were used as seeds during the tabulation. */ Collection<PathEdge<T>> getSeeds(); }
1,634
33.0625
96
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/dataflow/IFDS/TabulationSolver.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.dataflow.IFDS; import com.ibm.wala.cfg.IBasicBlock; import com.ibm.wala.core.util.CancelRuntimeException; import com.ibm.wala.core.util.ref.ReferenceCleanser; import com.ibm.wala.util.CancelException; import com.ibm.wala.util.MonitorUtil; import com.ibm.wala.util.MonitorUtil.IProgressMonitor; import com.ibm.wala.util.collections.HashMapFactory; import com.ibm.wala.util.collections.HashSetFactory; import com.ibm.wala.util.collections.Heap; import com.ibm.wala.util.collections.Iterator2Collection; import com.ibm.wala.util.collections.Iterator2Iterable; import com.ibm.wala.util.collections.MapUtil; import com.ibm.wala.util.collections.ToStringComparator; import com.ibm.wala.util.heapTrace.HeapTracer; import com.ibm.wala.util.intset.IntIterator; import com.ibm.wala.util.intset.IntSet; import com.ibm.wala.util.intset.IntSetAction; import com.ibm.wala.util.intset.MutableIntSet; import com.ibm.wala.util.intset.MutableSparseIntSet; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.TreeMap; import java.util.TreeSet; /** * A precise interprocedural tabulation solver. * * <p>See Reps, Horwitz, Sagiv POPL 95. * * <p>This version differs in some ways from the POPL algorithm. In particular ... * * <ul> * <li>to support exceptional control flow ... there may be several return sites for each call * site. * <li>it supports an optional merge operator, useful for non-IFDS problems and widening. * <li>it stores summary edges at each callee instead of at each call site. * </ul> * * <p> * * @param <T> type of node in the supergraph * @param <P> type of a procedure (like a box in an RSM) * @param <F> type of factoids propagated when solving this problem */ public class TabulationSolver<T, P, F> { /** * DEBUG_LEVEL: * * <ul> * <li>0 No output * <li>1 Print some simple stats and warning information * <li>2 Detailed debugging * <li>3 Also print worklists * </ul> */ protected static final int DEBUG_LEVEL = 0; protected static final boolean verbose = true && ("true".equals(System.getProperty("com.ibm.wala.fixedpoint.impl.verbose")) ? true : false); static final int VERBOSE_INTERVAL = 1000; static final boolean VERBOSE_TRACE_MEMORY = false; private static int verboseCounter = 0; /** Should we periodically clear out soft reference caches in an attempt to help the GC? */ protected static final boolean PERIODIC_WIPE_SOFT_CACHES = true; /** Interval which defines the period to clear soft reference caches */ private static final int WIPE_SOFT_CACHE_INTERVAL = 1000000; /** Counter for wiping soft caches */ private static int wipeCount = WIPE_SOFT_CACHE_INTERVAL; /** The supergraph which induces this dataflow problem */ protected final ISupergraph<T, P> supergraph; /** A map from an edge in a supergraph to a flow function */ protected final IFlowFunctionMap<T> flowFunctionMap; /** The problem being solved. */ private final TabulationProblem<T, P, F> problem; /** * A map from Object (entry node in supergraph) -&gt; LocalPathEdges. * * <p>Logically, this represents a set of edges (s_p,d_i) -&gt; (n, d_j). The data structure is * chosen to attempt to save space over representing each edge explicitly. */ private final Map<T, LocalPathEdges> pathEdges = HashMapFactory.make(); /** * A map from Object (entry node in supergraph) -&gt; CallFlowEdges. * * <p>Logically, this represents a set of edges (c,d_i) -&gt; (s_p, d_j). The data structure is * chosen to attempt to save space over representing each edge explicitly. */ private final Map<T, CallFlowEdges> callFlowEdges = HashMapFactory.make(); /** A map from Object (procedure) -&gt; LocalSummaryEdges. */ protected final Map<P, LocalSummaryEdges> summaryEdges = HashMapFactory.make(); /** * the set of all {@link PathEdge}s that were used as seeds during the tabulation, grouped by * procedure. */ private final Map<P, Set<PathEdge<T>>> seeds = HashMapFactory.make(); /** All seeds, stored redundantly for quick access. */ private final Set<PathEdge<T>> allSeeds = HashSetFactory.make(); /** The worklist */ private ITabulationWorklist<T> worklist; /** A progress monitor. can be null. */ protected final IProgressMonitor progressMonitor; /** * the path edge currently being processed in the main loop of {@link #forwardTabulateSLRPs()}; * {@code null} if {@link #forwardTabulateSLRPs()} is not currently running. Note that if we are * applying a summary edge in {@link #processExit(PathEdge)}, curPathEdge is modified to be the * path edge terminating at the call node in the caller, to match the behavior in {@link * #processCall(PathEdge)}. */ private PathEdge<T> curPathEdge; /** * the summary edge currently being applied in {@link #processCall(PathEdge)} or {@link * #processExit(PathEdge)}, or {@code null} if summary edges are not currently being processed. */ private PathEdge<T> curSummaryEdge; /** * @param p a description of the dataflow problem to solve * @throws IllegalArgumentException if p is null */ protected TabulationSolver(TabulationProblem<T, P, F> p, IProgressMonitor monitor) { if (p == null) { throw new IllegalArgumentException("p is null"); } this.supergraph = p.getSupergraph(); this.flowFunctionMap = p.getFunctionMap(); this.problem = p; this.progressMonitor = monitor; } /** Subclasses can override this to plug in a different worklist implementation. */ protected ITabulationWorklist<T> makeWorklist() { return new Worklist(); } /** * @param p a description of the dataflow problem to solve * @throws IllegalArgumentException if p is null */ public static <T, P, F> TabulationSolver<T, P, F> make(TabulationProblem<T, P, F> p) { return new TabulationSolver<>(p, null); } /** * Solve the dataflow problem. * * @return a representation of the result */ public TabulationResult<T, P, F> solve() throws CancelException { try { initialize(); forwardTabulateSLRPs(); Result r = new Result(); return r; } catch (CancelException | CancelRuntimeException e) { // store a partially-tabulated result in the thrown exception. Result r = new Result(); throw new TabulationCancelException(e, r); } } /** Start tabulation with the initial seeds. */ protected void initialize() { for (PathEdge<T> seed : problem.initialSeeds()) { addSeed(seed); } } /** Restart tabulation from a particular path edge. Use with care. */ public void addSeed(PathEdge<T> seed) { Set<PathEdge<T>> s = MapUtil.findOrCreateSet(seeds, supergraph.getProcOf(seed.entry)); s.add(seed); allSeeds.add(seed); propagate(seed.entry, seed.d1, seed.target, seed.d2); } /** See POPL 95 paper for this algorithm, Figure 3 */ @SuppressWarnings("unused") private void forwardTabulateSLRPs() throws CancelException { assert curPathEdge == null : "curPathEdge should not be non-null here"; if (worklist == null) { worklist = makeWorklist(); } while (worklist.size() > 0) { MonitorUtil.throwExceptionIfCanceled(progressMonitor); if (verbose) { performVerboseAction(); } if (PERIODIC_WIPE_SOFT_CACHES) { tendToSoftCaches(); } final PathEdge<T> edge = popFromWorkList(); if (DEBUG_LEVEL > 0) { System.err.println("TABULATE " + edge); } curPathEdge = edge; int j = merge(edge.entry, edge.d1, edge.target, edge.d2); if (j == -1 && DEBUG_LEVEL > 0) { System.err.println("merge -1: DROPPING"); } if (j != -1) { if (j != edge.d2) { // this means that we don't want to push the edge. instead, // we'll push the merged fact. a little tricky, but i think should // work. if (DEBUG_LEVEL > 0) { System.err.println("propagating merged fact " + j); } propagate(edge.entry, edge.d1, edge.target, j); } else { if (supergraph.isCall(edge.target)) { // [13] processCall(edge); } else if (supergraph.isExit(edge.target)) { // [21] processExit(edge); } else { // [33] processNormal(edge); } } } } curPathEdge = null; } /** * For some reason (either a bug in our code that defeats soft references, or a bad policy in the * GC), leaving soft reference caches to clear themselves out doesn't work. Help it out. * * <p>It's unfortunate that this method exits. */ protected void tendToSoftCaches() { wipeCount++; if (wipeCount > WIPE_SOFT_CACHE_INTERVAL) { wipeCount = 0; ReferenceCleanser.clearSoftCaches(); } } /** */ protected final void performVerboseAction() { verboseCounter++; if (verboseCounter % VERBOSE_INTERVAL == 0) { System.err.println("Tabulation Solver " + verboseCounter); System.err.println(" " + peekFromWorkList()); if (VERBOSE_TRACE_MEMORY) { ReferenceCleanser.clearSoftCaches(); System.err.println("Analyze leaks.."); HeapTracer.traceHeap(Collections.singleton(this), true); System.err.println("done analyzing leaks"); } } } /** Handle lines [33-37] of the algorithm */ @SuppressWarnings("unused") private void processNormal(final PathEdge<T> edge) { if (DEBUG_LEVEL > 0) { System.err.println("process normal: " + edge); } for (T m : Iterator2Iterable.make(supergraph.getSuccNodes(edge.target))) { if (DEBUG_LEVEL > 0) { System.err.println("normal successor: " + m); } IUnaryFlowFunction f = flowFunctionMap.getNormalFlowFunction(edge.target, m); IntSet D3 = computeFlow(edge.d2, f); if (DEBUG_LEVEL > 0) { System.err.println(" reached: " + D3); } if (D3 != null) { D3.foreach( d3 -> { newNormalExplodedEdge(edge, m, d3); propagate(edge.entry, edge.d1, m, d3); }); } } } /** * Handle lines [21 - 32] of the algorithm, propagating information from an exit node. * * <p>Note that we've changed the way we record summary edges. Summary edges are now associated * with a callee (s_p,exit), where the original algorithm used a call, return pair in the caller. */ @SuppressWarnings("unused") protected void processExit(final PathEdge<T> edge) { if (DEBUG_LEVEL > 0) { System.err.println("process exit: " + edge); } final LocalSummaryEdges summaries = findOrCreateLocalSummaryEdges(supergraph.getProcOf(edge.target)); int s_p_n = supergraph.getLocalBlockNumber(edge.entry); int x = supergraph.getLocalBlockNumber(edge.target); if (!summaries.contains(s_p_n, x, edge.d1, edge.d2)) { summaries.insertSummaryEdge(s_p_n, x, edge.d1, edge.d2); } assert curSummaryEdge == null : "curSummaryEdge should be null here"; curSummaryEdge = edge; final CallFlowEdges callFlow = findOrCreateCallFlowEdges(edge.entry); // [22] for each c /in callers(p) IntSet callFlowSourceNodes = callFlow.getCallFlowSourceNodes(edge.d1); if (callFlowSourceNodes != null) { for (IntIterator it = callFlowSourceNodes.intIterator(); it.hasNext(); ) { // [23] for each d4 s.t. <c,d4> -> <s_p,d1> occurred earlier int globalC = it.next(); final IntSet D4 = callFlow.getCallFlowSources(globalC, edge.d1); // [23] for each d5 s.t. <e_p,d2> -> <returnSite(c),d5> ... propagateToReturnSites(edge, supergraph.getNode(globalC), D4); } } curSummaryEdge = null; } /** * Propagate information for an "exit" edge to the appropriate return sites * * <p>[23] for each d5 s.t. {@literal <s_p,d2> -> <returnSite(c),d5>} .. * * @param edge the edge being processed * @param c a call site of edge.s_p * @param D4 set of d1 s.t. {@literal <c, d1> -> <edge.s_p, edge.d2>} was recorded as call flow */ @SuppressWarnings("unused") private void propagateToReturnSites(final PathEdge<T> edge, final T c, final IntSet D4) { P proc = supergraph.getProcOf(c); final T[] entries = supergraph.getEntriesForProcedure(proc); // we iterate over each potential return site; // we might have multiple return sites due to exceptions // note that we might have different summary edges for each // potential return site, and different flow functions from this // exit block to each return site. for (T retSite : Iterator2Iterable.make(supergraph.getReturnSites(c, supergraph.getProcOf(edge.target)))) { if (DEBUG_LEVEL > 1) { System.err.println( "candidate return site: " + retSite + ' ' + supergraph.getNumber(retSite)); } // note: since we might have multiple exit nodes for the callee, (to handle exceptional // returns) // not every return site might be valid for this exit node (edge.n). // so, we'll filter the logic by checking that we only process reachable return sites. // the supergraph carries the information regarding the legal successors // of the exit node if (!supergraph.hasEdge(edge.target, retSite)) { continue; } if (DEBUG_LEVEL > 1) { System.err.println("feasible return site: " + retSite); } final IFlowFunction retf = flowFunctionMap.getReturnFlowFunction(c, edge.target, retSite); if (retf instanceof IBinaryReturnFlowFunction) { propagateToReturnSiteWithBinaryFlowFunction(edge, c, D4, entries, retSite, retf); } else { final IntSet D5 = computeFlow(edge.d2, (IUnaryFlowFunction) retf); if (DEBUG_LEVEL > 1) { System.err.println("D4" + D4); System.err.println("D5 " + D5); } IntSetAction action = d4 -> propToReturnSite(c, entries, retSite, d4, D5, edge); D4.foreach(action); } } } /** * Propagate information for an "exit" edge to a caller return site * * <p>[23] for each d5 s.t. {@literal <s_p,d2> -> <returnSite(c),d5>} .. * * @param edge the edge being processed * @param c a call site of edge.s_p * @param D4 set of d1 s.t. {@literal <c, d1> -> <edge.s_p, edge.d2>} was recorded as call flow * @param entries the blocks in the supergraph that are entries for the procedure of c * @param retSite the return site being propagated to * @param retf the flow function */ private void propagateToReturnSiteWithBinaryFlowFunction( final PathEdge<T> edge, final T c, final IntSet D4, final T[] entries, final T retSite, final IFlowFunction retf) { D4.foreach( d4 -> { final IntSet D5 = computeBinaryFlow(d4, edge.d2, (IBinaryReturnFlowFunction) retf); propToReturnSite(c, entries, retSite, d4, D5, edge); }); } /** * Propagate information to a particular return site. * * @param c the corresponding call site * @param entries entry nodes in the caller * @param retSite the return site * @param d4 a fact s.t. {@literal <c, d4> -> <callee, d2>} was recorded as call flow and * {@literal <callee, d2>} is the source of the summary edge being applied * @param D5 facts to propagate to return site * @param edge the path edge ending at the exit site of the callee */ @SuppressWarnings("unused") private void propToReturnSite( final T c, final T[] entries, final T retSite, final int d4, final IntSet D5, final PathEdge<T> edge) { if (D5 != null) { D5.foreach( d5 -> { // [26 - 28] // note that we've modified the algorithm here to account // for potential // multiple entry nodes. Instead of propagating the new // summary edge // with respect to one s_profOf(c), we have to propagate // for each // potential entry node s_p /in s_procof(c) for (final T s_p : entries) { if (DEBUG_LEVEL > 1) { System.err.println(" do entry " + s_p); } IntSet D3 = getInversePathEdges(s_p, c, d4); if (DEBUG_LEVEL > 1) { System.err.println("D3" + D3); } if (D3 != null) { D3.foreach( d3 -> { // set curPathEdge to be consistent with its setting in processCall() when // applying a summary edge curPathEdge = PathEdge.createPathEdge(s_p, d3, c, d4); newSummaryEdge(curPathEdge, edge, retSite, d5); propagate(s_p, d3, retSite, d5); }); } } }); } } /** * @param d2 note that s_p must be an entry for procof(n) * @return set of d1 s.t. {@literal <s_p, d1> -> <n, d2>} is a path edge, or null if none found */ protected IntSet getInversePathEdges(T s_p, T n, int d2) { int number = supergraph.getLocalBlockNumber(n); LocalPathEdges lp = pathEdges.get(s_p); if (lp == null) { return null; } return lp.getInverse(number, d2); } /** * Handle lines [14 - 19] of the algorithm, propagating information into and across a call site. */ @SuppressWarnings("unused") protected void processCall(final PathEdge<T> edge) { if (DEBUG_LEVEL > 0) { System.err.println("process call: " + edge); } // c:= number of the call node final int c = supergraph.getNumber(edge.target); Collection<T> allReturnSites = HashSetFactory.make(); // populate allReturnSites with return sites for missing calls. for (T retSite : Iterator2Iterable.make(supergraph.getReturnSites(edge.target, null))) { allReturnSites.add(retSite); } // [14 - 16] boolean hasCallee = false; for (T callee : Iterator2Iterable.make(supergraph.getCalledNodes(edge.target))) { hasCallee = true; processParticularCallee(edge, c, allReturnSites, callee); } // special logic: in backwards problems, a "call" node can have // "normal" successors as well. deal with these. for (T m : Iterator2Iterable.make(supergraph.getNormalSuccessors(edge.target))) { if (DEBUG_LEVEL > 0) { System.err.println("normal successor: " + m); } IUnaryFlowFunction f = flowFunctionMap.getNormalFlowFunction(edge.target, m); IntSet D3 = computeFlow(edge.d2, f); if (DEBUG_LEVEL > 0) { System.err.println("normal successor reached: " + D3); } if (D3 != null) { D3.foreach( d3 -> { newNormalExplodedEdge(edge, m, d3); propagate(edge.entry, edge.d1, m, d3); }); } } // [17 - 19] // we modify this to handle each return site individually for (final T returnSite : allReturnSites) { if (DEBUG_LEVEL > 0) { System.err.println(" process return site: " + returnSite); } IUnaryFlowFunction f = null; if (hasCallee) { f = flowFunctionMap.getCallToReturnFlowFunction(edge.target, returnSite); } else { f = flowFunctionMap.getCallNoneToReturnFlowFunction(edge.target, returnSite); } IntSet reached = computeFlow(edge.d2, f); if (DEBUG_LEVEL > 0) { System.err.println("reached: " + reached); } if (reached != null) { reached.foreach( x -> { assert x >= 0; assert edge.d1 >= 0; newNormalExplodedEdge(edge, returnSite, x); propagate(edge.entry, edge.d1, returnSite, x); }); } } } /** * handle a particular callee for some call node. * * @param edge the path edge being processed * @param callNodeNum the number of the call node in the supergraph * @param allReturnSites a set collecting return sites for the call. This set is mutated with the * return sites for this callee. * @param calleeEntry the entry node of the callee in question */ @SuppressWarnings("unused") protected void processParticularCallee( final PathEdge<T> edge, final int callNodeNum, Collection<T> allReturnSites, final T calleeEntry) { if (DEBUG_LEVEL > 0) { System.err.println(" process callee: " + calleeEntry); } // reached := {d1} that reach the callee MutableSparseIntSet reached = MutableSparseIntSet.makeEmpty(); final Collection<T> returnSitesForCallee = Iterator2Collection.toSet( supergraph.getReturnSites(edge.target, supergraph.getProcOf(calleeEntry))); allReturnSites.addAll(returnSitesForCallee); // we modify this to handle each return site individually. Some types of problems // compute different flow functions for each return site. for (final T returnSite : returnSitesForCallee) { IUnaryFlowFunction f = flowFunctionMap.getCallFlowFunction(edge.target, calleeEntry, returnSite); IntSet r = computeFlow(edge.d2, f); if (r != null) { reached.addAll(r); } } // in some problems, we also want to consider flow into a callee that can never flow out // via a return. in this case, the return site is null. IUnaryFlowFunction f = flowFunctionMap.getCallFlowFunction(edge.target, calleeEntry, null); IntSet r = computeFlow(edge.d2, f); if (r != null) { reached.addAll(r); } if (DEBUG_LEVEL > 0) { System.err.println(" reached: " + reached); } if (reached != null) { final LocalSummaryEdges summaries = summaryEdges.get(supergraph.getProcOf(calleeEntry)); final CallFlowEdges callFlow = findOrCreateCallFlowEdges(calleeEntry); final int s_p_num = supergraph.getLocalBlockNumber(calleeEntry); reached.foreach( d1 -> { // we get reuse if we _don't_ propagate a new fact to the callee entry final boolean gotReuse = !propagate(calleeEntry, d1, calleeEntry, d1); recordCall(edge.target, calleeEntry, d1, gotReuse); newCallExplodedEdge(edge, calleeEntry, d1); // cache the fact that we've flowed <c, d2> -> <callee, d1> by a // call flow callFlow.addCallEdge(callNodeNum, edge.d2, d1); // handle summary edges now as well. this is different from the PoPL // 95 paper. if (summaries != null) { // for each exit from the callee P p = supergraph.getProcOf(calleeEntry); T[] exits = supergraph.getExitsForProcedure(p); for (final T exit : exits) { if (DEBUG_LEVEL > 0) { assert supergraph.containsNode(exit); } int x_num = supergraph.getLocalBlockNumber(exit); // reachedBySummary := {d2} s.t. <callee,d1> -> <exit,d2> // was recorded as a summary edge IntSet reachedBySummary = summaries.getSummaryEdges(s_p_num, x_num, d1); if (reachedBySummary != null) { for (final T returnSite : returnSitesForCallee) { // if "exit" is a valid exit from the callee to the return // site being processed if (supergraph.hasEdge(exit, returnSite)) { final IFlowFunction retf = flowFunctionMap.getReturnFlowFunction(edge.target, exit, returnSite); reachedBySummary.foreach( d2 -> { assert curSummaryEdge == null : "curSummaryEdge should be null here"; curSummaryEdge = PathEdge.createPathEdge(calleeEntry, d1, exit, d2); if (retf instanceof IBinaryReturnFlowFunction) { final IntSet D51 = computeBinaryFlow(edge.d2, d2, (IBinaryReturnFlowFunction) retf); if (D51 != null) { D51.foreach( d5 -> { newSummaryEdge(edge, curSummaryEdge, returnSite, d5); propagate(edge.entry, edge.d1, returnSite, d5); }); } } else { final IntSet D52 = computeFlow(d2, (IUnaryFlowFunction) retf); if (D52 != null) { D52.foreach( d5 -> { newSummaryEdge(edge, curSummaryEdge, returnSite, d5); propagate(edge.entry, edge.d1, returnSite, d5); }); } } curSummaryEdge = null; }); } } } } } }); } } /** * invoked when a callee is processed with a particular entry fact * * @param d1 the entry fact * @param gotReuse whether existing summary edges were applied */ @SuppressWarnings("unused") protected void recordCall(T callNode, T callee, int d1, boolean gotReuse) {} /** @return f(call_d, exit_d); */ @SuppressWarnings("unused") protected IntSet computeBinaryFlow(int call_d, int exit_d, IBinaryReturnFlowFunction f) { if (DEBUG_LEVEL > 0) { System.err.println("got binary flow function " + f); } IntSet result = f.getTargets(call_d, exit_d); return result; } /** @return f(d1) */ @SuppressWarnings("unused") protected IntSet computeFlow(int d1, IUnaryFlowFunction f) { if (DEBUG_LEVEL > 0) { System.err.println("got flow function " + f); } IntSet result = f.getTargets(d1); if (result == null) { return null; } else { return result; } } /** @return f^{-1}(d2) */ protected IntSet computeInverseFlow(int d2, IReversibleFlowFunction f) { return f.getSources(d2); } protected PathEdge<T> popFromWorkList() { assert worklist != null; return worklist.take(); } private PathEdge<T> peekFromWorkList() { // horrible. don't use in performance-critical assert worklist != null; PathEdge<T> result = worklist.take(); worklist.insert(result); return result; } /** * Propagate the fact &lt;s_p,i&gt; -&gt; &lt;n, j&gt; has arisen as a path edge. Returns * &lt;code&gt;true&lt;/code&gt; iff the path edge was not previously observed. * * @param s_p entry block * @param i dataflow fact on entry * @param n reached block * @param j dataflow fact reached */ @SuppressWarnings("unused") protected boolean propagate(T s_p, int i, T n, int j) { int number = supergraph.getLocalBlockNumber(n); if (number < 0) { System.err.println("BOOM " + n); supergraph.getLocalBlockNumber(n); } assert number >= 0; LocalPathEdges pLocal = findOrCreateLocalPathEdges(s_p); assert j >= 0; if (!pLocal.contains(i, number, j)) { if (DEBUG_LEVEL > 0) { System.err.println("propagate " + s_p + " " + i + ' ' + number + ' ' + j); } pLocal.addPathEdge(i, number, j); addToWorkList(s_p, i, n, j); return true; } return false; } public LocalPathEdges getLocalPathEdges(T s_p) { return pathEdges.get(s_p); } /** * Merging: suppose we're doing propagate &lt;s_p,i&gt; -&gt; &lt;n,j&gt; but we already have path * edges &lt;s_p,i&gt; -&gt; &lt;n, x&gt;, &lt;s_p,i&gt; -&gt; &lt;n,y&gt;, and &lt;s_p,i&gt; * -&gt;&lt;n, z&gt;. * * <p>let \alpha be the merge function. then instead of &lt;s_p,i&gt; -&gt; &lt;n,j&gt;, we * propagate &lt;s_p,i&gt; -&gt; &lt;n, \alpha(j,x,y,z) &gt; !!! * * <p>return -1 if no fact should be propagated */ private int merge(T s_p, int i, T n, int j) { assert j >= 0; IMergeFunction alpha = problem.getMergeFunction(); if (alpha != null) { LocalPathEdges lp = pathEdges.get(s_p); IntSet preExistFacts = lp.getReachable(supergraph.getLocalBlockNumber(n), i); if (preExistFacts == null) { return j; } else { int size = preExistFacts.size(); if ((size == 0) || ((size == 1) && preExistFacts.contains(j))) { return j; } else { int result = alpha.merge(preExistFacts, j); return result; } } } else { return j; } } @SuppressWarnings("unused") protected void addToWorkList(T s_p, int i, T n, int j) { if (worklist == null) { worklist = makeWorklist(); } worklist.insert(PathEdge.createPathEdge(s_p, i, n, j)); if (DEBUG_LEVEL >= 3) { System.err.println("WORKLIST: " + worklist); } } protected LocalPathEdges findOrCreateLocalPathEdges(T s_p) { LocalPathEdges result = pathEdges.get(s_p); if (result == null) { result = makeLocalPathEdges(); pathEdges.put(s_p, result); } return result; } private LocalPathEdges makeLocalPathEdges() { return problem.getMergeFunction() == null ? new LocalPathEdges(false) : new LocalPathEdges(true); } protected LocalSummaryEdges findOrCreateLocalSummaryEdges(P proc) { LocalSummaryEdges result = summaryEdges.get(proc); if (result == null) { result = new LocalSummaryEdges(); summaryEdges.put(proc, result); } return result; } protected CallFlowEdges findOrCreateCallFlowEdges(T s_p) { CallFlowEdges result = callFlowEdges.get(s_p); if (result == null) { result = new CallFlowEdges(); callFlowEdges.put(s_p, result); } return result; } /** * get the bitvector of facts that hold at the entry to a given node * * @return IntSet representing the bitvector */ public IntSet getResult(T node) { P proc = supergraph.getProcOf(node); int n = supergraph.getLocalBlockNumber(node); T[] entries = supergraph.getEntriesForProcedure(proc); MutableIntSet result = MutableSparseIntSet.makeEmpty(); Set<T> allEntries = HashSetFactory.make(Arrays.asList(entries)); Set<PathEdge<T>> pSeeds = seeds.get(proc); if (pSeeds != null) { for (PathEdge<T> seed : pSeeds) { allEntries.add(seed.entry); } } for (T entry : allEntries) { LocalPathEdges lp = pathEdges.get(entry); if (lp != null) { result.addAll(lp.getReachable(n)); } } return result; } public class Result implements TabulationResult<T, P, F> { /** * get the bitvector of facts that hold at the entry to a given node * * @return IntSet representing the bitvector */ @Override public IntSet getResult(T node) { return TabulationSolver.this.getResult(node); } @Override public String toString() { StringBuilder result = new StringBuilder(); TreeMap<Object, TreeSet<T>> map = new TreeMap<>(ToStringComparator.instance()); Comparator<Object> c = (o1, o2) -> { if (!(o1 instanceof IBasicBlock)) { return -1; } IBasicBlock<?> bb1 = (IBasicBlock<?>) o1; IBasicBlock<?> bb2 = (IBasicBlock<?>) o2; return bb1.getNumber() - bb2.getNumber(); }; for (T n : supergraph) { P proc = supergraph.getProcOf(n); TreeSet<T> s = map.computeIfAbsent(proc, k -> new TreeSet<>(c)); s.add(n); } for (Entry<Object, TreeSet<T>> e : map.entrySet()) { Set<T> s = e.getValue(); for (T o : s) { result.append(o).append(" : ").append(getResult(o)).append('\n'); } } return result.toString(); } @Override public TabulationProblem<T, P, F> getProblem() { return problem; } @Override public Collection<T> getSupergraphNodesReached() { Collection<T> result = HashSetFactory.make(); for (Entry<T, LocalPathEdges> e : pathEdges.entrySet()) { T key = e.getKey(); P proc = supergraph.getProcOf(key); IntSet reached = e.getValue().getReachedNodeNumbers(); for (IntIterator ii = reached.intIterator(); ii.hasNext(); ) { result.add(supergraph.getLocalBlock(proc, ii.next())); } } return result; } /** * @return set of d2 s.t. (n1,d1) -&gt; (n2,d2) is recorded as a summary edge, or null if none * found */ @Override public IntSet getSummaryTargets(T n1, int d1, T n2) { LocalSummaryEdges summaries = summaryEdges.get(supergraph.getProcOf(n1)); if (summaries == null) { return null; } int num1 = supergraph.getLocalBlockNumber(n1); int num2 = supergraph.getLocalBlockNumber(n2); return summaries.getSummaryEdges(num1, num2, d1); } @Override public Collection<PathEdge<T>> getSeeds() { return TabulationSolver.this.getSeeds(); } } /** @return Returns the supergraph. */ public ISupergraph<T, P> getSupergraph() { return supergraph; } protected class Worklist extends Heap<PathEdge<T>> implements ITabulationWorklist<T> { Worklist() { super(100); } @Override protected boolean compareElements(PathEdge<T> p1, PathEdge<T> p2) { return problem.getDomain().hasPriorityOver(p1, p2); } } /** * @return set of d1 s.t. (n1,d1) -&gt; (n2,d2) is recorded as a summary edge, or null if none * found * @throws UnsupportedOperationException unconditionally */ @SuppressWarnings("unused") public IntSet getSummarySources(T n2, int d2, T n1) throws UnsupportedOperationException { throw new UnsupportedOperationException("not currently supported. be careful"); // LocalSummaryEdges summaries = summaryEdges.get(supergraph.getProcOf(n1)); // if (summaries == null) { // return null; // } // int num1 = supergraph.getLocalBlockNumber(n1); // int num2 = supergraph.getLocalBlockNumber(n2); // return summaries.getInvertedSummaryEdgesForTarget(num1, num2, d2); } public TabulationProblem<T, P, F> getProblem() { return problem; } public Collection<PathEdge<T>> getSeeds() { return Collections.unmodifiableCollection(allSeeds); } public IProgressMonitor getProgressMonitor() { return progressMonitor; } protected PathEdge<T> getCurPathEdge() { return curPathEdge; } protected PathEdge<T> getCurSummaryEdge() { return curSummaryEdge; } /** * Indicates that due to a path edge &lt;s_p, d1&gt; -&gt; &lt;n, d2&gt; (the 'edge' parameter) * and a normal flow function application, a new path edge &lt;s_p, d1&gt; -&gt; &lt;m, d3&gt; was * created. To be overridden in subclasses. We also use this function to record call-to-return * flow. */ @SuppressWarnings("unused") protected void newNormalExplodedEdge(PathEdge<T> edge, T m, int d3) {} /** * Indicates that due to a path edge 'edge' &lt;s_p, d1&gt; -&gt; &lt;n, d2&gt; and application of * a call flow function, a new path edge &lt;calleeEntry, d3&gt; -&gt; &lt;calleeEntry, d3&gt; was * created. To be overridden in subclasses. */ @SuppressWarnings("unused") protected void newCallExplodedEdge(PathEdge<T> edge, T calleeEntry, int d3) {} /** * Combines [25] and [26-28]. In the caller we have a path edge 'edgeToCallSite' &lt;s_c, d3&gt; * -&gt; &lt;c, d4&gt;, where c is the call site. In the callee, we have path edge * 'calleeSummaryEdge' &lt;s_p, d1&gt; -&gt; &lt;e_p, d2&gt;. Of course, there is a call edge * &lt;c, d4&gt; -&gt; &lt;s_p, d1&gt;. Finally, we have a return edge &lt;e_p, d2&gt; -&gt; * &lt;returnSite, d5&gt;. */ @SuppressWarnings("unused") protected void newSummaryEdge( PathEdge<T> edgeToCallSite, PathEdge<T> calleeSummaryEdge, T returnSite, int d5) {} }
36,835
34.148855
100
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/dataflow/IFDS/UnorderedDomain.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.dataflow.IFDS; import com.ibm.wala.util.intset.MutableMapping; /** A {@link TabulationDomain} with no build-in partial order defining priority. */ public class UnorderedDomain<T, U> extends MutableMapping<T> implements TabulationDomain<T, U> { private static final long serialVersionUID = -988075488958891635L; @Override public boolean hasPriorityOver(PathEdge<U> p1, PathEdge<U> p2) { return false; } }
816
31.68
96
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/dataflow/IFDS/VectorGenFlowFunction.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.dataflow.IFDS; import com.ibm.wala.util.intset.IntSet; import com.ibm.wala.util.intset.SparseIntSet; /** A function which gens a vector of outgoing dataflow facts. */ public class VectorGenFlowFunction implements IReversibleFlowFunction { private final IntSet gen; /** * @param gen the intset of facts which are gen'ned by this flow function. gen <em>must</em> * contain 0. */ private VectorGenFlowFunction(IntSet gen) { this.gen = gen; assert gen.contains(0); } @Override public IntSet getTargets(int i) { return (i == 0) ? gen : gen.contains(i) ? null : SparseIntSet.singleton(i); } @Override public IntSet getSources(int i) { return gen.contains(i) ? SparseIntSet.singleton(0) : SparseIntSet.singleton(i); } /** * @param gen the intset of facts which should be gen'ed by a function * @return an instance of a flow function which gens these facts */ public static VectorGenFlowFunction make(IntSet gen) { if (gen == null) { throw new IllegalArgumentException("null gen"); } return new VectorGenFlowFunction(gen); } @Override public String toString() { return "VectorGen: " + gen; } }
1,582
27.267857
94
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/dataflow/IFDS/VectorKillFlowFunction.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.dataflow.IFDS; import com.ibm.wala.util.intset.IntSet; import com.ibm.wala.util.intset.SparseIntSet; /** A function which kills a vector of incoming dataflow facts */ public class VectorKillFlowFunction implements IReversibleFlowFunction { private final IntSet kill; /** @param kill the intset of facts which are killed by this flow function */ private VectorKillFlowFunction(IntSet kill) { if (kill == null) { throw new IllegalArgumentException("null kill"); } this.kill = kill; } @Override public IntSet getTargets(int i) { return kill.contains(i) ? null : SparseIntSet.singleton(i); } @Override public IntSet getSources(int i) { return kill.contains(i) ? null : SparseIntSet.singleton(i); } /** * @param kill the intset of facts which should be killed by a function * @return an instance of a flow function which kills these facts */ public static VectorKillFlowFunction make(IntSet kill) { return new VectorKillFlowFunction(kill); } @Override public String toString() { return "VectorKill: " + kill; } }
1,487
27.615385
79
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/dataflow/ssa/SSAInference.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.dataflow.ssa; import com.ibm.wala.analysis.typeInference.TypeInference; import com.ibm.wala.fixedpoint.impl.DefaultFixedPointSolver; import com.ibm.wala.fixedpoint.impl.NullaryOperator; import com.ibm.wala.fixpoint.AbstractOperator; import com.ibm.wala.fixpoint.IVariable; import com.ibm.wala.ssa.IR; import com.ibm.wala.ssa.SSAInstruction; import com.ibm.wala.ssa.SymbolTable; import com.ibm.wala.util.collections.Iterator2Iterable; import java.util.ArrayList; import java.util.List; /** * This class performs intra-procedural propagation over an SSA form. * * <p>A client will subclass an {@link SSAInference} by providing factories that generate {@link * IVariable}s corresponding to SSA value numbers, and {@link AbstractOperator}s corresponding to * SSA instructions. This class will set up a dataflow system induced by the SSA def-use graph, and * solve the system by iterating to a fixed point. * * @see TypeInference for the canonical client of this machinery. */ public abstract class SSAInference<T extends IVariable<T>> extends DefaultFixedPointSolver<T> { static final boolean DEBUG = false; /** The governing SSA form */ private IR ir; /** The governing symbol table */ private SymbolTable symbolTable; /** Dataflow variables, one for each value in the symbol table. */ private List<IVariable<T>> vars; public interface OperatorFactory<T extends IVariable<T>> { /** * Get the dataflow operator induced by an instruction in SSA form. * * @return dataflow operator for the instruction, or null if the instruction is not applicable * to the dataflow system. */ AbstractOperator<T> get(SSAInstruction instruction); } public interface VariableFactory<T extends IVariable<T>> { /** * Make the variable for a given value number. * * @return a newly created dataflow variable, or null if not applicable. */ IVariable<T> makeVariable(int valueNumber); } /** initializer for SSA Inference equations. */ protected void init(IR ir, VariableFactory<T> varFactory, OperatorFactory<T> opFactory) { this.ir = ir; this.symbolTable = ir.getSymbolTable(); createVariables(varFactory); createEquations(opFactory); } private void createEquations(OperatorFactory<T> opFactory) { SSAInstruction[] instructions = ir.getInstructions(); for (SSAInstruction s : instructions) { makeEquationForInstruction(opFactory, s); } for (SSAInstruction s : Iterator2Iterable.make(ir.iteratePhis())) { makeEquationForInstruction(opFactory, s); } for (SSAInstruction s : Iterator2Iterable.make(ir.iteratePis())) { makeEquationForInstruction(opFactory, s); } for (SSAInstruction s : Iterator2Iterable.make(ir.iterateCatchInstructions())) { makeEquationForInstruction(opFactory, s); } } /** Create a dataflow equation induced by a given instruction */ private void makeEquationForInstruction(OperatorFactory<T> opFactory, SSAInstruction s) { if (s != null && s.hasDef()) { AbstractOperator<T> op = opFactory.get(s); if (op != null) { T def = getVariable(s.getDef()); if (op instanceof NullaryOperator) { newStatement(def, (NullaryOperator<T>) op, false, false); } else { int n = s.getNumberOfUses(); T[] uses = makeStmtRHS(n); for (int j = 0; j < n; j++) { if (s.getUse(j) > -1) { uses[j] = getVariable(s.getUse(j)); assert uses[j] != null; } } newStatement(def, op, uses, false, false); } } } } /** Create a dataflow variable for each value number */ private void createVariables(VariableFactory<T> factory) { //noinspection unchecked final int varsCount = symbolTable.getMaxValueNumber() + 1; vars = new ArrayList<>(varsCount); vars.add(null); for (int i = 1; i < varsCount; i++) { vars.add(factory.makeVariable(i)); } } /** @return the dataflow variable representing the value number, or null if none found. */ @SuppressWarnings("unchecked") protected T getVariable(int valueNumber) { if (valueNumber < 0) { throw new IllegalArgumentException("Illegal valueNumber " + valueNumber); } if (DEBUG) { System.err.println("getVariable for " + valueNumber + " returns " + vars.get(valueNumber)); } assert vars != null : "null vars array"; return (T) vars.get(valueNumber); } /** * Return a string representation of the system * * @return a string representation of the system */ @Override public String toString() { StringBuilder result = new StringBuilder("Type inference : \n"); for (int i = 0; i < vars.size(); i++) { result.append('v').append(i).append(" ").append(vars.get(i)).append('\n'); } return result.toString(); } }
5,288
33.344156
99
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/demandpa/alg/AbstractDemandPointsTo.java
/* * This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html. * * This file is a derivative of code released by the University of * California under the terms listed below. * * Refinement Analysis Tools is Copyright (c) 2007 The Regents of the * University of California (Regents). Provided that this notice and * the following two paragraphs are included in any distribution of * Refinement Analysis Tools or its derivative work, Regents agrees * not to assert any of Regents' copyright rights in Refinement * Analysis Tools against recipient for recipient's reproduction, * preparation of derivative works, public display, public * performance, distribution or sublicensing of Refinement Analysis * Tools and derivative works, in source code and object code form. * This agreement not to assert does not confer, by implication, * estoppel, or otherwise any license or rights in any intellectual * property of Regents, including, but not limited to, any patents * of Regents or Regents' employees. * * IN NO EVENT SHALL REGENTS BE LIABLE TO ANY PARTY FOR DIRECT, * INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, * INCLUDING LOST PROFITS, ARISING OUT OF THE USE OF THIS SOFTWARE * AND ITS DOCUMENTATION, EVEN IF REGENTS HAS BEEN ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * REGENTS SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE AND FURTHER DISCLAIMS ANY STATUTORY * WARRANTY OF NON-INFRINGEMENT. THE SOFTWARE AND ACCOMPANYING * DOCUMENTATION, IF ANY, PROVIDED HEREUNDER IS PROVIDED "AS * IS". REGENTS HAS NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, * UPDATES, ENHANCEMENTS, OR MODIFICATIONS. */ package com.ibm.wala.demandpa.alg; import com.ibm.wala.demandpa.util.MemoryAccessMap; import com.ibm.wala.ipa.callgraph.AnalysisOptions; import com.ibm.wala.ipa.callgraph.CallGraph; import com.ibm.wala.ipa.callgraph.propagation.HeapModel; import com.ibm.wala.ipa.cha.IClassHierarchy; /** * Abstract super class for demand points-to analysis. Implements basic methods for tracking how * much traversal has been done. * * @author Manu Sridharan */ public abstract class AbstractDemandPointsTo implements IDemandPointerAnalysis { protected final CallGraph cg; protected final HeapModel heapModel; protected final MemoryAccessMap mam; protected final IClassHierarchy cha; protected final AnalysisOptions options; protected int numNodesTraversed; private int traversalBudget = Integer.MAX_VALUE; public int getTraversalBudget() { return traversalBudget; } protected void setTraversalBudget(int traversalBudget) { this.traversalBudget = traversalBudget; } public AbstractDemandPointsTo( CallGraph cg, HeapModel model, MemoryAccessMap mam, IClassHierarchy cha, AnalysisOptions options) { this.cg = cg; this.heapModel = model; this.mam = mam; this.cha = cha; this.options = options; } @Override public HeapModel getHeapModel() { return heapModel; } /** */ protected void incrementNumNodesTraversed() { if (numNodesTraversed > traversalBudget) { throw new BudgetExceededException(); } numNodesTraversed++; } protected void setNumNodesTraversed(int traversed) { numNodesTraversed = traversed; } public int getNumNodesTraversed() { return numNodesTraversed; } @Override public CallGraph getBaseCallGraph() { return cg; } @Override public IClassHierarchy getClassHierarchy() { return cha; } }
3,777
30.22314
96
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/demandpa/alg/BudgetExceededException.java
/* * This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html. * * This file is a derivative of code released by the University of * California under the terms listed below. * * Refinement Analysis Tools is Copyright (c) 2007 The Regents of the * University of California (Regents). Provided that this notice and * the following two paragraphs are included in any distribution of * Refinement Analysis Tools or its derivative work, Regents agrees * not to assert any of Regents' copyright rights in Refinement * Analysis Tools against recipient for recipient's reproduction, * preparation of derivative works, public display, public * performance, distribution or sublicensing of Refinement Analysis * Tools and derivative works, in source code and object code form. * This agreement not to assert does not confer, by implication, * estoppel, or otherwise any license or rights in any intellectual * property of Regents, including, but not limited to, any patents * of Regents or Regents' employees. * * IN NO EVENT SHALL REGENTS BE LIABLE TO ANY PARTY FOR DIRECT, * INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, * INCLUDING LOST PROFITS, ARISING OUT OF THE USE OF THIS SOFTWARE * AND ITS DOCUMENTATION, EVEN IF REGENTS HAS BEEN ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * REGENTS SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE AND FURTHER DISCLAIMS ANY STATUTORY * WARRANTY OF NON-INFRINGEMENT. THE SOFTWARE AND ACCOMPANYING * DOCUMENTATION, IF ANY, PROVIDED HEREUNDER IS PROVIDED "AS * IS". REGENTS HAS NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, * UPDATES, ENHANCEMENTS, OR MODIFICATIONS. */ package com.ibm.wala.demandpa.alg; /** * Exception thrown when a demand-driven points-to query exceeds its allocated budget. * * @author Manu Sridharan */ public class BudgetExceededException extends RuntimeException { private static final long serialVersionUID = -797000809257983053L; }
2,214
44.204082
86
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/demandpa/alg/CallStack.java
/* * This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html. * * This file is a derivative of code released by the University of * California under the terms listed below. * * Refinement Analysis Tools is Copyright (c) 2007 The Regents of the * University of California (Regents). Provided that this notice and * the following two paragraphs are included in any distribution of * Refinement Analysis Tools or its derivative work, Regents agrees * not to assert any of Regents' copyright rights in Refinement * Analysis Tools against recipient for recipient's reproduction, * preparation of derivative works, public display, public * performance, distribution or sublicensing of Refinement Analysis * Tools and derivative works, in source code and object code form. * This agreement not to assert does not confer, by implication, * estoppel, or otherwise any license or rights in any intellectual * property of Regents, including, but not limited to, any patents * of Regents or Regents' employees. * * IN NO EVENT SHALL REGENTS BE LIABLE TO ANY PARTY FOR DIRECT, * INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, * INCLUDING LOST PROFITS, ARISING OUT OF THE USE OF THIS SOFTWARE * AND ITS DOCUMENTATION, EVEN IF REGENTS HAS BEEN ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * REGENTS SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE AND FURTHER DISCLAIMS ANY STATUTORY * WARRANTY OF NON-INFRINGEMENT. THE SOFTWARE AND ACCOMPANYING * DOCUMENTATION, IF ANY, PROVIDED HEREUNDER IS PROVIDED "AS * IS". REGENTS HAS NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, * UPDATES, ENHANCEMENTS, OR MODIFICATIONS. */ package com.ibm.wala.demandpa.alg; import com.ibm.wala.demandpa.alg.statemachine.StateMachine.State; import com.ibm.wala.ipa.callgraph.propagation.cfa.CallerSiteContext; import com.ibm.wala.util.collections.ImmutableStack; /** Representation for a calling context. */ public class CallStack extends ImmutableStack<CallerSiteContext> implements State { public static CallStack emptyCallStack() { CallStack ret = new CallStack(new CallerSiteContext[0]); return ret; } protected CallStack(CallerSiteContext[] entries) { super(entries); } @Override protected CallStack makeStack(CallerSiteContext[] tmpEntries) { return new CallStack(tmpEntries); } @Override protected CallerSiteContext[] makeInternalArray(int size) { return new CallerSiteContext[size]; } @Override public CallStack pop() { final CallStack ret = (CallStack) super.pop(); return ret; } @Override public CallStack push(CallerSiteContext entry) { final CallStack ret = (CallStack) super.push(entry); return ret; } }
2,971
37.102564
83
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/demandpa/alg/ContextSensitiveStateMachine.java
/* * This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html. * * This file is a derivative of code released by the University of * California under the terms listed below. * * Refinement Analysis Tools is Copyright (c) 2007 The Regents of the * University of California (Regents). Provided that this notice and * the following two paragraphs are included in any distribution of * Refinement Analysis Tools or its derivative work, Regents agrees * not to assert any of Regents' copyright rights in Refinement * Analysis Tools against recipient for recipient's reproduction, * preparation of derivative works, public display, public * performance, distribution or sublicensing of Refinement Analysis * Tools and derivative works, in source code and object code form. * This agreement not to assert does not confer, by implication, * estoppel, or otherwise any license or rights in any intellectual * property of Regents, including, but not limited to, any patents * of Regents or Regents' employees. * * IN NO EVENT SHALL REGENTS BE LIABLE TO ANY PARTY FOR DIRECT, * INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, * INCLUDING LOST PROFITS, ARISING OUT OF THE USE OF THIS SOFTWARE * AND ITS DOCUMENTATION, EVEN IF REGENTS HAS BEEN ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * REGENTS SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE AND FURTHER DISCLAIMS ANY STATUTORY * WARRANTY OF NON-INFRINGEMENT. THE SOFTWARE AND ACCOMPANYING * DOCUMENTATION, IF ANY, PROVIDED HEREUNDER IS PROVIDED "AS * IS". REGENTS HAS NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, * UPDATES, ENHANCEMENTS, OR MODIFICATIONS. */ package com.ibm.wala.demandpa.alg; import com.ibm.wala.demandpa.alg.statemachine.StateMachine; import com.ibm.wala.demandpa.alg.statemachine.StateMachineFactory; import com.ibm.wala.demandpa.alg.statemachine.StatesMergedException; import com.ibm.wala.demandpa.flowgraph.AssignBarLabel; import com.ibm.wala.demandpa.flowgraph.AssignGlobalBarLabel; import com.ibm.wala.demandpa.flowgraph.AssignGlobalLabel; import com.ibm.wala.demandpa.flowgraph.AssignLabel; import com.ibm.wala.demandpa.flowgraph.GetFieldBarLabel; import com.ibm.wala.demandpa.flowgraph.GetFieldLabel; import com.ibm.wala.demandpa.flowgraph.IFlowLabel; import com.ibm.wala.demandpa.flowgraph.IFlowLabel.IFlowLabelVisitor; import com.ibm.wala.demandpa.flowgraph.MatchBarLabel; import com.ibm.wala.demandpa.flowgraph.MatchLabel; import com.ibm.wala.demandpa.flowgraph.NewBarLabel; import com.ibm.wala.demandpa.flowgraph.NewLabel; import com.ibm.wala.demandpa.flowgraph.ParamBarLabel; import com.ibm.wala.demandpa.flowgraph.ParamLabel; import com.ibm.wala.demandpa.flowgraph.PutFieldBarLabel; import com.ibm.wala.demandpa.flowgraph.PutFieldLabel; import com.ibm.wala.demandpa.flowgraph.ReturnBarLabel; import com.ibm.wala.demandpa.flowgraph.ReturnLabel; import com.ibm.wala.ipa.callgraph.propagation.cfa.CallerSiteContext; import com.ibm.wala.util.collections.HashSetFactory; import java.util.Collection; import java.util.HashSet; /** * A state machine for tracking calling context during a points-to query. Filters unrealizable * paths. */ public class ContextSensitiveStateMachine implements StateMachine<IFlowLabel> { private static final boolean DEBUG = false; private static final boolean DEBUG_RECURSION = false; /** The empty call stack. Note that the empty stack essentially represents all possible states. */ private final CallStack emptyStack = CallStack.emptyCallStack(); @Override public CallStack getStartState() { return emptyStack; } private final RecursionHandler recursionHandler; private class CSLabelVisitor implements IFlowLabelVisitor { final CallStack prevStack; State nextState = null; CSLabelVisitor(CallStack prevStack) { this.prevStack = prevStack; } @Override public void visitAssign(AssignLabel label, Object dst) { nextState = prevStack; } @Override public void visitAssignBar(AssignBarLabel label, Object dst) { nextState = prevStack; } @Override public void visitAssignGlobal(AssignGlobalLabel label, Object dst) { nextState = emptyStack; } @Override public void visitAssignGlobalBar(AssignGlobalBarLabel label, Object dst) { nextState = emptyStack; } @Override public void visitGetField(GetFieldLabel label, Object dst) { nextState = prevStack; } @Override public void visitGetFieldBar(GetFieldBarLabel label, Object dst) { nextState = prevStack; } @Override public void visitMatch(MatchLabel label, Object dst) { nextState = emptyStack; } @Override public void visitMatchBar(MatchBarLabel label, Object dst) { nextState = emptyStack; } @Override public void visitNew(NewLabel label, Object dst) { nextState = prevStack; } @Override public void visitNewBar(NewBarLabel label, Object dst) { nextState = prevStack; } @Override public void visitParam(ParamLabel label, Object dst) { handleMethodExit(label.getCallSite()); } private void handleMethodExit(CallerSiteContext callSite) { if (recursionHandler.isRecursive(callSite)) { nextState = prevStack; } else if (prevStack.isEmpty()) { nextState = prevStack; } else if (prevStack.peek().equals(callSite)) { nextState = prevStack.pop(); } else { nextState = ERROR; } } @Override public void visitParamBar(ParamBarLabel label, Object dst) { // method entry handleMethodEntry(label.getCallSite()); } private void handleMethodEntry(CallerSiteContext callSite) { if (recursionHandler.isRecursive(callSite)) { // just ignore it; we don't track recursive calls nextState = prevStack; } else if (prevStack.contains(callSite)) { if (DEBUG_RECURSION) { System.err.println("FOUND RECURSION"); System.err.println("stack " + prevStack + " contains " + callSite); } CallerSiteContext topCallSite = null; CallStack tmpStack = prevStack; // mark the appropriate call sites as recursive // and pop them Collection<CallerSiteContext> newRecursiveSites = HashSetFactory.make(); do { topCallSite = tmpStack.peek(); newRecursiveSites.add(topCallSite); tmpStack = tmpStack.pop(); } while (!topCallSite.equals(callSite) && !tmpStack.isEmpty()); recursionHandler.makeRecursive(newRecursiveSites); // here we throw the states merged exception to indicate // that recursion was detected // ideally, we would update all relevant data structures and continue, // but it greatly complicates the analysis implementation throw new StatesMergedException(); } else { nextState = prevStack.push(callSite); } } @Override public void visitPutField(PutFieldLabel label, Object dst) { nextState = prevStack; } @Override public void visitPutFieldBar(PutFieldBarLabel label, Object dst) { nextState = prevStack; } @Override public void visitReturn(ReturnLabel label, Object dst) { handleMethodEntry(label.getCallSite()); } @Override public void visitReturnBar(ReturnBarLabel label, Object dst) { handleMethodExit(label.getCallSite()); } } @Override public State transition(State prevState, IFlowLabel label) throws IllegalArgumentException, IllegalArgumentException { if (prevState == null) { throw new IllegalArgumentException("prevState == null"); } if (!(prevState instanceof CallStack)) { throw new IllegalArgumentException( "not ( prevState instanceof com.ibm.wala.demandpa.alg.CallStack ) "); } CallStack prevStack = (CallStack) prevState; if (!prevStack.isEmpty() && recursionHandler.isRecursive(prevStack.peek())) { // I don't think this is possible anymore assert false; // just pop off the call site return transition(prevStack.pop(), label); } CSLabelVisitor v = new CSLabelVisitor(prevStack); label.visit(v, null); if (DEBUG) { if (prevStack != v.nextState && v.nextState != ERROR) { System.err.println("prev stack " + prevStack); System.err.println("label " + label); System.err.println("recursive call sites " + recursionHandler); System.err.println("next stack " + v.nextState); } } return v.nextState; } private ContextSensitiveStateMachine(RecursionHandler recursionHandler) { this.recursionHandler = recursionHandler; } public static class Factory implements StateMachineFactory<IFlowLabel> { private final RecursionHandler prototype; public Factory(RecursionHandler prototype) { this.prototype = prototype; } public Factory() { this(new BasicRecursionHandler()); } @Override public StateMachine<IFlowLabel> make() { return new ContextSensitiveStateMachine(prototype.makeNew()); } } public interface RecursionHandler { boolean isRecursive(CallerSiteContext callSite); void makeRecursive(Collection<CallerSiteContext> callSites); /** in lieu of creating factories */ RecursionHandler makeNew(); } /** * handles method recursion by only collapsing cycles of recursive calls observed during analysis */ public static class BasicRecursionHandler implements RecursionHandler { private final HashSet<CallerSiteContext> recursiveCallSites = HashSetFactory.make(); @Override public boolean isRecursive(CallerSiteContext callSite) { return recursiveCallSites.contains(callSite); } @Override public void makeRecursive(Collection<CallerSiteContext> callSites) { recursiveCallSites.addAll(callSites); } @Override public RecursionHandler makeNew() { return new BasicRecursionHandler(); } } }
10,304
32.786885
100
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/demandpa/alg/DemandRefinementPointsTo.java
/* * This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html. * * This file is a derivative of code released by the University of * California under the terms listed below. * * Refinement Analysis Tools is Copyright (c) 2007 The Regents of the * University of California (Regents). Provided that this notice and * the following two paragraphs are included in any distribution of * Refinement Analysis Tools or its derivative work, Regents agrees * not to assert any of Regents' copyright rights in Refinement * Analysis Tools against recipient for recipient's reproduction, * preparation of derivative works, public display, public * performance, distribution or sublicensing of Refinement Analysis * Tools and derivative works, in source code and object code form. * This agreement not to assert does not confer, by implication, * estoppel, or otherwise any license or rights in any intellectual * property of Regents, including, but not limited to, any patents * of Regents or Regents' employees. * * IN NO EVENT SHALL REGENTS BE LIABLE TO ANY PARTY FOR DIRECT, * INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, * INCLUDING LOST PROFITS, ARISING OUT OF THE USE OF THIS SOFTWARE * AND ITS DOCUMENTATION, EVEN IF REGENTS HAS BEEN ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * REGENTS SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE AND FURTHER DISCLAIMS ANY STATUTORY * WARRANTY OF NON-INFRINGEMENT. THE SOFTWARE AND ACCOMPANYING * DOCUMENTATION, IF ANY, PROVIDED HEREUNDER IS PROVIDED "AS * IS". REGENTS HAS NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, * UPDATES, ENHANCEMENTS, OR MODIFICATIONS. */ package com.ibm.wala.demandpa.alg; import com.ibm.wala.analysis.reflection.InstanceKeyWithNode; import com.ibm.wala.classLoader.CallSiteReference; import com.ibm.wala.classLoader.IClass; import com.ibm.wala.classLoader.IField; import com.ibm.wala.classLoader.IMethod; import com.ibm.wala.classLoader.ShrikeBTMethod; import com.ibm.wala.demandpa.alg.refinepolicy.NeverRefineCGPolicy; import com.ibm.wala.demandpa.alg.refinepolicy.NeverRefineFieldsPolicy; import com.ibm.wala.demandpa.alg.refinepolicy.RefinementPolicy; import com.ibm.wala.demandpa.alg.refinepolicy.RefinementPolicyFactory; import com.ibm.wala.demandpa.alg.refinepolicy.SinglePassRefinementPolicy; import com.ibm.wala.demandpa.alg.statemachine.StateMachine; import com.ibm.wala.demandpa.alg.statemachine.StateMachine.State; import com.ibm.wala.demandpa.alg.statemachine.StateMachineFactory; import com.ibm.wala.demandpa.alg.statemachine.StatesMergedException; import com.ibm.wala.demandpa.flowgraph.AbstractFlowGraph; import com.ibm.wala.demandpa.flowgraph.AbstractFlowLabelVisitor; import com.ibm.wala.demandpa.flowgraph.AssignBarLabel; import com.ibm.wala.demandpa.flowgraph.AssignGlobalBarLabel; import com.ibm.wala.demandpa.flowgraph.AssignGlobalLabel; import com.ibm.wala.demandpa.flowgraph.AssignLabel; import com.ibm.wala.demandpa.flowgraph.DemandPointerFlowGraph; import com.ibm.wala.demandpa.flowgraph.GetFieldLabel; import com.ibm.wala.demandpa.flowgraph.IFlowGraph; import com.ibm.wala.demandpa.flowgraph.IFlowLabel; import com.ibm.wala.demandpa.flowgraph.IFlowLabel.IFlowLabelVisitor; import com.ibm.wala.demandpa.flowgraph.IFlowLabelWithFilter; import com.ibm.wala.demandpa.flowgraph.MatchBarLabel; import com.ibm.wala.demandpa.flowgraph.MatchLabel; import com.ibm.wala.demandpa.flowgraph.NewLabel; import com.ibm.wala.demandpa.flowgraph.ParamBarLabel; import com.ibm.wala.demandpa.flowgraph.ParamLabel; import com.ibm.wala.demandpa.flowgraph.PutFieldLabel; import com.ibm.wala.demandpa.flowgraph.ReturnBarLabel; import com.ibm.wala.demandpa.flowgraph.ReturnLabel; import com.ibm.wala.demandpa.util.ArrayContents; import com.ibm.wala.demandpa.util.MemoryAccess; import com.ibm.wala.demandpa.util.MemoryAccessMap; import com.ibm.wala.demandpa.util.PointerParamValueNumIterator; import com.ibm.wala.ipa.callgraph.AnalysisOptions; import com.ibm.wala.ipa.callgraph.CGNode; import com.ibm.wala.ipa.callgraph.CallGraph; import com.ibm.wala.ipa.callgraph.propagation.AbstractLocalPointerKey; import com.ibm.wala.ipa.callgraph.propagation.FilteredPointerKey; import com.ibm.wala.ipa.callgraph.propagation.FilteredPointerKey.MultipleClassesFilter; import com.ibm.wala.ipa.callgraph.propagation.FilteredPointerKey.SingleClassFilter; import com.ibm.wala.ipa.callgraph.propagation.FilteredPointerKey.SingleInstanceFilter; import com.ibm.wala.ipa.callgraph.propagation.FilteredPointerKey.TypeFilter; import com.ibm.wala.ipa.callgraph.propagation.HeapModel; import com.ibm.wala.ipa.callgraph.propagation.InstanceFieldKey; import com.ibm.wala.ipa.callgraph.propagation.InstanceKey; import com.ibm.wala.ipa.callgraph.propagation.LocalPointerKey; import com.ibm.wala.ipa.callgraph.propagation.PointerAnalysis; import com.ibm.wala.ipa.callgraph.propagation.PointerKey; import com.ibm.wala.ipa.callgraph.propagation.ReturnValueKey; import com.ibm.wala.ipa.callgraph.propagation.StaticFieldKey; import com.ibm.wala.ipa.callgraph.propagation.cfa.CallerSiteContext; import com.ibm.wala.ipa.callgraph.propagation.cfa.ExceptionReturnValueKey; import com.ibm.wala.ipa.cha.IClassHierarchy; import com.ibm.wala.shrike.shrikeBT.IInstruction; import com.ibm.wala.shrike.shrikeCT.InvalidClassFileException; import com.ibm.wala.ssa.IR; import com.ibm.wala.ssa.SSAAbstractInvokeInstruction; import com.ibm.wala.ssa.SSAArrayStoreInstruction; import com.ibm.wala.ssa.SSAInstruction; import com.ibm.wala.ssa.SSANewInstruction; import com.ibm.wala.ssa.SSAPutInstruction; import com.ibm.wala.util.collections.ArraySet; import com.ibm.wala.util.collections.ArraySetMultiMap; import com.ibm.wala.util.collections.HashMapFactory; import com.ibm.wala.util.collections.HashSetFactory; import com.ibm.wala.util.collections.HashSetMultiMap; import com.ibm.wala.util.collections.Iterator2Collection; import com.ibm.wala.util.collections.Iterator2Iterable; import com.ibm.wala.util.collections.MapIterator; import com.ibm.wala.util.collections.MultiMap; import com.ibm.wala.util.collections.Pair; import com.ibm.wala.util.collections.Util; import com.ibm.wala.util.debug.Assertions; import com.ibm.wala.util.debug.UnimplementedError; import com.ibm.wala.util.intset.IntSet; import com.ibm.wala.util.intset.MutableIntSet; import com.ibm.wala.util.intset.MutableIntSetFactory; import com.ibm.wala.util.intset.MutableMapping; import com.ibm.wala.util.intset.MutableSparseIntSet; import com.ibm.wala.util.intset.MutableSparseIntSetFactory; import com.ibm.wala.util.intset.OrdinalSet; import com.ibm.wala.util.intset.OrdinalSetMapping; import java.util.ArrayDeque; import java.util.Collection; import java.util.Collections; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedHashSet; import java.util.Map; import java.util.Set; import java.util.function.Function; import java.util.function.Predicate; /** Demand-driven refinement-based points-to analysis. */ public class DemandRefinementPointsTo extends AbstractDemandPointsTo { private static final boolean DEBUG = false; private static final boolean DEBUG_TOPLEVEL = false; private static final boolean PARANOID = false; private static final boolean MEASURE_MEMORY_USAGE = false; protected final IFlowGraph g; private StateMachineFactory<IFlowLabel> stateMachineFactory; /** the state machine for additional filtering of paths */ private StateMachine<IFlowLabel> stateMachine; protected RefinementPolicy refinementPolicy; private RefinementPolicyFactory refinementPolicyFactory; public RefinementPolicy getRefinementPolicy() { return refinementPolicy; } private DemandRefinementPointsTo( CallGraph cg, ThisFilteringHeapModel model, MemoryAccessMap fam, IClassHierarchy cha, AnalysisOptions options, StateMachineFactory<IFlowLabel> stateMachineFactory, IFlowGraph flowGraph) { super(cg, model, fam, cha, options); this.stateMachineFactory = stateMachineFactory; g = flowGraph; this.refinementPolicyFactory = new SinglePassRefinementPolicy.Factory( new NeverRefineFieldsPolicy(), new NeverRefineCGPolicy()); sanityCheckCG(); } private void sanityCheckCG() { if (PARANOID) { for (CGNode callee : cg) { for (CGNode caller : Iterator2Iterable.make(cg.getPredNodes(callee))) { for (CallSiteReference site : Iterator2Iterable.make(cg.getPossibleSites(caller, callee))) { try { caller.getIR().getCalls(site); } catch (IllegalArgumentException e) { System.err.println(caller + " is pred of " + callee); System.err.println("no calls at site " + site); System.err.println(caller.getIR()); if (caller.getMethod() instanceof ShrikeBTMethod) { try { IInstruction[] instructions = ((ShrikeBTMethod) caller.getMethod()).getInstructions(); for (int i = 0; i < instructions.length; i++) { System.err.println(i + ": " + instructions[i]); } } catch (InvalidClassFileException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } } Assertions.UNREACHABLE(); } } } } } } /** * Possible results of a query. * * @see DemandRefinementPointsTo#getPointsTo(PointerKey, Predicate) * @author manu */ public enum PointsToResult { /** The points-to set result satisfies the supplied {@link Predicate} */ SUCCESS, /** * The {@link RefinementPolicy} indicated that no more refinement was possible, <em>and</em> on * at least one refinement pass the budget was not exhausted */ NOMOREREFINE, /** * The budget specified in the {@link RefinementPolicy} was exceeded on all refinement passes */ BUDGETEXCEEDED } /** re-initialize state for a new query */ protected void startNewQuery() { // re-init the refinement policy refinementPolicy = refinementPolicyFactory.make(); // re-init the state machine stateMachine = stateMachineFactory.make(); } /** * compute a points-to set for a pointer key, aiming to satisfy some predicate * * @param pk the pointer key * @param ikeyPred the desired predicate that each instance key in the points-to set should * ideally satisfy * @return a pair consisting of (1) a {@link PointsToResult} indicating whether a points-to set * satisfying the predicate was computed, and (2) the last computed points-to set for the * variable (possibly {@code null} if no points-to set could be computed in the budget) * @throws IllegalArgumentException if {@code pk} is not a {@link LocalPointerKey}; to eventually * be fixed */ public Pair<PointsToResult, Collection<InstanceKey>> getPointsTo( PointerKey pk, Predicate<InstanceKey> ikeyPred) throws IllegalArgumentException { Pair<PointsToResult, Collection<InstanceKeyAndState>> p = getPointsToWithStates(pk, ikeyPred); final Collection<InstanceKeyAndState> p2SetWithStates = p.snd; Collection<InstanceKey> finalP2Set = p2SetWithStates != null ? removeStates(p2SetWithStates) : Collections.<InstanceKey>emptySet(); return Pair.make(p.fst, finalP2Set); } private Pair<PointsToResult, Collection<InstanceKeyAndState>> getPointsToWithStates( PointerKey pk, Predicate<InstanceKey> ikeyPred) { if (!(pk instanceof com.ibm.wala.ipa.callgraph.propagation.LocalPointerKey)) { throw new IllegalArgumentException("only locals for now"); } LocalPointerKey queriedPk = (LocalPointerKey) pk; if (DEBUG) { System.err.println("answering query for " + pk); } startNewQuery(); Pair<PointsToResult, Collection<InstanceKeyAndState>> p = outerRefinementLoop( new PointerKeyAndState(queriedPk, stateMachine.getStartState()), ikeyPred); return p; } /** * Unwrap a Collection of WithState<T> objects, returning a Collection containing the wrapped * objects */ private static <T> Collection<T> removeStates( final Collection<? extends WithState<T>> p2SetWithStates) { if (p2SetWithStates == null) { throw new IllegalArgumentException("p2SetWithStates == null"); } Collection<T> finalP2Set = Iterator2Collection.toSet( new MapIterator<WithState<T>, T>(p2SetWithStates.iterator(), WithState::getWrapped)); return finalP2Set; } /** * create a demand points-to analysis runner * * @param cg the underlying call graph for the analysis * @param model the heap model to be used for the analysis * @param mam indicates what code reads or writes each field * @param stateMachineFactory factory for state machines to track additional properties like * calling context */ public static DemandRefinementPointsTo makeWithDefaultFlowGraph( CallGraph cg, HeapModel model, MemoryAccessMap mam, IClassHierarchy cha, AnalysisOptions options, StateMachineFactory<IFlowLabel> stateMachineFactory) { final ThisFilteringHeapModel thisFilteringHeapModel = new ThisFilteringHeapModel(model, cha); return new DemandRefinementPointsTo( cg, thisFilteringHeapModel, mam, cha, options, stateMachineFactory, new DemandPointerFlowGraph(cg, thisFilteringHeapModel, mam, cha)); } private Pair<PointsToResult, Collection<InstanceKeyAndState>> outerRefinementLoop( PointerKeyAndState queried, Predicate<InstanceKey> ikeyPred) { Collection<InstanceKeyAndState> lastP2Set = null; boolean succeeded = false; int numPasses = refinementPolicy.getNumPasses(); int passNum = 0; for (; passNum < numPasses; passNum++) { setNumNodesTraversed(0); setTraversalBudget(refinementPolicy.getBudgetForPass(passNum)); Collection<InstanceKeyAndState> curP2Set = null; PointsToComputer computer = null; boolean completedPassInBudget = false; try { while (true) { try { computer = new PointsToComputer(queried); computer.compute(); curP2Set = computer.getComputedP2Set(queried); // System.err.println("completed pass"); if (DEBUG) { System.err.println("traversed " + getNumNodesTraversed() + " nodes"); System.err.println("POINTS-TO SET " + curP2Set); } completedPassInBudget = true; break; } catch (StatesMergedException e) { if (DEBUG) { System.err.println("restarting..."); } } } } catch (BudgetExceededException e) { } if (curP2Set != null) { if (lastP2Set == null) { lastP2Set = curP2Set; } else if (lastP2Set.size() > curP2Set.size()) { // got a more precise set assert removeStates(lastP2Set).containsAll(removeStates(curP2Set)); lastP2Set = curP2Set; } else { // new set size is >= lastP2Set, so don't update assert removeStates(curP2Set).containsAll(removeStates(lastP2Set)); } if (curP2Set.isEmpty() || passesPred(curP2Set, ikeyPred)) { // we did it! // if (curP2Set.isEmpty()) { // System.err.println("EMPTY PTO SET"); // } succeeded = true; break; } else if (completedPassInBudget) { } } // if we get here, means either budget for pass was exceeded, // or points-to set wasn't good enough // so, start new pass, if more refinement to do if (!refinementPolicy.nextPass()) { break; } } PointsToResult result = null; if (succeeded) { result = PointsToResult.SUCCESS; } else if (passNum == numPasses) { // we ran all the passes without succeeding and // without the refinement policy giving up result = PointsToResult.BUDGETEXCEEDED; } else { if (lastP2Set != null) { result = PointsToResult.NOMOREREFINE; } else { // we stopped before the maximum number of passes, but we never // actually finished a pass, so we count this as BUDGETEXCEEDED result = PointsToResult.BUDGETEXCEEDED; } } return Pair.make(result, lastP2Set); } /** to measure memory usage */ public long lastQueryMemoryUse; /** * check if the points-to set of a variable passes some predicate, without necessarily computing * the whole points-to set * * @param pk the pointer key * @param ikeyPred the desired predicate that each instance key in the points-to set should * ideally satisfy * @param pa a pre-computed points-to analysis * @return a {@link PointsToResult} indicating whether a points-to set satisfying the predicate * was computed * @throws IllegalArgumentException if {@code pk} is not a {@link LocalPointerKey}; to eventually * be fixed */ public PointsToResult pointsToPassesPred( PointerKey pk, Predicate<InstanceKey> ikeyPred, PointerAnalysis<InstanceKey> pa) throws IllegalArgumentException { if (!(pk instanceof com.ibm.wala.ipa.callgraph.propagation.LocalPointerKey)) { throw new IllegalArgumentException("only locals for now"); } LocalPointerKey queriedPk = (LocalPointerKey) pk; if (DEBUG) { System.err.println("answering query for " + pk); } boolean succeeded = false; startNewQuery(); int numPasses = refinementPolicy.getNumPasses(); int passNum = 0; boolean completedSomePass = false; if (MEASURE_MEMORY_USAGE) { lastQueryMemoryUse = -1; } for (; passNum < numPasses; passNum++) { setNumNodesTraversed(0); setTraversalBudget(refinementPolicy.getBudgetForPass(passNum)); boolean completedPassInBudget = false; boolean passed = false; long initialMemory = 0; try { while (true) { try { if (MEASURE_MEMORY_USAGE) { initialMemory = Util.getUsedMemory(); } PointsToComputer computer = new PointsToComputer(queriedPk); passed = doTopLevelTraversal(queriedPk, ikeyPred, computer, pa); // System.err.println("completed pass"); if (DEBUG) { System.err.println("traversed " + getNumNodesTraversed() + " nodes"); } completedPassInBudget = true; completedSomePass = true; break; } catch (StatesMergedException e) { if (DEBUG) { System.err.println("restarting..."); } } finally { if (MEASURE_MEMORY_USAGE) { long memoryAfterPass = Util.getUsedMemory(); assert initialMemory != 0; long usedByPass = memoryAfterPass - initialMemory; if (usedByPass > lastQueryMemoryUse) { lastQueryMemoryUse = usedByPass; if (usedByPass > 20000000) { System.err.println("DOH!"); System.exit(1); } } } } } } catch (BudgetExceededException e) { } if (completedPassInBudget) { if (passed) { succeeded = true; break; } } // if we get here, means either budget for pass was exceeded, // or points-to set wasn't good enough // so, start new pass, if more refinement to do if (!refinementPolicy.nextPass()) { break; } } PointsToResult result = null; if (succeeded) { result = PointsToResult.SUCCESS; } else if (passNum == numPasses) { // we ran all the passes without succeeding and // without the refinement policy giving up result = PointsToResult.BUDGETEXCEEDED; } else { result = completedSomePass ? PointsToResult.NOMOREREFINE : PointsToResult.BUDGETEXCEEDED; } if (MEASURE_MEMORY_USAGE) { System.err.println("memory " + lastQueryMemoryUse); } return result; } /** do all instance keys in p2set pass ikeyPred? */ private static boolean passesPred( Collection<InstanceKeyAndState> curP2Set, final Predicate<InstanceKey> ikeyPred) { return Util.forAll(curP2Set, t -> ikeyPred.test(t.getInstanceKey())); } /** * @return the points-to set of {@code pk}, or {@code null} if the points-to set can't be computed * in the allocated budget */ @Override public Collection<InstanceKey> getPointsTo(PointerKey pk) { return getPointsTo(pk, k -> false).snd; } /** * @return the points-to set of {@code pk}, including the {@link State}s attached to the {@link * InstanceKey}s, or {@code null} if the points-to set can't be computed in the allocated * budget */ public Collection<InstanceKeyAndState> getPointsToWithStates(PointerKey pk) { return getPointsToWithStates(pk, k -> false).snd; } /** * get all the pointer keys that some instance key can flow to * * @return a pair consisting of (1) a {@link PointsToResult} indicating whether a flows-to set was * computed, and (2) the last computed flows-to set for the instance key (possibly {@code * null} if no flows-to set could be computed in the budget) */ public Pair<PointsToResult, Collection<PointerKey>> getFlowsTo(InstanceKey ik) { startNewQuery(); return getFlowsToInternal(new InstanceKeyAndState(ik, stateMachine.getStartState())); } /** * get all the pointer keys that some instance key with state can flow to * * @return a pair consisting of (1) a {@link PointsToResult} indicating whether a flows-to set was * computed, and (2) the last computed flows-to set for the instance key (possibly {@code * null} if no flows-to set could be computed in the budget) */ public Pair<PointsToResult, Collection<PointerKey>> getFlowsTo(InstanceKeyAndState ikAndState) { startNewQuery(); return getFlowsToInternal(ikAndState); } private Pair<PointsToResult, Collection<PointerKey>> getFlowsToInternal( InstanceKeyAndState ikAndState) { InstanceKey ik = ikAndState.getInstanceKey(); if (!(ik instanceof InstanceKeyWithNode)) { assert false : "TODO: handle " + ik.getClass(); } if (DEBUG) { System.err.println("answering flows-to query for " + ikAndState); } Collection<PointerKeyAndState> lastFlowsToSet = null; boolean succeeded = false; int numPasses = refinementPolicy.getNumPasses(); int passNum = 0; for (; passNum < numPasses; passNum++) { setNumNodesTraversed(0); setTraversalBudget(refinementPolicy.getBudgetForPass(passNum)); Collection<PointerKeyAndState> curFlowsToSet = null; FlowsToComputer computer = null; try { while (true) { try { computer = new FlowsToComputer(ikAndState); computer.compute(); curFlowsToSet = computer.getComputedFlowsToSet(); // System.err.println("completed pass"); if (DEBUG) { System.err.println("traversed " + getNumNodesTraversed() + " nodes"); System.err.println("FLOWS-TO SET " + curFlowsToSet); } break; } catch (StatesMergedException e) { if (DEBUG) { System.err.println("restarting..."); } } } } catch (BudgetExceededException e) { } if (curFlowsToSet != null) { if (lastFlowsToSet == null) { lastFlowsToSet = curFlowsToSet; } else if (lastFlowsToSet.size() > curFlowsToSet.size()) { // got a more precise set assert removeStates(lastFlowsToSet).containsAll(removeStates(curFlowsToSet)); lastFlowsToSet = curFlowsToSet; } else { // new set size is >= lastP2Set, so don't update // TODO what is wrong with this assertion?!? --MS // assert removeStates(curFlowsToSet).containsAll(removeStates(lastFlowsToSet)); } // TODO add predicate support if (curFlowsToSet.isEmpty() /* || passesPred(curFlowsToSet, ikeyPred) */) { succeeded = true; break; } } // if we get here, means either budget for pass was exceeded, // or points-to set wasn't good enough // so, start new pass, if more refinement to do if (!refinementPolicy.nextPass()) { break; } } PointsToResult result = null; if (succeeded) { result = PointsToResult.SUCCESS; } else if (passNum == numPasses) { // we ran all the passes without succeeding and // without the refinement policy giving up result = PointsToResult.BUDGETEXCEEDED; } else { if (lastFlowsToSet != null) { result = PointsToResult.NOMOREREFINE; } else { // we stopped before the maximum number of passes, but we never // actually finished a pass, so we count this as BUDGETEXCEEDED result = PointsToResult.BUDGETEXCEEDED; } } return Pair.make(result, lastFlowsToSet == null ? null : removeStates(lastFlowsToSet)); } /** * Closure indicating how to handle copies between {@link PointerKey}s. * * @author Manu Sridharan */ private abstract static class CopyHandler { abstract void handle(PointerKeyAndState src, PointerKey dst, IFlowLabel label); } /** * Representation of a statement storing a value into a field. * * @author Manu Sridharan */ private static final class StoreEdge { // // Represents statement of the form base.field = val final PointerKeyAndState base; final IField field; final PointerKeyAndState val; @Override public int hashCode() { final int PRIME = 31; int result = 1; result = PRIME * result + val.hashCode(); result = PRIME * result + field.hashCode(); result = PRIME * result + base.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 StoreEdge other = (StoreEdge) obj; if (!val.equals(other.val)) return false; if (!field.equals(other.field)) return false; if (!base.equals(other.base)) return false; return true; } public StoreEdge( final PointerKeyAndState base, final IField field, final PointerKeyAndState val) { this.base = base; this.field = field; this.val = val; } } /** * Representation of a field read. * * @author Manu Sridharan */ private static final class LoadEdge { // Represents statements of the form val = base.field final PointerKeyAndState base; final IField field; final PointerKeyAndState val; @Override public String toString() { return val + " := " + base + ", field " + field; } @Override public int hashCode() { final int PRIME = 31; int result = 1; result = PRIME * result + val.hashCode(); result = PRIME * result + field.hashCode(); result = PRIME * result + base.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 LoadEdge other = (LoadEdge) obj; if (!val.equals(other.val)) return false; if (!field.equals(other.field)) return false; if (!base.equals(other.base)) return false; return true; } public LoadEdge( final PointerKeyAndState base, final IField field, final PointerKeyAndState val) { this.base = base; this.field = field; this.val = val; } } /** * Points-to analysis algorithm code. * * <p>Pseudocode in Chapter 5 of Manu Sridharan's dissertation. * * @author Manu Sridharan */ protected class PointsToComputer { protected final PointerKeyAndState queriedPkAndState; /** map from pointer key to states in which the key's points-to set was queried */ private final MultiMap<PointerKey, State> pointsToQueried = HashSetMultiMap.make(); /** map from pointer key to states in which a tracked points-to set for the key was computed */ private final MultiMap<PointerKey, State> trackedQueried = HashSetMultiMap.make(); /** forward worklist: for initially processing points-to queries */ private final Collection<PointerKeyAndState> initWorklist = new LinkedHashSet<>(); /** worklist for variables whose points-to set has been updated */ private final Collection<PointerKeyAndState> pointsToWorklist = new LinkedHashSet<>(); /** worklist for variables whose tracked points-to set has been updated */ private final Collection<PointerKeyAndState> trackedPointsToWorklist = new LinkedHashSet<>(); /** maps a pointer key to those on-the-fly virtual calls for which it is the receiver */ private final MultiMap<PointerKeyAndState, CallerSiteContext> pkToOTFCalls = HashSetMultiMap.make(); /** cache of the targets discovered for a call site during on-the-fly call graph construction */ private final MultiMap<CallerSiteContext, IMethod> callToOTFTargets = ArraySetMultiMap.make(); // alloc nodes to the fields we're looking to match on them, // matching getfield with putfield private final MultiMap<InstanceKeyAndState, IField> forwInstKeyToFields = HashSetMultiMap.make(); // matching putfield_bar with getfield_bar private final MultiMap<InstanceKeyAndState, IField> backInstKeyToFields = HashSetMultiMap.make(); // points-to sets and tracked points-to sets protected final Map<PointerKeyAndState, MutableIntSet> pkToP2Set = HashMapFactory.make(); protected final Map<PointerKeyAndState, MutableIntSet> pkToTrackedSet = HashMapFactory.make(); private final Map<InstanceFieldKeyAndState, MutableIntSet> instFieldKeyToP2Set = HashMapFactory.make(); private final Map<InstanceFieldKeyAndState, MutableIntSet> instFieldKeyToTrackedSet = HashMapFactory.make(); /** for numbering {@link InstanceKey}, {@link State} pairs */ protected final OrdinalSetMapping<InstanceKeyAndState> ikAndStates = MutableMapping.make(); private final MutableIntSetFactory<MutableSparseIntSet> intSetFactory = new MutableSparseIntSetFactory(); // new // BitVectorIntSetFactory(); /** tracks all field stores encountered during traversal */ private final HashSet<StoreEdge> encounteredStores = HashSetFactory.make(); /** tracks all field loads encountered during traversal */ private final HashSet<LoadEdge> encounteredLoads = HashSetFactory.make(); /** * use this with care! only for subclasses that aren't computing points-to information exactly * (e.g., {@link FlowsToComputer}) */ protected PointsToComputer() { queriedPkAndState = null; } protected PointsToComputer(PointerKey pk) { queriedPkAndState = new PointerKeyAndState(pk, stateMachine.getStartState()); } protected PointsToComputer(PointerKeyAndState pkAndState) { this.queriedPkAndState = pkAndState; } private OrdinalSet<InstanceKeyAndState> makeOrdinalSet(IntSet intSet) { // make a copy here, to avoid comodification during iteration // TODO remove the copying, do it only at necessary call sites return new OrdinalSet<>(intSetFactory.makeCopy(intSet), ikAndStates); } /** * get a points-to set that has already been computed via some previous call to {@link * #compute()}; does _not_ do any fresh demand-driven computation. */ public Collection<InstanceKeyAndState> getComputedP2Set(PointerKeyAndState queried) { return Iterator2Collection.toSet(makeOrdinalSet(find(pkToP2Set, queried)).iterator()); // return Iterator2Collection.toSet(new MapIterator<InstanceKeyAndState, // InstanceKey>(makeOrdinalSet( // find(pkToP2Set, new PointerKeyAndState(lpk, stateMachine.getStartState()))).iterator(), // new Function<InstanceKeyAndState, InstanceKey>() { // // public InstanceKey apply(InstanceKeyAndState object) { // return object.getInstanceKey(); // } // // })); } @SuppressWarnings("unused") protected boolean addAllToP2Set( Map<PointerKeyAndState, MutableIntSet> p2setMap, PointerKeyAndState pkAndState, IntSet vals, IFlowLabel label) { final PointerKey pk = pkAndState.getPointerKey(); if (pk instanceof FilteredPointerKey) { if (DEBUG) { System.err.println("handling filtered pointer key " + pk); } final TypeFilter typeFilter = ((FilteredPointerKey) pk).getTypeFilter(); vals = updateValsForFilter(vals, typeFilter); } if (label instanceof IFlowLabelWithFilter) { TypeFilter typeFilter = ((IFlowLabelWithFilter) label).getFilter(); if (typeFilter != null) { vals = updateValsForFilter(vals, typeFilter); } } boolean added = findOrCreate(p2setMap, pkAndState).addAll(vals); // final boolean added = p2setMap.putAll(pkAndState, vals); if (DEBUG && added) { System.err.println("POINTS-TO ADDITION TO PK " + pkAndState + ':'); for (InstanceKeyAndState ikAndState : makeOrdinalSet(vals)) { System.err.println(ikAndState); } System.err.println("*************"); } return added; } private IntSet updateValsForFilter(IntSet vals, final TypeFilter typeFilter) { if (typeFilter instanceof SingleClassFilter) { final IClass concreteType = ((SingleClassFilter) typeFilter).getConcreteType(); final MutableIntSet tmp = intSetFactory.make(); vals.foreach( x -> { InstanceKeyAndState ikAndState = ikAndStates.getMappedObject(x); if (cha.isAssignableFrom( concreteType, ikAndState.getInstanceKey().getConcreteType())) { tmp.add(x); } }); vals = tmp; } else if (typeFilter instanceof MultipleClassesFilter) { final MutableIntSet tmp = intSetFactory.make(); vals.foreach( x -> { InstanceKeyAndState ikAndState = ikAndStates.getMappedObject(x); for (IClass t : ((MultipleClassesFilter) typeFilter).getConcreteTypes()) { if (cha.isAssignableFrom(t, ikAndState.getInstanceKey().getConcreteType())) { tmp.add(x); } } }); vals = tmp; } else if (typeFilter instanceof SingleInstanceFilter) { final InstanceKey theOnlyInstanceKey = ((SingleInstanceFilter) typeFilter).getInstance(); final MutableIntSet tmp = intSetFactory.make(); vals.foreach( x -> { InstanceKeyAndState ikAndState = ikAndStates.getMappedObject(x); if (ikAndState.getInstanceKey().equals(theOnlyInstanceKey)) { tmp.add(x); } }); vals = tmp; } else { Assertions.UNREACHABLE(); } return vals; } protected void compute() { final CGNode node = ((LocalPointerKey) queriedPkAndState.getPointerKey()).getNode(); if (hasNullIR(node)) { return; } g.addSubgraphForNode(node); addToInitWorklist(queriedPkAndState); worklistLoop(); } protected void worklistLoop() { do { while (!initWorklist.isEmpty() || !pointsToWorklist.isEmpty() || !trackedPointsToWorklist.isEmpty()) { handleInitWorklist(); handlePointsToWorklist(); handleTrackedPointsToWorklist(); } makePassOverFieldStmts(); } while (!initWorklist.isEmpty() || !pointsToWorklist.isEmpty() || !trackedPointsToWorklist.isEmpty()); } void handleCopy( final PointerKeyAndState curPkAndState, final PointerKey succPk, final IFlowLabel label) { assert !label.isBarred(); State curState = curPkAndState.getState(); doTransition( curState, label, nextState -> { PointerKeyAndState succPkAndState = new PointerKeyAndState(succPk, nextState); handleCopy(curPkAndState, succPkAndState, label); return null; }); } void handleCopy( PointerKeyAndState curPkAndState, PointerKeyAndState succPkAndState, IFlowLabel label) { if (!addToInitWorklist(succPkAndState)) { // handle like x = y with Y updated if (addAllToP2Set(pkToP2Set, curPkAndState, find(pkToP2Set, succPkAndState), label)) { addToPToWorklist(curPkAndState); } } } void handleAllCopies( PointerKeyAndState curPk, Iterator<? extends Object> succNodes, IFlowLabel label) { while (succNodes.hasNext()) { handleCopy(curPk, (PointerKey) succNodes.next(), label); } } /** * @param label the label of the edge from curPk to predPk (must be barred) * @return those {@link PointerKeyAndState}s whose points-to sets have been queried, such that * the {@link PointerKey} is predPk, and transitioning from its state on {@code label.bar()} * yields the state of {@code curPkAndState} */ protected Collection<PointerKeyAndState> matchingPToQueried( PointerKeyAndState curPkAndState, PointerKey predPk, IFlowLabel label) { Collection<PointerKeyAndState> ret = ArraySet.make(); assert label.isBarred(); IFlowLabel unbarredLabel = label.bar(); final State curState = curPkAndState.getState(); Set<State> predPkStates = pointsToQueried.get(predPk); for (State predState : predPkStates) { State transState = stateMachine.transition(predState, unbarredLabel); if (transState.equals(curState)) { // we have a winner! ret.add(new PointerKeyAndState(predPk, predState)); } } return ret; } Collection<PointerKeyAndState> matchingTrackedQueried( PointerKeyAndState curPkAndState, PointerKey succPk, IFlowLabel label) { Collection<PointerKeyAndState> ret = ArraySet.make(); assert label.isBarred(); final State curState = curPkAndState.getState(); Set<State> succPkStates = trackedQueried.get(succPk); for (State succState : succPkStates) { State transState = stateMachine.transition(succState, label); if (transState.equals(curState)) { ret.add(new PointerKeyAndState(succPk, succState)); } } return ret; } protected void handleBackCopy( PointerKeyAndState curPkAndState, PointerKey predPk, IFlowLabel label) { for (PointerKeyAndState predPkAndState : matchingPToQueried(curPkAndState, predPk, label)) { if (addAllToP2Set(pkToP2Set, predPkAndState, find(pkToP2Set, curPkAndState), label)) { addToPToWorklist(predPkAndState); } } } void handleAllBackCopies( PointerKeyAndState curPkAndState, Iterator<? extends Object> predNodes, IFlowLabel label) { while (predNodes.hasNext()) { handleBackCopy(curPkAndState, (PointerKey) predNodes.next(), label); } } /** * should only be called when pk's points-to set has just been updated. add pk to the points-to * worklist, and re-propagate and calls that had pk as the receiver. */ void addToPToWorklist(PointerKeyAndState pkAndState) { pointsToWorklist.add(pkAndState); Set<CallerSiteContext> otfCalls = pkToOTFCalls.get(pkAndState); for (CallerSiteContext callSiteAndCGNode : otfCalls) { propTargets(pkAndState, callSiteAndCGNode); } } boolean addToInitWorklist(PointerKeyAndState pkAndState) { if (pointsToQueried.put(pkAndState.getPointerKey(), pkAndState.getState())) { if (pkAndState.getPointerKey() instanceof AbstractLocalPointerKey) { CGNode node = ((AbstractLocalPointerKey) pkAndState.getPointerKey()).getNode(); if (!g.hasSubgraphForNode(node)) { assert false : "missing constraints for " + node; } } if (DEBUG) { // System.err.println("adding to init_ " + pkAndState); } initWorklist.add(pkAndState); // if (pkAndStates.getMappedIndex(pkAndState) == -1) { // pkAndStates.add(pkAndState); // } return true; } return false; } protected void addToTrackedPToWorklist(PointerKeyAndState pkAndState) { if (pkAndState.getPointerKey() instanceof AbstractLocalPointerKey) { CGNode node = ((AbstractLocalPointerKey) pkAndState.getPointerKey()).getNode(); if (!g.hasSubgraphForNode(node)) { assert false : "missing constraints for " + node; } } if (DEBUG) { // System.err.println("adding to tracked points-to " + pkAndState); } trackedQueried.put(pkAndState.getPointerKey(), pkAndState.getState()); trackedPointsToWorklist.add(pkAndState); } /** * Adds new targets for a virtual call, based on the points-to set of the receiver, and * propagates values for the parameters / return value of the new targets. NOTE: this method * will <em>not</em> do any propagation for virtual call targets that have already been * discovered. * * @param receiverAndState the receiver * @param callSiteAndCGNode the call */ void propTargets(PointerKeyAndState receiverAndState, CallerSiteContext callSiteAndCGNode) { final CGNode caller = callSiteAndCGNode.getCaller(); CallSiteReference call = callSiteAndCGNode.getCallSite(); final State receiverState = receiverAndState.getState(); OrdinalSet<InstanceKeyAndState> p2set = makeOrdinalSet(find(pkToP2Set, receiverAndState)); for (InstanceKeyAndState ikAndState : p2set) { InstanceKey ik = ikAndState.getInstanceKey(); IMethod targetMethod = options.getMethodTargetSelector().getCalleeTarget(caller, call, ik.getConcreteType()); if (targetMethod == null) { // NOTE: target method can be null because we don't // always have type filters continue; } // if we've already handled this target, we can stop if (callToOTFTargets.get(callSiteAndCGNode).contains(targetMethod)) { continue; } callToOTFTargets.put(callSiteAndCGNode, targetMethod); // TODO can we just pick one of these, rather than all of them? // TODO handle clone() properly Set<CGNode> targetCGNodes = cg.getNodes(targetMethod.getReference()); for (final CGNode targetForCall : targetCGNodes) { if (DEBUG) { System.err.println("adding target " + targetForCall + " for call " + call); } if (hasNullIR(targetForCall)) { continue; } g.addSubgraphForNode(targetForCall); // need to check flows through parameters and returns, // in direction of value flow and reverse SSAAbstractInvokeInstruction[] calls = getCallInstrs(caller, call); for (final SSAAbstractInvokeInstruction invokeInstr : calls) { final ReturnLabel returnLabel = ReturnLabel.make(new CallerSiteContext(caller, call)); if (invokeInstr.hasDef()) { final PointerKeyAndState defAndState = new PointerKeyAndState( heapModel.getPointerKeyForLocal(caller, invokeInstr.getDef()), receiverState); final PointerKey ret = heapModel.getPointerKeyForReturnValue(targetForCall); doTransition( receiverState, returnLabel, retState -> { repropCallArg( defAndState, new PointerKeyAndState(ret, retState), returnLabel.bar()); return null; }); } final PointerKeyAndState exc = new PointerKeyAndState( heapModel.getPointerKeyForLocal(caller, invokeInstr.getException()), receiverState); final PointerKey excRet = heapModel.getPointerKeyForExceptionalReturnValue(targetForCall); doTransition( receiverState, returnLabel, excRetState -> { repropCallArg( exc, new PointerKeyAndState(excRet, excRetState), returnLabel.bar()); return null; }); for (int formalNum : Iterator2Iterable.make(new PointerParamValueNumIterator(targetForCall))) { final int actualNum = formalNum - 1; final ParamBarLabel paramBarLabel = ParamBarLabel.make(new CallerSiteContext(caller, call)); doTransition( receiverState, paramBarLabel, formalState -> { repropCallArg( new PointerKeyAndState( heapModel.getPointerKeyForLocal(targetForCall, formalNum), formalState), new PointerKeyAndState( heapModel.getPointerKeyForLocal(caller, invokeInstr.getUse(actualNum)), receiverState), paramBarLabel); return null; }); } } } } } /** handle possible updated flow in both directions for a call parameter */ private void repropCallArg( PointerKeyAndState src, PointerKeyAndState dst, IFlowLabel dstToSrcLabel) { if (DEBUG) { // System.err.println("re-propping from src " + src + " to dst " + dst); } for (PointerKeyAndState srcToHandle : matchingPToQueried(dst, src.getPointerKey(), dstToSrcLabel)) { handleCopy(srcToHandle, dst, dstToSrcLabel.bar()); } for (PointerKeyAndState dstToHandle : matchingTrackedQueried(src, dst.getPointerKey(), dstToSrcLabel)) { IntSet trackedSet = find(pkToTrackedSet, dstToHandle); if (!trackedSet.isEmpty()) { if (findOrCreate(pkToTrackedSet, src).addAll(trackedSet)) { addToTrackedPToWorklist(src); } } } } void handleInitWorklist() { while (!initWorklist.isEmpty()) { incrementNumNodesTraversed(); final PointerKeyAndState curPkAndState = initWorklist.iterator().next(); initWorklist.remove(curPkAndState); final PointerKey curPk = curPkAndState.getPointerKey(); final State curState = curPkAndState.getState(); if (DEBUG) System.err.println("init " + curPkAndState); if (curPk instanceof LocalPointerKey) { assert g.hasSubgraphForNode(((LocalPointerKey) curPk).getNode()); } // if (curPk instanceof LocalPointerKey) { // Collection<InstanceKey> constantVals = // getConstantVals((LocalPointerKey) curPk); // if (constantVals != null) { // for (InstanceKey ik : constantVals) { // pkToP2Set.put(curPk, ik); // addToPToWorklist(curPk); // } // } // } IFlowLabelVisitor v = new AbstractFlowLabelVisitor() { @Override public void visitNew(NewLabel label, Object dst) { final InstanceKey ik = (InstanceKey) dst; if (DEBUG) { System.err.println("alloc " + ik + " assigned to " + curPk); } doTransition( curState, label, newState -> { InstanceKeyAndState ikAndState = new InstanceKeyAndState(ik, newState); int n = ikAndStates.add(ikAndState); findOrCreate(pkToP2Set, curPkAndState).add(n); addToPToWorklist(curPkAndState); return null; }); } @Override public void visitGetField(GetFieldLabel label, Object dst) { IField field = label.getField(); PointerKey loadBase = (PointerKey) dst; if (refineFieldAccesses(field, loadBase, curPk, label, curState)) { // if (Assertions.verifyAssertions) { // Assertions._assert(stateMachine.transition(curState, label) == // curState); // } PointerKeyAndState loadBaseAndState = new PointerKeyAndState(loadBase, curState); addEncounteredLoad(new LoadEdge(loadBaseAndState, field, curPkAndState)); if (!addToInitWorklist(loadBaseAndState)) { // handle like x = y.f, with Y updated for (InstanceKeyAndState ikAndState : makeOrdinalSet(find(pkToP2Set, loadBaseAndState))) { trackInstanceField(ikAndState, field, forwInstKeyToFields); } } } else { handleAllCopies( curPkAndState, g.getWritesToInstanceField(loadBase, field), MatchLabel.v()); } } @Override public void visitAssignGlobal(AssignGlobalLabel label, Object dst) { handleAllCopies( curPkAndState, g.getWritesToStaticField((StaticFieldKey) dst), AssignGlobalLabel.v()); } @Override public void visitAssign(AssignLabel label, Object dst) { handleCopy(curPkAndState, (PointerKey) dst, AssignLabel.noFilter()); } }; g.visitSuccs(curPk, v); // interprocedural edges handleForwInterproc( curPkAndState, new CopyHandler() { @Override void handle(PointerKeyAndState src, PointerKey dst, IFlowLabel label) { handleCopy(src, dst, label); } }); } } /** handle flow from actuals to formals, and from returned values to variables at the caller */ private void handleForwInterproc( final PointerKeyAndState curPkAndState, final CopyHandler handler) { PointerKey curPk = curPkAndState.getPointerKey(); if (curPk instanceof LocalPointerKey) { final LocalPointerKey localPk = (LocalPointerKey) curPk; if (g.isParam(localPk)) { // System.err.println("at param"); final CGNode callee = localPk.getNode(); final int paramPos = localPk.getValueNumber() - 1; for (final CallerSiteContext callSiteAndCGNode : g.getPotentialCallers(localPk)) { final CGNode caller = callSiteAndCGNode.getCaller(); final CallSiteReference call = callSiteAndCGNode.getCallSite(); // final IR ir = getIR(caller); if (hasNullIR(caller)) continue; final ParamLabel paramLabel = ParamLabel.make(callSiteAndCGNode); doTransition( curPkAndState.getState(), paramLabel, new Function<>() { private void propagateToCallee() { // if (caller.getIR() == null) { // return; // } g.addSubgraphForNode(caller); SSAAbstractInvokeInstruction[] callInstrs = getCallInstrs(caller, call); for (SSAAbstractInvokeInstruction callInstr : callInstrs) { PointerKey actualPk = heapModel.getPointerKeyForLocal(caller, callInstr.getUse(paramPos)); assert g.containsNode(actualPk); assert g.containsNode(localPk); handler.handle(curPkAndState, actualPk, paramLabel); } } @Override public Object apply(State callerState) { // hack to get some actual parameter from call site // TODO do this better SSAAbstractInvokeInstruction[] callInstrs = getCallInstrs(caller, call); if (callInstrs.length == 0) { return null; } SSAAbstractInvokeInstruction callInstr = callInstrs[0]; PointerKey actualPk = heapModel.getPointerKeyForLocal(caller, callInstr.getUse(paramPos)); Set<CGNode> possibleTargets = g.getPossibleTargets(caller, call, (LocalPointerKey) actualPk); if (noOnTheFlyNeeded(callSiteAndCGNode, possibleTargets)) { propagateToCallee(); } else { if (callToOTFTargets.get(callSiteAndCGNode).contains(callee.getMethod())) { // already found this target as valid, so do propagation propagateToCallee(); } else { // if necessary, start a query for the call site queryCallTargets(callSiteAndCGNode, callInstrs, callerState); } } return null; } }); } } SSAAbstractInvokeInstruction callInstr = g.getInstrReturningTo(localPk); if (callInstr != null) { CGNode caller = localPk.getNode(); boolean isExceptional = localPk.getValueNumber() == callInstr.getException(); CallSiteReference callSiteRef = callInstr.getCallSite(); CallerSiteContext callSiteAndCGNode = new CallerSiteContext(caller, callSiteRef); // get call targets Set<CGNode> possibleCallees = g.getPossibleTargets(caller, callSiteRef, localPk); // cg.getPossibleTargets(caller, callSiteRef); // if (DEBUG && // callSiteRef.getDeclaredTarget().toString().indexOf("clone()") != // -1) { // System.err.println(possibleCallees); // System.err.println(Iterator2Collection.toCollection(cg.getSuccNodes(caller))); // System.err.println(Iterator2Collection.toCollection(cg.getPredNodes(possibleCallees.iterator().next()))); // } // construct graph for each target if (noOnTheFlyNeeded(callSiteAndCGNode, possibleCallees)) { for (CGNode callee : possibleCallees) { if (hasNullIR(callee)) { continue; } g.addSubgraphForNode(callee); PointerKey retVal = isExceptional ? heapModel.getPointerKeyForExceptionalReturnValue(callee) : heapModel.getPointerKeyForReturnValue(callee); assert g.containsNode(retVal); handler.handle(curPkAndState, retVal, ReturnLabel.make(callSiteAndCGNode)); } } else { if (callToOTFTargets.containsKey(callSiteAndCGNode)) { // already queried this call site // handle existing targets Set<IMethod> targetMethods = callToOTFTargets.get(callSiteAndCGNode); for (CGNode callee : possibleCallees) { if (targetMethods.contains(callee.getMethod())) { if (hasNullIR(callee)) { continue; } g.addSubgraphForNode(callee); PointerKey retVal = isExceptional ? heapModel.getPointerKeyForExceptionalReturnValue(callee) : heapModel.getPointerKeyForReturnValue(callee); assert g.containsNode(retVal); handler.handle(curPkAndState, retVal, ReturnLabel.make(callSiteAndCGNode)); } } } else { // if necessary, raise a query for the call site queryCallTargets( callSiteAndCGNode, getCallInstrs(caller, callSiteAndCGNode.getCallSite()), curPkAndState.getState()); } } } } } /** * track a field of some instance key, as we are interested in statements that read or write to * the field * * @param ikToFields either {@link #forwInstKeyToFields} or {@link #backInstKeyToFields} */ private void trackInstanceField( InstanceKeyAndState ikAndState, IField field, MultiMap<InstanceKeyAndState, IField> ikToFields) { ikToFields.put(ikAndState, field); addPredsOfIKeyAndStateToTrackedPointsTo(ikAndState); } private void addPredsOfIKeyAndStateToTrackedPointsTo(InstanceKeyAndState ikAndState) throws UnimplementedError { for (Object o : Iterator2Iterable.make(g.getPredNodes(ikAndState.getInstanceKey(), NewLabel.v()))) { PointerKey ikPred = (PointerKey) o; PointerKeyAndState ikPredAndState = new PointerKeyAndState(ikPred, ikAndState.getState()); int mappedIndex = ikAndStates.getMappedIndex(ikAndState); assert mappedIndex != -1; if (findOrCreate(pkToTrackedSet, ikPredAndState).add(mappedIndex)) { addToTrackedPToWorklist(ikPredAndState); } } } /** * Initiates a query for the targets of some virtual call, by asking for points-to set of * receiver. NOTE: if receiver has already been queried, will not do any additional propagation * for already-discovered virtual call targets */ private void queryCallTargets( CallerSiteContext callSiteAndCGNode, SSAAbstractInvokeInstruction[] callInstrs, State callerState) { final CGNode caller = callSiteAndCGNode.getCaller(); for (SSAAbstractInvokeInstruction callInstr : callInstrs) { PointerKey thisArg = heapModel.getPointerKeyForLocal(caller, callInstr.getUse(0)); PointerKeyAndState thisArgAndState = new PointerKeyAndState(thisArg, callerState); if (pkToOTFCalls.put(thisArgAndState, callSiteAndCGNode)) { // added the call target final CGNode node = ((LocalPointerKey) thisArg).getNode(); if (hasNullIR(node)) { return; } g.addSubgraphForNode(node); if (!addToInitWorklist(thisArgAndState)) { // need to handle pk's current values for call propTargets(thisArgAndState, callSiteAndCGNode); } else { if (DEBUG) { final CallSiteReference call = callSiteAndCGNode.getCallSite(); System.err.println("querying for targets of call " + call + " in " + caller); } } } else { // TODO: I think we can remove this call propTargets(thisArgAndState, callSiteAndCGNode); } } } void handlePointsToWorklist() { while (!pointsToWorklist.isEmpty()) { incrementNumNodesTraversed(); final PointerKeyAndState curPkAndState = pointsToWorklist.iterator().next(); pointsToWorklist.remove(curPkAndState); final PointerKey curPk = curPkAndState.getPointerKey(); final State curState = curPkAndState.getState(); if (DEBUG) { System.err.println("points-to " + curPkAndState); System.err.println("***pto-set " + find(pkToP2Set, curPkAndState) + "***"); } IFlowLabelVisitor predVisitor = new AbstractFlowLabelVisitor() { @Override public void visitPutField(PutFieldLabel label, Object dst) { IField field = label.getField(); PointerKey storeBase = (PointerKey) dst; if (refineFieldAccesses(field, storeBase, curPk, label, curState)) { // statements x.f = y, Y updated (X' not empty required) // update Z.f for all z in X' PointerKeyAndState storeBaseAndState = new PointerKeyAndState(storeBase, curState); encounteredStores.add(new StoreEdge(storeBaseAndState, field, curPkAndState)); for (InstanceKeyAndState ikAndState : makeOrdinalSet(find(pkToTrackedSet, storeBaseAndState))) { if (forwInstKeyToFields.get(ikAndState).contains(field)) { InstanceFieldKeyAndState ifKeyAndState = getInstFieldKey(ikAndState, field); findOrCreate(instFieldKeyToP2Set, ifKeyAndState) .addAll(find(pkToP2Set, curPkAndState)); } } } else { handleAllBackCopies( curPkAndState, g.getReadsOfInstanceField(storeBase, field), MatchBarLabel.v()); } } @Override public void visitGetField(GetFieldLabel label, Object dst) { IField field = label.getField(); PointerKey dstPtrKey = (PointerKey) dst; if (refineFieldAccesses(field, curPk, dstPtrKey, label, curState)) { // statements x = y.f, Y updated // if X queried, start tracking Y.f PointerKeyAndState loadDefAndState = new PointerKeyAndState(dstPtrKey, curState); addEncounteredLoad(new LoadEdge(curPkAndState, field, loadDefAndState)); if (pointsToQueried.get(dstPtrKey).contains(curState)) { for (InstanceKeyAndState ikAndState : makeOrdinalSet(find(pkToP2Set, curPkAndState))) { trackInstanceField(ikAndState, field, forwInstKeyToFields); } } } } @Override public void visitAssignGlobal(AssignGlobalLabel label, Object dst) { handleAllBackCopies( curPkAndState, g.getReadsOfStaticField((StaticFieldKey) dst), label.bar()); } @Override public void visitAssign(AssignLabel label, Object dst) { handleBackCopy(curPkAndState, (PointerKey) dst, label.bar()); } }; g.visitPreds(curPk, predVisitor); IFlowLabelVisitor succVisitor = new AbstractFlowLabelVisitor() { @Override public void visitPutField(PutFieldLabel label, Object dst) { IField field = label.getField(); PointerKey dstPtrKey = (PointerKey) dst; // pass barred label since this is for tracked points-to sets if (refineFieldAccesses(field, curPk, dstPtrKey, label.bar(), curState)) { // x.f = y, X updated // if Y' non-empty, then update // tracked set of X.f, to trace flow // to reads PointerKeyAndState storeDst = new PointerKeyAndState(dstPtrKey, curState); encounteredStores.add(new StoreEdge(curPkAndState, field, storeDst)); IntSet trackedSet = find(pkToTrackedSet, storeDst); if (!trackedSet.isEmpty()) { for (InstanceKeyAndState ikAndState : makeOrdinalSet(find(pkToP2Set, curPkAndState))) { InstanceFieldKeyAndState ifk = getInstFieldKey(ikAndState, field); findOrCreate(instFieldKeyToTrackedSet, ifk).addAll(trackedSet); trackInstanceField(ikAndState, field, backInstKeyToFields); } } } } }; g.visitSuccs(curPk, succVisitor); handleBackInterproc( curPkAndState, new CopyHandler() { @Override void handle(PointerKeyAndState src, PointerKey dst, IFlowLabel label) { handleBackCopy(src, dst, label); } }, false); } } /** handle flow from return value to callers, or from actual to formals */ private void handleBackInterproc( final PointerKeyAndState curPkAndState, final CopyHandler handler, final boolean addGraphs) { final PointerKey curPk = curPkAndState.getPointerKey(); final State curState = curPkAndState.getState(); // interprocedural edges if (curPk instanceof ReturnValueKey) { final ReturnValueKey returnKey = (ReturnValueKey) curPk; if (DEBUG) { System.err.println("return value"); } final CGNode callee = returnKey.getNode(); if (DEBUG) { System.err.println("returning from " + callee); // System.err.println("CALL GRAPH:\n" + cg); // System.err.println(new // Iterator2Collection(cg.getPredNodes(cgNode))); } final boolean isExceptional = returnKey instanceof ExceptionReturnValueKey; // iterate over callers for (final CallerSiteContext callSiteAndCGNode : g.getPotentialCallers(returnKey)) { final CGNode caller = callSiteAndCGNode.getCaller(); if (hasNullIR(caller)) continue; final CallSiteReference call = callSiteAndCGNode.getCallSite(); if (calleeSubGraphMissingAndShouldNotBeAdded(addGraphs, callee, curPkAndState)) { continue; } final ReturnBarLabel returnBarLabel = ReturnBarLabel.make(callSiteAndCGNode); doTransition( curState, returnBarLabel, new Function<>() { private void propagateToCaller() { // if (caller.getIR() == null) { // return; // } g.addSubgraphForNode(caller); SSAAbstractInvokeInstruction[] callInstrs = getCallInstrs(caller, call); for (SSAAbstractInvokeInstruction callInstr : callInstrs) { PointerKey returnAtCallerKey = heapModel.getPointerKeyForLocal( caller, isExceptional ? callInstr.getException() : callInstr.getDef()); assert g.containsNode(returnAtCallerKey); assert g.containsNode(returnKey); handler.handle(curPkAndState, returnAtCallerKey, returnBarLabel); } } @Override public Object apply(State callerState) { // if (DEBUG) { // System.err.println("caller " + caller); // } SSAAbstractInvokeInstruction[] callInstrs = getCallInstrs(caller, call); if (callInstrs.length == 0) { return null; } SSAAbstractInvokeInstruction callInstr = callInstrs[0]; PointerKey returnAtCallerKey = heapModel.getPointerKeyForLocal( caller, isExceptional ? callInstr.getException() : callInstr.getDef()); Set<CGNode> possibleTargets = g.getPossibleTargets(caller, call, (LocalPointerKey) returnAtCallerKey); if (noOnTheFlyNeeded(callSiteAndCGNode, possibleTargets)) { propagateToCaller(); } else { if (callToOTFTargets.get(callSiteAndCGNode).contains(callee.getMethod())) { // already found this target as valid, so do propagation propagateToCaller(); } else { // if necessary, start a query for the call site queryCallTargets(callSiteAndCGNode, callInstrs, callerState); } } return null; } }); } } if (curPk instanceof LocalPointerKey) { LocalPointerKey localPk = (LocalPointerKey) curPk; CGNode caller = localPk.getNode(); // from actual parameter to callee for (SSAAbstractInvokeInstruction callInstr : Iterator2Iterable.make(g.getInstrsPassingParam(localPk))) { for (int i = 0; i < callInstr.getNumberOfUses(); i++) { if (localPk.getValueNumber() != callInstr.getUse(i)) continue; CallSiteReference callSiteRef = callInstr.getCallSite(); CallerSiteContext callSiteAndCGNode = new CallerSiteContext(caller, callSiteRef); // get call targets Set<CGNode> possibleCallees = g.getPossibleTargets(caller, callSiteRef, localPk); // construct graph for each target if (noOnTheFlyNeeded(callSiteAndCGNode, possibleCallees)) { for (CGNode callee : possibleCallees) { if (calleeSubGraphMissingAndShouldNotBeAdded(addGraphs, callee, curPkAndState)) { continue; } if (hasNullIR(callee)) { continue; } g.addSubgraphForNode(callee); PointerKey paramVal = heapModel.getPointerKeyForLocal(callee, i + 1); assert g.containsNode(paramVal); handler.handle(curPkAndState, paramVal, ParamBarLabel.make(callSiteAndCGNode)); } } else { if (callToOTFTargets.containsKey(callSiteAndCGNode)) { // already queried this call site // handle existing targets Set<IMethod> targetMethods = callToOTFTargets.get(callSiteAndCGNode); for (CGNode callee : possibleCallees) { if (targetMethods.contains(callee.getMethod())) { if (hasNullIR(callee)) { continue; } g.addSubgraphForNode(callee); PointerKey paramVal = heapModel.getPointerKeyForLocal(callee, i + 1); assert g.containsNode(paramVal); handler.handle(curPkAndState, paramVal, ParamBarLabel.make(callSiteAndCGNode)); } } } else { // if necessary, raise a query for the call site queryCallTargets( callSiteAndCGNode, getCallInstrs(caller, callSiteAndCGNode.getCallSite()), curState); } } } } } } /** * when doing backward interprocedural propagation, is it true that we should not add a graph * representation for a callee _and_ that the subgraph for the callee is missing? * * @param addGraphs whether graphs should always be added */ protected boolean calleeSubGraphMissingAndShouldNotBeAdded( boolean addGraphs, CGNode callee, @SuppressWarnings("unused") PointerKeyAndState pkAndState) { return !addGraphs && !g.hasSubgraphForNode(callee); } public void handleTrackedPointsToWorklist() { // if (Assertions.verifyAssertions) { // Assertions._assert(trackedPointsToWorklist.isEmpty() || refineFields); // } while (!trackedPointsToWorklist.isEmpty()) { incrementNumNodesTraversed(); final PointerKeyAndState curPkAndState = trackedPointsToWorklist.iterator().next(); trackedPointsToWorklist.remove(curPkAndState); final PointerKey curPk = curPkAndState.getPointerKey(); final State curState = curPkAndState.getState(); if (DEBUG) System.err.println("tracked points-to " + curPkAndState); final MutableIntSet trackedSet = find(pkToTrackedSet, curPkAndState); IFlowLabelVisitor succVisitor = new AbstractFlowLabelVisitor() { @Override public void visitPutField(PutFieldLabel label, Object dst) { // statements x.f = y, X' updated, f in map // query y; if already queried, add Y to Z.f for all // z in X' IField field = label.getField(); PointerKey dstPtrKey = (PointerKey) dst; if (refineFieldAccesses(field, curPk, dstPtrKey, label, curState)) { for (InstanceKeyAndState ikAndState : makeOrdinalSet(trackedSet)) { boolean needField = forwInstKeyToFields.get(ikAndState).contains(field); PointerKeyAndState storeDst = new PointerKeyAndState(dstPtrKey, curState); encounteredStores.add(new StoreEdge(curPkAndState, field, storeDst)); if (needField) { if (!addToInitWorklist(storeDst)) { InstanceFieldKeyAndState ifk = getInstFieldKey(ikAndState, field); findOrCreate(instFieldKeyToP2Set, ifk).addAll(find(pkToP2Set, storeDst)); } } } } } }; g.visitSuccs(curPk, succVisitor); IFlowLabelVisitor predVisitor = new AbstractFlowLabelVisitor() { @Override public void visitAssignGlobal(final AssignGlobalLabel label, Object dst) { for (Object o : Iterator2Iterable.make(g.getReadsOfStaticField((StaticFieldKey) dst))) { final PointerKey predPk = (PointerKey) o; doTransition( curState, AssignGlobalBarLabel.v(), predPkState -> { PointerKeyAndState predPkAndState = new PointerKeyAndState(predPk, predPkState); handleTrackedPred(trackedSet, predPkAndState, AssignGlobalBarLabel.v()); return null; }); } } @Override public void visitPutField(PutFieldLabel label, Object dst) { IField field = label.getField(); PointerKey storeBase = (PointerKey) dst; // bar label since this is for tracked points-to sets if (refineFieldAccesses(field, storeBase, curPk, label.bar(), curState)) { PointerKeyAndState storeBaseAndState = new PointerKeyAndState(storeBase, curState); encounteredStores.add(new StoreEdge(storeBaseAndState, field, curPkAndState)); if (!addToInitWorklist(storeBaseAndState)) { for (InstanceKeyAndState ikAndState : makeOrdinalSet(find(pkToP2Set, storeBaseAndState))) { InstanceFieldKeyAndState ifk = getInstFieldKey(ikAndState, field); findOrCreate(instFieldKeyToTrackedSet, ifk).addAll(trackedSet); trackInstanceField(ikAndState, field, backInstKeyToFields); } } } else { // send to all getfield sources for (final PointerKey predPk : Iterator2Iterable.make(g.getReadsOfInstanceField(storeBase, field))) { doTransition( curState, MatchBarLabel.v(), predPkState -> { PointerKeyAndState predPkAndState = new PointerKeyAndState(predPk, predPkState); handleTrackedPred(trackedSet, predPkAndState, MatchBarLabel.v()); return null; }); } } } @Override public void visitGetField(GetFieldLabel label, Object dst) { IField field = label.getField(); PointerKey dstPtrKey = (PointerKey) dst; // x = y.f, Y' updated // bar label since this is for tracked points-to sets if (refineFieldAccesses(field, curPk, dstPtrKey, label.bar(), curState)) { for (InstanceKeyAndState ikAndState : makeOrdinalSet(trackedSet)) { // tracking value written into ik.field boolean needField = backInstKeyToFields.get(ikAndState).contains(field); PointerKeyAndState loadedVal = new PointerKeyAndState(dstPtrKey, curState); addEncounteredLoad(new LoadEdge(curPkAndState, field, loadedVal)); if (needField) { InstanceFieldKeyAndState ifk = getInstFieldKey(ikAndState, field); // use an assign bar label with no filter here, since filtering only happens // at casts handleTrackedPred( find(instFieldKeyToTrackedSet, ifk), loadedVal, AssignBarLabel.noFilter()); } } } } @Override public void visitAssign(final AssignLabel label, Object dst) { final PointerKey predPk = (PointerKey) dst; doTransition( curState, label.bar(), predPkState -> { PointerKeyAndState predPkAndState = new PointerKeyAndState(predPk, predPkState); handleTrackedPred(trackedSet, predPkAndState, label.bar()); return null; }); } }; g.visitPreds(curPk, predVisitor); handleBackInterproc( curPkAndState, new CopyHandler() { @Override void handle(PointerKeyAndState src, final PointerKey dst, final IFlowLabel label) { assert src == curPkAndState; doTransition( curState, label, dstState -> { PointerKeyAndState dstAndState = new PointerKeyAndState(dst, dstState); handleTrackedPred(trackedSet, dstAndState, label); return null; }); } }, true); } } private void addEncounteredLoad(LoadEdge loadEdge) { if (encounteredLoads.add(loadEdge)) { // if (DEBUG) { // System.err.println("encountered load edge " + loadEdge); // } } } public void makePassOverFieldStmts() { for (StoreEdge storeEdge : encounteredStores) { PointerKeyAndState storedValAndState = storeEdge.val; IField field = storeEdge.field; PointerKeyAndState baseAndState = storeEdge.base; // x.f = y, X' updated // for each z in X' such that f in z's map, // add Y to Z.f IntSet trackedSet = find(pkToTrackedSet, baseAndState); for (InstanceKeyAndState ikAndState : makeOrdinalSet(trackedSet)) { if (forwInstKeyToFields.get(ikAndState).contains(field)) { if (!addToInitWorklist(storedValAndState)) { InstanceFieldKeyAndState ifk = getInstFieldKey(ikAndState, field); findOrCreate(instFieldKeyToP2Set, ifk).addAll(find(pkToP2Set, storedValAndState)); } } } } for (LoadEdge loadEdge : encounteredLoads) { PointerKeyAndState loadedValAndState = loadEdge.val; IField field = loadEdge.field; PointerKey basePointerKey = loadEdge.base.getPointerKey(); State loadDstState = loadedValAndState.getState(); PointerKeyAndState baseAndStateToHandle = new PointerKeyAndState(basePointerKey, loadDstState); boolean basePointerOkay = pointsToQueried.get(basePointerKey).contains(loadDstState) || !pointsToQueried.get(loadedValAndState.getPointerKey()).contains(loadDstState) || initWorklist.contains(loadedValAndState); // if (!basePointerOkay) { // System.err.println("ASSERTION WILL FAIL"); // System.err.println("QUERIED: " + queriedPkAndStates); // } if (!basePointerOkay) { // remove this assertion, since we now allow multiple queries --MS // Assertions._assert(false, "queried " + loadedValAndState + " but not " + // baseAndStateToHandle); } final IntSet curP2Set = find(pkToP2Set, baseAndStateToHandle); // int startSize = curP2Set.size(); // int curSize = -1; for (InstanceKeyAndState ikAndState : makeOrdinalSet(curP2Set)) { // curSize = curP2Set.size(); // if (Assertions.verifyAssertions) { // Assertions._assert(startSize == curSize); // } InstanceFieldKeyAndState ifk = getInstFieldKey(ikAndState, field); // make sure we've actually queried the def'd val before adding to its points-to set if (pointsToQueried .get(loadedValAndState.getPointerKey()) .contains(loadedValAndState.getState())) { // just pass no label assign filter since no type-based filtering can be // done here if (addAllToP2Set( pkToP2Set, loadedValAndState, find(instFieldKeyToP2Set, ifk), AssignLabel.noFilter())) { if (DEBUG) { System.err.println("from load edge " + loadEdge); } addToPToWorklist(loadedValAndState); } } } // } // x = y.f, Y' updated PointerKeyAndState baseAndState = loadEdge.base; for (InstanceKeyAndState ikAndState : makeOrdinalSet(find(pkToTrackedSet, baseAndState))) { if (backInstKeyToFields.get(ikAndState).contains(field)) { // tracking value written into ik.field InstanceFieldKeyAndState ifk = getInstFieldKey(ikAndState, field); if (findOrCreate(pkToTrackedSet, loadedValAndState) .addAll(find(instFieldKeyToTrackedSet, ifk))) { if (DEBUG) { System.err.println("from load edge " + loadEdge); } addToTrackedPToWorklist(loadedValAndState); } } } } } private InstanceFieldKeyAndState getInstFieldKey(InstanceKeyAndState ikAndState, IField field) { return new InstanceFieldKeyAndState( new InstanceFieldKey(ikAndState.getInstanceKey(), field), ikAndState.getState()); } protected <K> MutableIntSet findOrCreate(Map<K, MutableIntSet> M, K key) { MutableIntSet result = M.get(key); if (result == null) { result = intSetFactory.make(); M.put(key, result); } return result; } private final MutableIntSet emptySet = intSetFactory.make(); protected <K> MutableIntSet find(Map<K, MutableIntSet> M, K key) { MutableIntSet result = M.get(key); if (result == null) { result = emptySet; } return result; } /** * Handle a predecessor when processing some tracked locations * * @param curTrackedSet the tracked locations * @param predPkAndState the predecessor */ protected boolean handleTrackedPred( final MutableIntSet curTrackedSet, PointerKeyAndState predPkAndState, IFlowLabel label) { if (addAllToP2Set(pkToTrackedSet, predPkAndState, curTrackedSet, label)) { addToTrackedPToWorklist(predPkAndState); return true; } return false; } } /** * Returns the call instructions corresponding to a given call site in a node. (There can be * multiple call instructions if the program's bytecode uses the {@code jsr} instruction.) * * <p>If the site does not exist in the node's IR, returns an array of length 0. This can occur, * e.g., if the up-front call graph is a {@link com.ibm.wala.ipa.callgraph.cha.CHACallGraph}, * which does not construct IRs and may include call sites not present after building IR. */ private static SSAAbstractInvokeInstruction[] getCallInstrs(CGNode node, CallSiteReference site) { IR ir = node.getIR(); return ir.getCallInstructionIndices(site) == null ? new SSAAbstractInvokeInstruction[0] : ir.getCalls(site); } private static boolean hasNullIR(CGNode node) { boolean ret = node.getMethod().isNative(); assert node.getIR() != null || ret; return ret; } private Object doTransition(State curState, IFlowLabel label, Function<State, Object> func) { State nextState = stateMachine.transition(curState, label); Object ret = null; if (nextState != StateMachine.ERROR) { ret = func.apply(nextState); } else { // System.err.println("filtered at edge " + label); } return ret; } public StateMachineFactory<IFlowLabel> getStateMachineFactory() { return stateMachineFactory; } public void setStateMachineFactory(StateMachineFactory<IFlowLabel> stateMachineFactory) { this.stateMachineFactory = stateMachineFactory; } public RefinementPolicyFactory getRefinementPolicyFactory() { return refinementPolicyFactory; } public void setRefinementPolicyFactory(RefinementPolicyFactory refinementPolicyFactory) { this.refinementPolicyFactory = refinementPolicyFactory; } /** we are looking for an instance key flowing to pk that violates pred. */ @SuppressWarnings("unused") private boolean doTopLevelTraversal( PointerKey pk, final Predicate<InstanceKey> pred, final PointsToComputer ptoComputer, PointerAnalysis<InstanceKey> pa) { final Set<PointerKeyAndState> visited = HashSetFactory.make(); final ArrayDeque<PointerKeyAndState> worklist = new ArrayDeque<>(); class Helper { /** * cache of the targets discovered for a call site during on-the-fly call graph construction */ private final MultiMap<CallerSiteContext, IMethod> callToOTFTargets = ArraySetMultiMap.make(); void propagate(PointerKeyAndState pkAndState) { if (visited.add(pkAndState)) { assert graphContainsNode(pkAndState.getPointerKey()); worklist.addLast(pkAndState); } } private boolean graphContainsNode(PointerKey pointerKey) { if (pointerKey instanceof LocalPointerKey) { LocalPointerKey lpk = (LocalPointerKey) pointerKey; return g.hasSubgraphForNode(lpk.getNode()); } return true; } private Collection<IMethod> getOTFTargets( CallerSiteContext callSiteAndCGNode, SSAAbstractInvokeInstruction[] callInstrs, State callerState) { if (DEBUG_TOPLEVEL) { System.err.println("toplevel refining call site " + callSiteAndCGNode); } final CallSiteReference call = callSiteAndCGNode.getCallSite(); final CGNode caller = callSiteAndCGNode.getCaller(); Collection<IMethod> result = HashSetFactory.make(); for (SSAAbstractInvokeInstruction callInstr : callInstrs) { PointerKey thisArg = heapModel.getPointerKeyForLocal(caller, callInstr.getUse(0)); PointerKeyAndState thisArgAndState = new PointerKeyAndState(thisArg, callerState); OrdinalSet<InstanceKeyAndState> thisPToSet = getPToSetFromComputer(ptoComputer, thisArgAndState); for (InstanceKeyAndState ikAndState : thisPToSet) { InstanceKey ik = ikAndState.getInstanceKey(); IMethod targetMethod = options .getMethodTargetSelector() .getCalleeTarget(caller, call, ik.getConcreteType()); if (targetMethod == null) { // NOTE: target method can be null because we don't // always have type filters continue; } result.add(targetMethod); } } return result; } public void handleTopLevelForwInterproc(PointerKeyAndState curPkAndState) { PointerKey curPk = curPkAndState.getPointerKey(); final State curState = curPkAndState.getState(); if (curPk instanceof LocalPointerKey) { final LocalPointerKey localPk = (LocalPointerKey) curPk; if (g.isParam(localPk)) { // System.err.println("at param"); final CGNode callee = localPk.getNode(); final int paramPos = localPk.getValueNumber() - 1; for (final CallerSiteContext callSiteAndCGNode : g.getPotentialCallers(localPk)) { final CGNode caller = callSiteAndCGNode.getCaller(); final CallSiteReference call = callSiteAndCGNode.getCallSite(); // final IR ir = getIR(caller); if (hasNullIR(caller)) continue; final ParamLabel paramLabel = ParamLabel.make(callSiteAndCGNode); doTransition( curPkAndState.getState(), paramLabel, new Function<>() { private void propagateToCallee() { // if (caller.getIR() == null) { // return; // } g.addSubgraphForNode(caller); SSAAbstractInvokeInstruction[] callInstrs = getCallInstrs(caller, call); for (SSAAbstractInvokeInstruction callInstr : callInstrs) { final PointerKey actualPk = heapModel.getPointerKeyForLocal(caller, callInstr.getUse(paramPos)); assert g.containsNode(actualPk); assert g.containsNode(localPk); doTransition( curState, paramLabel, nextState -> { propagate(new PointerKeyAndState(actualPk, nextState)); return null; }); } } @Override public Object apply(State callerState) { // hack to get some actual parameter from call site // TODO do this better SSAAbstractInvokeInstruction[] callInstrs = getCallInstrs(caller, call); if (callInstrs.length == 0) { return null; } SSAAbstractInvokeInstruction callInstr = callInstrs[0]; PointerKey actualPk = heapModel.getPointerKeyForLocal(caller, callInstr.getUse(paramPos)); Set<CGNode> possibleTargets = g.getPossibleTargets(caller, call, (LocalPointerKey) actualPk); if (noOnTheFlyNeeded(callSiteAndCGNode, possibleTargets)) { propagateToCallee(); } else { Collection<IMethod> otfTargets = getOTFTargets(callSiteAndCGNode, callInstrs, callerState); if (otfTargets.contains(callee.getMethod())) { // already found this target as valid, so do propagation propagateToCallee(); } } return null; } }); } } SSAAbstractInvokeInstruction callInstr = g.getInstrReturningTo(localPk); if (callInstr != null) { CGNode caller = localPk.getNode(); boolean isExceptional = localPk.getValueNumber() == callInstr.getException(); CallSiteReference callSiteRef = callInstr.getCallSite(); CallerSiteContext callSiteAndCGNode = new CallerSiteContext(caller, callSiteRef); // get call targets Set<CGNode> possibleCallees = g.getPossibleTargets(caller, callSiteRef, localPk); if (noOnTheFlyNeeded(callSiteAndCGNode, possibleCallees)) { for (CGNode callee : possibleCallees) { if (hasNullIR(callee)) { continue; } g.addSubgraphForNode(callee); final PointerKey retVal = isExceptional ? heapModel.getPointerKeyForExceptionalReturnValue(callee) : heapModel.getPointerKeyForReturnValue(callee); assert g.containsNode(retVal); doTransition( curState, ReturnLabel.make(callSiteAndCGNode), nextState -> { propagate(new PointerKeyAndState(retVal, nextState)); return null; }); } } else { Collection<IMethod> otfTargets = getOTFTargets( callSiteAndCGNode, getCallInstrs(caller, callSiteAndCGNode.getCallSite()), curPkAndState.getState()); for (CGNode callee : possibleCallees) { if (otfTargets.contains(callee.getMethod())) { if (hasNullIR(callee)) { continue; } g.addSubgraphForNode(callee); final PointerKey retVal = isExceptional ? heapModel.getPointerKeyForExceptionalReturnValue(callee) : heapModel.getPointerKeyForReturnValue(callee); assert g.containsNode(retVal); doTransition( curState, ReturnLabel.make(callSiteAndCGNode), nextState -> { propagate(new PointerKeyAndState(retVal, nextState)); return null; }); } } } } } } private OrdinalSet<InstanceKeyAndState> getPToSetFromComputer( final PointsToComputer ptoComputer, PointerKeyAndState pointerKeyAndState) { // make sure relevant constraints have been added if (pointerKeyAndState.getPointerKey() instanceof LocalPointerKey) { LocalPointerKey lpk = (LocalPointerKey) pointerKeyAndState.getPointerKey(); g.addSubgraphForNode(lpk.getNode()); } // add pointerKeyAndState to init worklist ptoComputer.addToInitWorklist(pointerKeyAndState); // run worklist algorithm ptoComputer.worklistLoop(); // suck out the points-to set final MutableIntSet intP2Set = ptoComputer.pkToP2Set.get(pointerKeyAndState); if (intP2Set == null) { // null if empty p2set return OrdinalSet.empty(); } else { return ptoComputer.makeOrdinalSet(intP2Set); } } private void computeFlowsTo( PointsToComputer ptoComputer, OrdinalSet<InstanceKeyAndState> basePToSet) { for (InstanceKeyAndState ikAndState : basePToSet) { ptoComputer.addPredsOfIKeyAndStateToTrackedPointsTo(ikAndState); } // run worklist loop assert ptoComputer.initWorklist.isEmpty(); assert ptoComputer.pointsToWorklist.isEmpty(); ptoComputer.worklistLoop(); } private Collection<State> getFlowedToStates( PointsToComputer ptoComputer, OrdinalSet<InstanceKeyAndState> basePToSet, PointerKey putfieldBase) { Collection<State> result = HashSetFactory.make(); Set<State> trackedStates = ptoComputer.trackedQueried.get(putfieldBase); for (State trackedState : trackedStates) { PointerKeyAndState pkAndState = new PointerKeyAndState(putfieldBase, trackedState); if (ptoComputer .makeOrdinalSet(ptoComputer.pkToTrackedSet.get(pkAndState)) .containsAny(basePToSet)) { result.add(trackedState); } } // for (PointerKeyAndState pkAndState : ptoComputer.pkToTrackedSet.keySet()) { // if (pkAndState.getPointerKey().equals(putfieldBase)) { // if // (ptoComputer.makeOrdinalSet(ptoComputer.pkToTrackedSet.get(pkAndState)).containsAny(basePToSet)) { // result.add(pkAndState.getState()); // } // } // } return result; } } final Helper h = new Helper(); PointerKeyAndState initPkAndState = new PointerKeyAndState(pk, stateMachine.getStartState()); if (pk instanceof LocalPointerKey) { g.addSubgraphForNode(((LocalPointerKey) pk).getNode()); } h.propagate(initPkAndState); while (!worklist.isEmpty()) { incrementNumNodesTraversed(); PointerKeyAndState curPkAndState = worklist.removeFirst(); final PointerKey curPk = curPkAndState.getPointerKey(); final State curState = curPkAndState.getState(); // if predicate holds for pre-computed points-to set of curPk, we are done if (DEBUG_TOPLEVEL) { System.err.println("toplevel pkAndState " + curPkAndState); } if (predHoldsForPk(curPk, pred, pa)) { if (DEBUG_TOPLEVEL) { System.err.println("predicate holds"); } continue; } // otherwise, traverse new, assign, assign global, param, return, match edges class MyFlowLabelVisitor extends AbstractFlowLabelVisitor { boolean foundBadInstanceKey; @Override public void visitNew(NewLabel label, Object dst) { // TODO Auto-generated method stub final InstanceKey ik = (InstanceKey) dst; if (DEBUG_TOPLEVEL) { System.err.println("toplevel alloc " + ik + " assigned to " + curPk); } doTransition( curState, label, newState -> { // just check if ik violates the pred if (!pred.test(ik)) { foundBadInstanceKey = true; } return null; }); } @Override public void visitGetField(GetFieldLabel label, Object dst) { IField field = label.getField(); PointerKey loadBase = (PointerKey) dst; if (refineFieldAccesses(field, loadBase, curPk, label, curState)) { if (DEBUG_TOPLEVEL) { System.err.println("toplevel refining for read of " + field); } // find points-to set of base pointer OrdinalSet<InstanceKeyAndState> basePToSet = h.getPToSetFromComputer(ptoComputer, new PointerKeyAndState(loadBase, curState)); if (DEBUG_TOPLEVEL) { System.err.println("toplevel base pointer p2set " + basePToSet); } // find "flows-to sets" of pointed-to instance keys h.computeFlowsTo(ptoComputer, basePToSet); if (DEBUG_TOPLEVEL) { System.err.println("toplevel finished computing flows to"); } // for each putfield base pointer, if flowed-to, then propagate written pointer key for (MemoryAccess fieldWrite : getWrites(field, loadBase)) { Collection<Pair<PointerKey, PointerKey>> baseAndStoredPairs = getBaseAndStored(fieldWrite, field); if (baseAndStoredPairs == null) { continue; } for (Pair<PointerKey, PointerKey> p : baseAndStoredPairs) { PointerKey base = p.fst; PointerKey stored = p.snd; Collection<State> reachedFlowStates = h.getFlowedToStates(ptoComputer, basePToSet, base); for (State nextState : reachedFlowStates) { if (DEBUG_TOPLEVEL) { System.err.println( "toplevel alias with base " + base + " in state " + nextState); } h.propagate(new PointerKeyAndState(stored, nextState)); } } } } else { // use match edges for (final PointerKey writtenPk : Iterator2Iterable.make(g.getWritesToInstanceField(loadBase, field))) { doTransition( curState, MatchLabel.v(), nextState -> { h.propagate(new PointerKeyAndState(writtenPk, nextState)); return null; }); } } } private Collection<Pair<PointerKey, PointerKey>> getBaseAndStored( MemoryAccess fieldWrite, IField field) { final CGNode node = fieldWrite.getNode(); // an optimization; if node is not represented in our constraint graph, then we could not // possibly // have discovered flow to the base pointer if (!g.hasSubgraphForNode(node)) { return null; } IR ir = node.getIR(); PointerKey base = null, stored = null; if (field == ArrayContents.v()) { final SSAInstruction instruction = ir.getInstructions()[fieldWrite.getInstructionIndex()]; if (instruction == null) { return null; } if (instruction instanceof SSANewInstruction) { return DemandPointerFlowGraph.getInfoForNewMultiDim( (SSANewInstruction) instruction, heapModel, fieldWrite.getNode()) .arrStoreInstrs; } SSAArrayStoreInstruction s = (SSAArrayStoreInstruction) instruction; base = heapModel.getPointerKeyForLocal(fieldWrite.getNode(), s.getArrayRef()); stored = heapModel.getPointerKeyForLocal(fieldWrite.getNode(), s.getValue()); } else { SSAPutInstruction s = (SSAPutInstruction) ir.getInstructions()[fieldWrite.getInstructionIndex()]; if (s == null) { return null; } base = heapModel.getPointerKeyForLocal(fieldWrite.getNode(), s.getRef()); stored = heapModel.getPointerKeyForLocal(fieldWrite.getNode(), s.getVal()); } return Collections.singleton(Pair.make(base, stored)); } private Collection<MemoryAccess> getWrites(IField field, PointerKey loadBase) { final PointerKey convertedBase = convertToHeapModel(loadBase, mam.getHeapModel()); if (field == ArrayContents.v()) { return mam.getArrayWrites(loadBase); } else { return mam.getFieldWrites(convertedBase, field); } } @Override public void visitAssignGlobal(AssignGlobalLabel label, Object dst) { for (Object writeToStaticField : Iterator2Iterable.make(g.getWritesToStaticField((StaticFieldKey) dst))) { final PointerKey writtenPk = (PointerKey) writeToStaticField; doTransition( curState, label, nextState -> { h.propagate(new PointerKeyAndState(writtenPk, nextState)); return null; }); } } @Override public void visitAssign(AssignLabel label, Object dst) { final PointerKey succPk = (PointerKey) dst; doTransition( curState, label, nextState -> { h.propagate(new PointerKeyAndState(succPk, nextState)); return null; }); } } MyFlowLabelVisitor v = new MyFlowLabelVisitor(); g.visitSuccs(curPk, v); if (v.foundBadInstanceKey) { // found an instance key violating the pred return false; } h.handleTopLevelForwInterproc(curPkAndState); } return true; } private static boolean predHoldsForPk( PointerKey curPk, Predicate<InstanceKey> pred, PointerAnalysis<InstanceKey> pa) { PointerKey curPkForPAHeapModel = convertToHeapModel(curPk, pa.getHeapModel()); OrdinalSet<InstanceKey> pointsToSet = pa.getPointsToSet(curPkForPAHeapModel); for (InstanceKey ik : pointsToSet) { if (!pred.test(ik)) { return false; } } return true; } private static PointerKey convertToHeapModel(PointerKey curPk, HeapModel heapModel) { return AbstractFlowGraph.convertPointerKeyToHeapModel(curPk, heapModel); } private boolean refineFieldAccesses( IField field, PointerKey basePtr, PointerKey val, IFlowLabel label, State state) { boolean shouldRefine = refinementPolicy.getFieldRefinePolicy().shouldRefine(field, basePtr, val, label, state); if (DEBUG) { if (shouldRefine) { System.err.println("refining access to " + field); } else { System.err.println("using match for access to " + field); } } return shouldRefine; } private boolean noOnTheFlyNeeded(CallerSiteContext call, Set<CGNode> possibleTargets) { // NOTE: if we want to be more precise for queries in dead code, // we shouldn't rely on possibleTargets here (since there may be // zero targets) if (!refinementPolicy.getCallGraphRefinePolicy().shouldRefine(call)) { return true; } // here we compute the number of unique *method* targets, as opposed to call graph nodes. // if we have a context-sensitive call graph, with many targets representing clones of // the same method, we don't want to count the clones twice Set<IMethod> methodTargets = new HashSet<>(); for (CGNode node : possibleTargets) { methodTargets.add(node.getMethod()); } return methodTargets.size() <= 1; } /** used to compute "flows-to sets," i.e., all the pointers that can point to some instance key */ protected class FlowsToComputer extends PointsToComputer { private final InstanceKeyAndState queriedIkAndState; private final int queriedIkAndStateNum; /** holds the desired flows-to set */ private final Collection<PointerKeyAndState> theFlowsToSet = HashSetFactory.make(); public FlowsToComputer(InstanceKeyAndState ikAndState) { this.queriedIkAndState = ikAndState; this.queriedIkAndStateNum = ikAndStates.add(queriedIkAndState); } @Override protected void compute() { // seed the points-to worklist InstanceKey ik = queriedIkAndState.getInstanceKey(); g.addSubgraphForNode(((InstanceKeyWithNode) ik).getNode()); for (Object pred : Iterator2Iterable.make(g.getPredNodes(ik, NewLabel.v()))) { PointerKey predPk = (PointerKey) pred; PointerKeyAndState predPkAndState = new PointerKeyAndState(predPk, queriedIkAndState.getState()); theFlowsToSet.add(predPkAndState); findOrCreate(pkToTrackedSet, predPkAndState).add(queriedIkAndStateNum); addToTrackedPToWorklist(predPkAndState); } worklistLoop(); } public Collection<PointerKeyAndState> getComputedFlowsToSet() { return theFlowsToSet; } /** also update the flows-to set of interest if necessary */ @Override protected boolean handleTrackedPred( MutableIntSet curTrackedSet, PointerKeyAndState predPkAndState, IFlowLabel label) { boolean result = super.handleTrackedPred(curTrackedSet, predPkAndState, label); if (result && find(pkToTrackedSet, predPkAndState).contains(queriedIkAndStateNum)) { theFlowsToSet.add(predPkAndState); } return result; } } }
109,048
40.86142
118
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/demandpa/alg/IDemandPointerAnalysis.java
/* * This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html. * * This file is a derivative of code released by the University of * California under the terms listed below. * * Refinement Analysis Tools is Copyright (c) 2007 The Regents of the * University of California (Regents). Provided that this notice and * the following two paragraphs are included in any distribution of * Refinement Analysis Tools or its derivative work, Regents agrees * not to assert any of Regents' copyright rights in Refinement * Analysis Tools against recipient for recipient's reproduction, * preparation of derivative works, public display, public * performance, distribution or sublicensing of Refinement Analysis * Tools and derivative works, in source code and object code form. * This agreement not to assert does not confer, by implication, * estoppel, or otherwise any license or rights in any intellectual * property of Regents, including, but not limited to, any patents * of Regents or Regents' employees. * * IN NO EVENT SHALL REGENTS BE LIABLE TO ANY PARTY FOR DIRECT, * INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, * INCLUDING LOST PROFITS, ARISING OUT OF THE USE OF THIS SOFTWARE * AND ITS DOCUMENTATION, EVEN IF REGENTS HAS BEEN ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * REGENTS SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE AND FURTHER DISCLAIMS ANY STATUTORY * WARRANTY OF NON-INFRINGEMENT. THE SOFTWARE AND ACCOMPANYING * DOCUMENTATION, IF ANY, PROVIDED HEREUNDER IS PROVIDED "AS * IS". REGENTS HAS NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, * UPDATES, ENHANCEMENTS, OR MODIFICATIONS. */ package com.ibm.wala.demandpa.alg; import com.ibm.wala.ipa.callgraph.CallGraph; import com.ibm.wala.ipa.callgraph.propagation.HeapModel; import com.ibm.wala.ipa.callgraph.propagation.InstanceKey; import com.ibm.wala.ipa.callgraph.propagation.PointerKey; import com.ibm.wala.ipa.cha.IClassHierarchy; import java.util.Collection; /** * Basic interface for a demand-driven points-to analysis. * * @author Manu Sridharan */ public interface IDemandPointerAnalysis { HeapModel getHeapModel(); CallGraph getBaseCallGraph(); IClassHierarchy getClassHierarchy(); Collection<InstanceKey> getPointsTo(PointerKey pk); }
2,545
40.064516
72
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/demandpa/alg/InstanceFieldKeyAndState.java
/* * This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html. * * This file is a derivative of code released by the University of * California under the terms listed below. * * Refinement Analysis Tools is Copyright (c) 2007 The Regents of the * University of California (Regents). Provided that this notice and * the following two paragraphs are included in any distribution of * Refinement Analysis Tools or its derivative work, Regents agrees * not to assert any of Regents' copyright rights in Refinement * Analysis Tools against recipient for recipient's reproduction, * preparation of derivative works, public display, public * performance, distribution or sublicensing of Refinement Analysis * Tools and derivative works, in source code and object code form. * This agreement not to assert does not confer, by implication, * estoppel, or otherwise any license or rights in any intellectual * property of Regents, including, but not limited to, any patents * of Regents or Regents' employees. * * IN NO EVENT SHALL REGENTS BE LIABLE TO ANY PARTY FOR DIRECT, * INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, * INCLUDING LOST PROFITS, ARISING OUT OF THE USE OF THIS SOFTWARE * AND ITS DOCUMENTATION, EVEN IF REGENTS HAS BEEN ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * REGENTS SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE AND FURTHER DISCLAIMS ANY STATUTORY * WARRANTY OF NON-INFRINGEMENT. THE SOFTWARE AND ACCOMPANYING * DOCUMENTATION, IF ANY, PROVIDED HEREUNDER IS PROVIDED "AS * IS". REGENTS HAS NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, * UPDATES, ENHANCEMENTS, OR MODIFICATIONS. */ package com.ibm.wala.demandpa.alg; import com.ibm.wala.demandpa.alg.statemachine.StateMachine.State; import com.ibm.wala.ipa.callgraph.propagation.InstanceFieldKey; public class InstanceFieldKeyAndState extends WithState<InstanceFieldKey> { public InstanceFieldKeyAndState(InstanceFieldKey wrapped, State state) { super(wrapped, state); } public InstanceFieldKey getInstanceFieldKey() { return getWrapped(); } }
2,350
43.358491
75
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/demandpa/alg/InstanceKeyAndState.java
/* * This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html. * * This file is a derivative of code released by the University of * California under the terms listed below. * * Refinement Analysis Tools is Copyright (c) 2007 The Regents of the * University of California (Regents). Provided that this notice and * the following two paragraphs are included in any distribution of * Refinement Analysis Tools or its derivative work, Regents agrees * not to assert any of Regents' copyright rights in Refinement * Analysis Tools against recipient for recipient's reproduction, * preparation of derivative works, public display, public * performance, distribution or sublicensing of Refinement Analysis * Tools and derivative works, in source code and object code form. * This agreement not to assert does not confer, by implication, * estoppel, or otherwise any license or rights in any intellectual * property of Regents, including, but not limited to, any patents * of Regents or Regents' employees. * * IN NO EVENT SHALL REGENTS BE LIABLE TO ANY PARTY FOR DIRECT, * INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, * INCLUDING LOST PROFITS, ARISING OUT OF THE USE OF THIS SOFTWARE * AND ITS DOCUMENTATION, EVEN IF REGENTS HAS BEEN ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * REGENTS SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE AND FURTHER DISCLAIMS ANY STATUTORY * WARRANTY OF NON-INFRINGEMENT. THE SOFTWARE AND ACCOMPANYING * DOCUMENTATION, IF ANY, PROVIDED HEREUNDER IS PROVIDED "AS * IS". REGENTS HAS NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, * UPDATES, ENHANCEMENTS, OR MODIFICATIONS. */ package com.ibm.wala.demandpa.alg; import com.ibm.wala.demandpa.alg.statemachine.StateMachine.State; import com.ibm.wala.ipa.callgraph.propagation.InstanceKey; /** @author Manu Sridharan */ public class InstanceKeyAndState extends WithState<InstanceKey> { public InstanceKeyAndState(InstanceKey ik, State state) { super(ik, state); } public InstanceKey getInstanceKey() { return getWrapped(); } }
2,334
43.056604
72
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/demandpa/alg/IntraProcFilter.java
/* * This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html. * * This file is a derivative of code released by the University of * California under the terms listed below. * * Refinement Analysis Tools is Copyright (c) 2007 The Regents of the * University of California (Regents). Provided that this notice and * the following two paragraphs are included in any distribution of * Refinement Analysis Tools or its derivative work, Regents agrees * not to assert any of Regents' copyright rights in Refinement * Analysis Tools against recipient for recipient's reproduction, * preparation of derivative works, public display, public * performance, distribution or sublicensing of Refinement Analysis * Tools and derivative works, in source code and object code form. * This agreement not to assert does not confer, by implication, * estoppel, or otherwise any license or rights in any intellectual * property of Regents, including, but not limited to, any patents * of Regents or Regents' employees. * * IN NO EVENT SHALL REGENTS BE LIABLE TO ANY PARTY FOR DIRECT, * INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, * INCLUDING LOST PROFITS, ARISING OUT OF THE USE OF THIS SOFTWARE * AND ITS DOCUMENTATION, EVEN IF REGENTS HAS BEEN ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * REGENTS SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE AND FURTHER DISCLAIMS ANY STATUTORY * WARRANTY OF NON-INFRINGEMENT. THE SOFTWARE AND ACCOMPANYING * DOCUMENTATION, IF ANY, PROVIDED HEREUNDER IS PROVIDED "AS * IS". REGENTS HAS NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, * UPDATES, ENHANCEMENTS, OR MODIFICATIONS. */ package com.ibm.wala.demandpa.alg; import com.ibm.wala.demandpa.alg.statemachine.StateMachine; import com.ibm.wala.demandpa.alg.statemachine.StateMachineFactory; import com.ibm.wala.demandpa.flowgraph.AbstractFlowLabelVisitor; import com.ibm.wala.demandpa.flowgraph.IFlowLabel; import com.ibm.wala.demandpa.flowgraph.ParamBarLabel; import com.ibm.wala.demandpa.flowgraph.ParamLabel; import com.ibm.wala.demandpa.flowgraph.ReturnBarLabel; import com.ibm.wala.demandpa.flowgraph.ReturnLabel; /** * State machine that only allows intraprocedural paths. Mainly for testing purposes. * * @author Manu Sridharan */ public class IntraProcFilter implements StateMachine<IFlowLabel> { private static final State DUMMY = new State() {}; @Override public State getStartState() { return DUMMY; } private static class InterprocFilterVisitor extends AbstractFlowLabelVisitor { @Override public void visitParamBar(ParamBarLabel label, Object dst) { interprocEdge = true; } @Override public void visitParam(ParamLabel label, Object dst) { interprocEdge = true; } @Override public void visitReturn(ReturnLabel label, Object dst) { interprocEdge = true; } @Override public void visitReturnBar(ReturnBarLabel label, Object dst) { interprocEdge = true; } boolean interprocEdge = false; } @Override public State transition(State prevState, IFlowLabel label) throws IllegalArgumentException { if (label == null) { throw new IllegalArgumentException("label == null"); } // filter out all interprocedural edges InterprocFilterVisitor v = new InterprocFilterVisitor(); label.visit(v, null); return v.interprocEdge ? ERROR : DUMMY; } private IntraProcFilter() {} public static class Factory implements StateMachineFactory<IFlowLabel> { @Override public StateMachine<IFlowLabel> make() { return new IntraProcFilter(); } } }
3,884
34.972222
94
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/demandpa/alg/PointerKeyAndState.java
/* * This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html. * * This file is a derivative of code released by the University of * California under the terms listed below. * * Refinement Analysis Tools is Copyright (c) 2007 The Regents of the * University of California (Regents). Provided that this notice and * the following two paragraphs are included in any distribution of * Refinement Analysis Tools or its derivative work, Regents agrees * not to assert any of Regents' copyright rights in Refinement * Analysis Tools against recipient for recipient's reproduction, * preparation of derivative works, public display, public * performance, distribution or sublicensing of Refinement Analysis * Tools and derivative works, in source code and object code form. * This agreement not to assert does not confer, by implication, * estoppel, or otherwise any license or rights in any intellectual * property of Regents, including, but not limited to, any patents * of Regents or Regents' employees. * * IN NO EVENT SHALL REGENTS BE LIABLE TO ANY PARTY FOR DIRECT, * INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, * INCLUDING LOST PROFITS, ARISING OUT OF THE USE OF THIS SOFTWARE * AND ITS DOCUMENTATION, EVEN IF REGENTS HAS BEEN ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * REGENTS SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE AND FURTHER DISCLAIMS ANY STATUTORY * WARRANTY OF NON-INFRINGEMENT. THE SOFTWARE AND ACCOMPANYING * DOCUMENTATION, IF ANY, PROVIDED HEREUNDER IS PROVIDED "AS * IS". REGENTS HAS NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, * UPDATES, ENHANCEMENTS, OR MODIFICATIONS. */ package com.ibm.wala.demandpa.alg; import com.ibm.wala.demandpa.alg.statemachine.StateMachine.State; import com.ibm.wala.ipa.callgraph.propagation.PointerKey; /** @author Manu Sridharan */ public class PointerKeyAndState extends WithState<PointerKey> { public PointerKeyAndState(PointerKey pk, State state) { super(pk, state); } public PointerKey getPointerKey() { return getWrapped(); } }
2,328
42.12963
72
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/demandpa/alg/SimpleDemandPointsTo.java
/* * This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html. * * This file is a derivative of code released by the University of * California under the terms listed below. * * Refinement Analysis Tools is Copyright (c) 2007 The Regents of the * University of California (Regents). Provided that this notice and * the following two paragraphs are included in any distribution of * Refinement Analysis Tools or its derivative work, Regents agrees * not to assert any of Regents' copyright rights in Refinement * Analysis Tools against recipient for recipient's reproduction, * preparation of derivative works, public display, public * performance, distribution or sublicensing of Refinement Analysis * Tools and derivative works, in source code and object code form. * This agreement not to assert does not confer, by implication, * estoppel, or otherwise any license or rights in any intellectual * property of Regents, including, but not limited to, any patents * of Regents or Regents' employees. * * IN NO EVENT SHALL REGENTS BE LIABLE TO ANY PARTY FOR DIRECT, * INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, * INCLUDING LOST PROFITS, ARISING OUT OF THE USE OF THIS SOFTWARE * AND ITS DOCUMENTATION, EVEN IF REGENTS HAS BEEN ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * REGENTS SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE AND FURTHER DISCLAIMS ANY STATUTORY * WARRANTY OF NON-INFRINGEMENT. THE SOFTWARE AND ACCOMPANYING * DOCUMENTATION, IF ANY, PROVIDED HEREUNDER IS PROVIDED "AS * IS". REGENTS HAS NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, * UPDATES, ENHANCEMENTS, OR MODIFICATIONS. */ package com.ibm.wala.demandpa.alg; import com.ibm.wala.demandpa.flowgraph.SimpleDemandPointerFlowGraph; import com.ibm.wala.demandpa.util.MemoryAccessMap; import com.ibm.wala.ipa.callgraph.AnalysisOptions; import com.ibm.wala.ipa.callgraph.CGNode; import com.ibm.wala.ipa.callgraph.CallGraph; import com.ibm.wala.ipa.callgraph.propagation.HeapModel; import com.ibm.wala.ipa.callgraph.propagation.InstanceKey; import com.ibm.wala.ipa.callgraph.propagation.LocalPointerKey; import com.ibm.wala.ipa.callgraph.propagation.PointerKey; import com.ibm.wala.ipa.cha.IClassHierarchy; import com.ibm.wala.util.collections.HashSetFactory; import com.ibm.wala.util.debug.UnimplementedError; import com.ibm.wala.util.graph.traverse.SlowDFSDiscoverTimeIterator; import java.util.Collection; import java.util.Collections; /** * Purely field-based, context-insensitive demand-driven points-to analysis with very simple * implementation. * * @author Manu Sridharan */ public class SimpleDemandPointsTo extends AbstractDemandPointsTo { private static final boolean VERBOSE = false; public SimpleDemandPointsTo( CallGraph cg, HeapModel model, MemoryAccessMap fam, IClassHierarchy cha, AnalysisOptions options) { super(cg, model, fam, cha, options); } @Override public Collection<InstanceKey> getPointsTo(PointerKey pk) throws IllegalArgumentException, UnimplementedError { if (pk == null) { throw new IllegalArgumentException("pk == null"); } assert pk instanceof LocalPointerKey : "we only handle locals"; LocalPointerKey lpk = (LocalPointerKey) pk; // Create an (initially empty) dependence graph SimpleDemandPointerFlowGraph g = new SimpleDemandPointerFlowGraph(cg, heapModel, mam, cha); // initialize the graph with the subgraph of x's method CGNode node = lpk.getNode(); g.addSubgraphForNode(node); if (!g.containsNode(pk)) { return Collections.emptySet(); } if (VERBOSE) { System.err.println(g); } SlowDFSDiscoverTimeIterator<Object> dfs = new SlowDFSDiscoverTimeIterator<>(g, pk); Collection<InstanceKey> keys = HashSetFactory.make(); while (dfs.hasNext()) { Object o = dfs.next(); if (o instanceof InstanceKey) { keys.add((InstanceKey) o); } } return keys; } }
4,252
37.315315
95
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/demandpa/alg/ThisFilteringHeapModel.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.demandpa.alg; import com.ibm.wala.classLoader.IClass; import com.ibm.wala.classLoader.IField; import com.ibm.wala.classLoader.IMethod; import com.ibm.wala.classLoader.NewSiteReference; import com.ibm.wala.classLoader.ProgramCounter; import com.ibm.wala.ipa.callgraph.CGNode; import com.ibm.wala.ipa.callgraph.ContextKey; import com.ibm.wala.ipa.callgraph.propagation.FilteredPointerKey; import com.ibm.wala.ipa.callgraph.propagation.FilteredPointerKey.TypeFilter; import com.ibm.wala.ipa.callgraph.propagation.HeapModel; import com.ibm.wala.ipa.callgraph.propagation.InstanceKey; import com.ibm.wala.ipa.callgraph.propagation.PointerKey; import com.ibm.wala.ipa.cha.IClassHierarchy; import com.ibm.wala.types.TypeReference; import com.ibm.wala.util.debug.Assertions; import java.util.Iterator; /** * a {@link HeapModel} that delegates to another except for pointer keys representing {@code this} * parameters of methods, for which it returns a {@link FilteredPointerKey} for the type of the * parameter * * @see DemandRefinementPointsTo * @author manu */ class ThisFilteringHeapModel implements HeapModel { private final HeapModel delegate; private final IClassHierarchy cha; @Override public IClassHierarchy getClassHierarchy() { return delegate.getClassHierarchy(); } @Override public FilteredPointerKey getFilteredPointerKeyForLocal( CGNode node, int valueNumber, TypeFilter filter) { return delegate.getFilteredPointerKeyForLocal(node, valueNumber, filter); } @Override public InstanceKey getInstanceKeyForAllocation(CGNode node, NewSiteReference allocation) { return delegate.getInstanceKeyForAllocation(node, allocation); } @Override public InstanceKey getInstanceKeyForMetadataObject(Object obj, TypeReference objType) { return delegate.getInstanceKeyForMetadataObject(obj, objType); } @Override public InstanceKey getInstanceKeyForConstant(TypeReference type, Object S) { return delegate.getInstanceKeyForConstant(type, S); } @Override public InstanceKey getInstanceKeyForMultiNewArray( CGNode node, NewSiteReference allocation, int dim) { return delegate.getInstanceKeyForMultiNewArray(node, allocation, dim); } @Override public InstanceKey getInstanceKeyForPEI(CGNode node, ProgramCounter instr, TypeReference type) { return delegate.getInstanceKeyForPEI(node, instr, type); } @Override public PointerKey getPointerKeyForArrayContents(InstanceKey I) { return delegate.getPointerKeyForArrayContents(I); } @Override public PointerKey getPointerKeyForExceptionalReturnValue(CGNode node) { return delegate.getPointerKeyForExceptionalReturnValue(node); } @Override public PointerKey getPointerKeyForInstanceField(InstanceKey I, IField field) { return delegate.getPointerKeyForInstanceField(I, field); } @Override public PointerKey getPointerKeyForLocal(CGNode node, int valueNumber) { if (!node.getMethod().isStatic() && valueNumber == 1) { return delegate.getFilteredPointerKeyForLocal(node, valueNumber, getFilter(node)); } else { return delegate.getPointerKeyForLocal(node, valueNumber); } } private FilteredPointerKey.TypeFilter getFilter(CGNode target) { FilteredPointerKey.TypeFilter filter = (FilteredPointerKey.TypeFilter) target.getContext().get(ContextKey.PARAMETERS[0]); if (filter != null) { return filter; } else { // the context does not select a particular concrete type for the // receiver. IClass C = getReceiverClass(target.getMethod()); return new FilteredPointerKey.SingleClassFilter(C); } } /** @return the receiver class for this method. */ private IClass getReceiverClass(IMethod method) { TypeReference formalType = method.getParameterType(0); IClass C = cha.lookupClass(formalType); if (method.isStatic()) { Assertions.UNREACHABLE("asked for receiver of static method " + method); } if (C == null) { Assertions.UNREACHABLE("no class found for " + formalType + " recv of " + method); } return C; } @Override public PointerKey getPointerKeyForReturnValue(CGNode node) { return delegate.getPointerKeyForReturnValue(node); } @Override public PointerKey getPointerKeyForStaticField(IField f) { return delegate.getPointerKeyForStaticField(f); } @Override public Iterator<PointerKey> iteratePointerKeys() { return delegate.iteratePointerKeys(); } public ThisFilteringHeapModel(HeapModel delegate, IClassHierarchy cha) { if (delegate == null) { throw new IllegalArgumentException("delegate null"); } this.delegate = delegate; this.cha = cha; } }
5,092
31.858065
98
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/demandpa/alg/WithState.java
/* * This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html. * * This file is a derivative of code released by the University of * California under the terms listed below. * * Refinement Analysis Tools is Copyright (c) 2007 The Regents of the * University of California (Regents). Provided that this notice and * the following two paragraphs are included in any distribution of * Refinement Analysis Tools or its derivative work, Regents agrees * not to assert any of Regents' copyright rights in Refinement * Analysis Tools against recipient for recipient's reproduction, * preparation of derivative works, public display, public * performance, distribution or sublicensing of Refinement Analysis * Tools and derivative works, in source code and object code form. * This agreement not to assert does not confer, by implication, * estoppel, or otherwise any license or rights in any intellectual * property of Regents, including, but not limited to, any patents * of Regents or Regents' employees. * * IN NO EVENT SHALL REGENTS BE LIABLE TO ANY PARTY FOR DIRECT, * INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, * INCLUDING LOST PROFITS, ARISING OUT OF THE USE OF THIS SOFTWARE * AND ITS DOCUMENTATION, EVEN IF REGENTS HAS BEEN ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * REGENTS SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE AND FURTHER DISCLAIMS ANY STATUTORY * WARRANTY OF NON-INFRINGEMENT. THE SOFTWARE AND ACCOMPANYING * DOCUMENTATION, IF ANY, PROVIDED HEREUNDER IS PROVIDED "AS * IS". REGENTS HAS NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, * UPDATES, ENHANCEMENTS, OR MODIFICATIONS. */ package com.ibm.wala.demandpa.alg; import com.ibm.wala.demandpa.alg.statemachine.StateMachine.State; /** Simple abstraction for pairing some type with a {@link State}. */ public abstract class WithState<T> { private final T wrapped; private final State state; private final int hc; public WithState(final T wrapped, final State state) { if (wrapped == null) { throw new IllegalArgumentException("null wrapped"); } if (state == null) { throw new IllegalArgumentException("null state"); } this.wrapped = wrapped; this.state = state; this.hc = 31 * state.hashCode() + wrapped.hashCode(); } public State getState() { return state; } public T getWrapped() { return wrapped; } @Override public String toString() { return wrapped + ", STATE " + state; } @Override public int hashCode() { return hc; } @SuppressWarnings("unchecked") @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; final WithState<T> other = (WithState<T>) obj; if (state == null) { if (other.state != null) return false; } else if (!state.equals(other.state)) return false; if (wrapped == null) { if (other.wrapped != null) return false; } else if (!wrapped.equals(other.wrapped)) return false; return true; } }
3,349
33.536082
72
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/demandpa/alg/refinepolicy/AbstractRefinementPolicy.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.demandpa.alg.refinepolicy; import java.util.Arrays; /** * Default {@link RefinementPolicy} implementation, delegating to some provided {@link * FieldRefinePolicy} and {@link CallGraphRefinePolicy} * * @author manu */ public abstract class AbstractRefinementPolicy implements RefinementPolicy { protected static final int DEFAULT_NUM_PASSES = 4; protected static final int LONGER_PASS_BUDGET = 12000; private static final int SHORTER_PASS_BUDGET = 1000; private static final int[] DEFAULT_BUDGET_PER_PASS; static { int[] tmp = new int[DEFAULT_NUM_PASSES]; tmp[0] = SHORTER_PASS_BUDGET; Arrays.fill(tmp, 1, DEFAULT_NUM_PASSES, LONGER_PASS_BUDGET); DEFAULT_BUDGET_PER_PASS = tmp; } protected final FieldRefinePolicy fieldRefinePolicy; protected final CallGraphRefinePolicy cgRefinePolicy; protected final int numPasses; protected final int[] budgetPerPass; public AbstractRefinementPolicy( FieldRefinePolicy fieldRefinePolicy, CallGraphRefinePolicy cgRefinePolicy, int numPasses, int[] budgetPerPass) { this.fieldRefinePolicy = fieldRefinePolicy; this.cgRefinePolicy = cgRefinePolicy; this.numPasses = numPasses; this.budgetPerPass = budgetPerPass; } public AbstractRefinementPolicy( FieldRefinePolicy fieldRefinePolicy, CallGraphRefinePolicy cgRefinePolicy) { this(fieldRefinePolicy, cgRefinePolicy, DEFAULT_NUM_PASSES, DEFAULT_BUDGET_PER_PASS); } @Override public int getBudgetForPass(int passNum) { return budgetPerPass[passNum]; } @Override public CallGraphRefinePolicy getCallGraphRefinePolicy() { return cgRefinePolicy; } @Override public FieldRefinePolicy getFieldRefinePolicy() { return fieldRefinePolicy; } @Override public int getNumPasses() { return numPasses; } @Override public boolean nextPass() { // don't short-circuit since nextPass() can have side-effects boolean fieldNextPass = fieldRefinePolicy.nextPass(); boolean callNextPass = cgRefinePolicy.nextPass(); return fieldNextPass || callNextPass; } }
2,485
26.622222
89
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/demandpa/alg/refinepolicy/AlwaysRefineCGPolicy.java
/* * This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html. * * This file is a derivative of code released by the University of * California under the terms listed below. * * Refinement Analysis Tools is Copyright (c) 2007 The Regents of the * University of California (Regents). Provided that this notice and * the following two paragraphs are included in any distribution of * Refinement Analysis Tools or its derivative work, Regents agrees * not to assert any of Regents' copyright rights in Refinement * Analysis Tools against recipient for recipient's reproduction, * preparation of derivative works, public display, public * performance, distribution or sublicensing of Refinement Analysis * Tools and derivative works, in source code and object code form. * This agreement not to assert does not confer, by implication, * estoppel, or otherwise any license or rights in any intellectual * property of Regents, including, but not limited to, any patents * of Regents or Regents' employees. * * IN NO EVENT SHALL REGENTS BE LIABLE TO ANY PARTY FOR DIRECT, * INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, * INCLUDING LOST PROFITS, ARISING OUT OF THE USE OF THIS SOFTWARE * AND ITS DOCUMENTATION, EVEN IF REGENTS HAS BEEN ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * REGENTS SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE AND FURTHER DISCLAIMS ANY STATUTORY * WARRANTY OF NON-INFRINGEMENT. THE SOFTWARE AND ACCOMPANYING * DOCUMENTATION, IF ANY, PROVIDED HEREUNDER IS PROVIDED "AS * IS". REGENTS HAS NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, * UPDATES, ENHANCEMENTS, OR MODIFICATIONS. */ package com.ibm.wala.demandpa.alg.refinepolicy; import com.ibm.wala.ipa.callgraph.propagation.cfa.CallerSiteContext; /** A policy that always refines the call graph. */ public class AlwaysRefineCGPolicy implements CallGraphRefinePolicy { @Override public boolean shouldRefine(CallerSiteContext callSiteAndCGNode) { return true; } @Override public boolean nextPass() { return false; } }
2,328
41.345455
72
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/demandpa/alg/refinepolicy/AlwaysRefineFieldsPolicy.java
/* * This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html. * * This file is a derivative of code released by the University of * California under the terms listed below. * * Refinement Analysis Tools is Copyright (c) 2007 The Regents of the * University of California (Regents). Provided that this notice and * the following two paragraphs are included in any distribution of * Refinement Analysis Tools or its derivative work, Regents agrees * not to assert any of Regents' copyright rights in Refinement * Analysis Tools against recipient for recipient's reproduction, * preparation of derivative works, public display, public * performance, distribution or sublicensing of Refinement Analysis * Tools and derivative works, in source code and object code form. * This agreement not to assert does not confer, by implication, * estoppel, or otherwise any license or rights in any intellectual * property of Regents, including, but not limited to, any patents * of Regents or Regents' employees. * * IN NO EVENT SHALL REGENTS BE LIABLE TO ANY PARTY FOR DIRECT, * INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, * INCLUDING LOST PROFITS, ARISING OUT OF THE USE OF THIS SOFTWARE * AND ITS DOCUMENTATION, EVEN IF REGENTS HAS BEEN ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * REGENTS SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE AND FURTHER DISCLAIMS ANY STATUTORY * WARRANTY OF NON-INFRINGEMENT. THE SOFTWARE AND ACCOMPANYING * DOCUMENTATION, IF ANY, PROVIDED HEREUNDER IS PROVIDED "AS * IS". REGENTS HAS NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, * UPDATES, ENHANCEMENTS, OR MODIFICATIONS. */ package com.ibm.wala.demandpa.alg.refinepolicy; import com.ibm.wala.classLoader.IField; import com.ibm.wala.demandpa.alg.statemachine.StateMachine; import com.ibm.wala.demandpa.flowgraph.IFlowLabel; import com.ibm.wala.ipa.callgraph.propagation.PointerKey; /** * A policy that always refines handling of field accesses by checking for an alias path * corresponding to each match edge. * * @author Manu Sridharan */ public class AlwaysRefineFieldsPolicy implements FieldRefinePolicy { @Override public boolean shouldRefine( IField field, PointerKey basePtr, PointerKey val, IFlowLabel label, StateMachine.State state) { return true; } @Override public boolean nextPass() { return false; } }
2,668
37.681159
88
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/demandpa/alg/refinepolicy/CallGraphRefinePolicy.java
/* * This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html. * * This file is a derivative of code released by the University of * California under the terms listed below. * * Refinement Analysis Tools is Copyright (c) 2007 The Regents of the * University of California (Regents). Provided that this notice and * the following two paragraphs are included in any distribution of * Refinement Analysis Tools or its derivative work, Regents agrees * not to assert any of Regents' copyright rights in Refinement * Analysis Tools against recipient for recipient's reproduction, * preparation of derivative works, public display, public * performance, distribution or sublicensing of Refinement Analysis * Tools and derivative works, in source code and object code form. * This agreement not to assert does not confer, by implication, * estoppel, or otherwise any license or rights in any intellectual * property of Regents, including, but not limited to, any patents * of Regents or Regents' employees. * * IN NO EVENT SHALL REGENTS BE LIABLE TO ANY PARTY FOR DIRECT, * INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, * INCLUDING LOST PROFITS, ARISING OUT OF THE USE OF THIS SOFTWARE * AND ITS DOCUMENTATION, EVEN IF REGENTS HAS BEEN ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * REGENTS SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE AND FURTHER DISCLAIMS ANY STATUTORY * WARRANTY OF NON-INFRINGEMENT. THE SOFTWARE AND ACCOMPANYING * DOCUMENTATION, IF ANY, PROVIDED HEREUNDER IS PROVIDED "AS * IS". REGENTS HAS NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, * UPDATES, ENHANCEMENTS, OR MODIFICATIONS. */ package com.ibm.wala.demandpa.alg.refinepolicy; import com.ibm.wala.ipa.callgraph.propagation.cfa.CallerSiteContext; /** Interface for specifying a policy for refining the call graph. */ public interface CallGraphRefinePolicy { /** * @return {@code true} if the analysis should attempt to determine targets for the virtual call * on-the-fly, and {@code false} otherwise */ boolean shouldRefine(CallerSiteContext callSiteAndCGNode); /** * @return {@code true} if more refinement can be done, and hence another pass can be attempted; * {@code false} otherwise */ boolean nextPass(); }
2,539
43.561404
98
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/demandpa/alg/refinepolicy/ContainersFieldPolicy.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.demandpa.alg.refinepolicy; import com.ibm.wala.ipa.cha.IClassHierarchy; import java.util.regex.Pattern; public class ContainersFieldPolicy extends ManualFieldPolicy { public ContainersFieldPolicy(IClassHierarchy cha) { super(cha, Pattern.compile("Ljava/util(?!(/logging)).*")); } }
682
30.045455
72
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/demandpa/alg/refinepolicy/DelegatingFieldRefinePolicy.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.demandpa.alg.refinepolicy; import com.ibm.wala.classLoader.IField; import com.ibm.wala.demandpa.alg.statemachine.StateMachine; import com.ibm.wala.demandpa.flowgraph.IFlowLabel; import com.ibm.wala.ipa.callgraph.propagation.PointerKey; /** A field refine policy that first checks with A, then delegates to B */ public class DelegatingFieldRefinePolicy implements FieldRefinePolicy { private final FieldRefinePolicy A; private final FieldRefinePolicy B; public DelegatingFieldRefinePolicy(FieldRefinePolicy a, FieldRefinePolicy b) { if (a == null) { throw new IllegalArgumentException("null A"); } if (b == null) { throw new IllegalArgumentException("null B"); } A = a; B = b; } @Override public boolean nextPass() { // careful not to short-circuit here, since nextPass() can have side-effects boolean AnextPass = A.nextPass(); boolean BnextPass = B.nextPass(); return AnextPass || BnextPass; } /** * returns {@code true} if {@code A.shouldRefine(field) || B.shouldRefine(field)}. Note that if * {@code A.shouldRefine(field)} is {@code true}, {@code B.shouldRefine(field)} is <em>not</em> * called. */ @Override public boolean shouldRefine( IField field, PointerKey basePtr, PointerKey val, IFlowLabel label, StateMachine.State state) { // make code explicit to avoid subtle reliance on short-circuiting boolean AshouldRefine = A.shouldRefine(field, basePtr, val, label, state); if (AshouldRefine) { return true; } else { return B.shouldRefine(field, basePtr, val, label, state); } } }
2,036
30.338462
97
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/demandpa/alg/refinepolicy/FieldRefinePolicy.java
/* * This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html. * * This file is a derivative of code released by the University of * California under the terms listed below. * * Refinement Analysis Tools is Copyright (c) 2007 The Regents of the * University of California (Regents). Provided that this notice and * the following two paragraphs are included in any distribution of * Refinement Analysis Tools or its derivative work, Regents agrees * not to assert any of Regents' copyright rights in Refinement * Analysis Tools against recipient for recipient's reproduction, * preparation of derivative works, public display, public * performance, distribution or sublicensing of Refinement Analysis * Tools and derivative works, in source code and object code form. * This agreement not to assert does not confer, by implication, * estoppel, or otherwise any license or rights in any intellectual * property of Regents, including, but not limited to, any patents * of Regents or Regents' employees. * * IN NO EVENT SHALL REGENTS BE LIABLE TO ANY PARTY FOR DIRECT, * INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, * INCLUDING LOST PROFITS, ARISING OUT OF THE USE OF THIS SOFTWARE * AND ITS DOCUMENTATION, EVEN IF REGENTS HAS BEEN ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * REGENTS SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE AND FURTHER DISCLAIMS ANY STATUTORY * WARRANTY OF NON-INFRINGEMENT. THE SOFTWARE AND ACCOMPANYING * DOCUMENTATION, IF ANY, PROVIDED HEREUNDER IS PROVIDED "AS * IS". REGENTS HAS NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, * UPDATES, ENHANCEMENTS, OR MODIFICATIONS. */ package com.ibm.wala.demandpa.alg.refinepolicy; import com.ibm.wala.classLoader.IField; import com.ibm.wala.demandpa.alg.statemachine.StateMachine; import com.ibm.wala.demandpa.flowgraph.IFlowLabel; import com.ibm.wala.ipa.callgraph.propagation.PointerKey; /** * Interface for specifying a policy for refinement of field access handling. * * @author Manu Sridharan */ public interface FieldRefinePolicy { /** * @param field the accessed field * @param basePtr the base pointer of the access * @return {@code true} if match edges for the field access should be refined. Otherwise, {@code * false} is returned, indicating that the field can be handled with match edges. */ boolean shouldRefine( IField field, PointerKey basePtr, PointerKey val, IFlowLabel label, StateMachine.State state); /** * @return {@code true} if more refinement can be done, and hence another pass can be attempted; * {@code false} otherwise */ boolean nextPass(); }
2,911
42.462687
100
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/demandpa/alg/refinepolicy/ManualCGRefinePolicy.java
/* * This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html. * * This file is a derivative of code released by the University of * California under the terms listed below. * * Refinement Analysis Tools is Copyright (c) 2007 The Regents of the * University of California (Regents). Provided that this notice and * the following two paragraphs are included in any distribution of * Refinement Analysis Tools or its derivative work, Regents agrees * not to assert any of Regents' copyright rights in Refinement * Analysis Tools against recipient for recipient's reproduction, * preparation of derivative works, public display, public * performance, distribution or sublicensing of Refinement Analysis * Tools and derivative works, in source code and object code form. * This agreement not to assert does not confer, by implication, * estoppel, or otherwise any license or rights in any intellectual * property of Regents, including, but not limited to, any patents * of Regents or Regents' employees. * * IN NO EVENT SHALL REGENTS BE LIABLE TO ANY PARTY FOR DIRECT, * INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, * INCLUDING LOST PROFITS, ARISING OUT OF THE USE OF THIS SOFTWARE * AND ITS DOCUMENTATION, EVEN IF REGENTS HAS BEEN ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * REGENTS SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE AND FURTHER DISCLAIMS ANY STATUTORY * WARRANTY OF NON-INFRINGEMENT. THE SOFTWARE AND ACCOMPANYING * DOCUMENTATION, IF ANY, PROVIDED HEREUNDER IS PROVIDED "AS * IS". REGENTS HAS NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, * UPDATES, ENHANCEMENTS, OR MODIFICATIONS. */ package com.ibm.wala.demandpa.alg.refinepolicy; import com.ibm.wala.ipa.callgraph.propagation.cfa.CallerSiteContext; import com.ibm.wala.types.MethodReference; /** * A call graph refinement policy with manual annotations for which virtual call sites to refine. */ public class ManualCGRefinePolicy implements CallGraphRefinePolicy { @Override public boolean shouldRefine(CallerSiteContext callSiteAndCGNode) throws IllegalArgumentException { if (callSiteAndCGNode == null) { throw new IllegalArgumentException("callSiteAndCGNode == null"); } MethodReference declaredTarget = callSiteAndCGNode.getCallSite().getDeclaredTarget(); if (declaredTarget.toString().contains("toString()Ljava/lang/String")) { return false; } return true; } @Override public boolean nextPass() { return false; } }
2,764
41.538462
100
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/demandpa/alg/refinepolicy/ManualFieldPolicy.java
/* * This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html. * * This file is a derivative of code released by the University of * California under the terms listed below. * * Refinement Analysis Tools is Copyright (c) 2007 The Regents of the * University of California (Regents). Provided that this notice and * the following two paragraphs are included in any distribution of * Refinement Analysis Tools or its derivative work, Regents agrees * not to assert any of Regents' copyright rights in Refinement * Analysis Tools against recipient for recipient's reproduction, * preparation of derivative works, public display, public * performance, distribution or sublicensing of Refinement Analysis * Tools and derivative works, in source code and object code form. * This agreement not to assert does not confer, by implication, * estoppel, or otherwise any license or rights in any intellectual * property of Regents, including, but not limited to, any patents * of Regents or Regents' employees. * * IN NO EVENT SHALL REGENTS BE LIABLE TO ANY PARTY FOR DIRECT, * INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, * INCLUDING LOST PROFITS, ARISING OUT OF THE USE OF THIS SOFTWARE * AND ITS DOCUMENTATION, EVEN IF REGENTS HAS BEEN ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * REGENTS SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE AND FURTHER DISCLAIMS ANY STATUTORY * WARRANTY OF NON-INFRINGEMENT. THE SOFTWARE AND ACCOMPANYING * DOCUMENTATION, IF ANY, PROVIDED HEREUNDER IS PROVIDED "AS * IS". REGENTS HAS NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, * UPDATES, ENHANCEMENTS, OR MODIFICATIONS. */ package com.ibm.wala.demandpa.alg.refinepolicy; import com.ibm.wala.classLoader.IClass; import com.ibm.wala.classLoader.IField; import com.ibm.wala.demandpa.alg.statemachine.StateMachine; import com.ibm.wala.demandpa.flowgraph.IFlowLabel; import com.ibm.wala.demandpa.util.ArrayContents; import com.ibm.wala.ipa.callgraph.propagation.PointerKey; import com.ibm.wala.ipa.cha.IClassHierarchy; import com.ibm.wala.types.ClassLoaderReference; import com.ibm.wala.types.TypeReference; import java.util.regex.Matcher; import java.util.regex.Pattern; /** Manually annotated policy for refining field accesses. */ public class ManualFieldPolicy implements FieldRefinePolicy { protected final Pattern refinePattern; // = // Pattern.compile("Lca/mcgill/sable/util|Ljava/util|Lpolyglot/util/TypedList"); private static final int NUM_DECISIONS_TO_TRACK = 10; private final boolean[] decisions = new boolean[NUM_DECISIONS_TO_TRACK]; private int curDecision; private final IClass[] encounteredClasses = new IClass[NUM_DECISIONS_TO_TRACK]; @Override public boolean shouldRefine( IField field, PointerKey basePtr, PointerKey val, IFlowLabel label, StateMachine.State state) { if (field == null) { throw new IllegalArgumentException("null field"); } if (field == ArrayContents.v()) { return true; } else { final IClass declaringClass = field.getDeclaringClass(); final Matcher m = refinePattern.matcher(declaringClass.toString()); final boolean foundPattern = m.find(); recordDecision(declaringClass, foundPattern); return foundPattern; } } private void recordDecision(final IClass declaringClass, final boolean foundPattern) { if (curDecision < NUM_DECISIONS_TO_TRACK) { IClass topMostClass = removeInner(declaringClass); if (notSuperOfAnyEncountered(topMostClass)) { encounteredClasses[curDecision] = topMostClass; decisions[curDecision] = foundPattern; curDecision++; } } } private boolean notSuperOfAnyEncountered(IClass klass) { for (int i = 0; i < curDecision; i++) { if (cha.isAssignableFrom(klass, encounteredClasses[i])) { return false; } } return true; } private final IClassHierarchy cha; /** * @return the top-level {@link IClass} where klass is declared, or klass itself if klass is * top-level */ private IClass removeInner(IClass klass) { ClassLoaderReference cl = klass.getClassLoader().getReference(); String klassStr = klass.getName().toString(); int dollarIndex = klassStr.indexOf('$'); if (dollarIndex == -1) { return klass; } else { String topMostName = klassStr.substring(0, dollarIndex); IClass topMostClass = cha.lookupClass(TypeReference.findOrCreate(cl, topMostName)); assert topMostClass != null; return topMostClass; } } /** * @param refinePattern a pattern for detecting which match edges to refine. If the <em>declaring * class</em> of the field related to the match edge matches the pattern, the match edge will * be refined. For example, the pattern {@code Pattern.compile("Ljava/util")} will cause all * fields of classes in the {@code java.util} package to be refined. */ public ManualFieldPolicy(IClassHierarchy cha, Pattern refinePattern) { this.cha = cha; this.refinePattern = refinePattern; } @Override public boolean nextPass() { return false; } /** @return a String representation of the decisions made by this */ public String getHistory() { StringBuilder ret = new StringBuilder(); for (int i = 0; i < curDecision; i++) { if (decisions[i]) { ret.append("refined "); } else { ret.append("skipped "); } ret.append(encounteredClasses[i]); if (i + 1 < curDecision) { ret.append(", "); } } return ret.toString(); } }
5,879
35.521739
99
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/demandpa/alg/refinepolicy/ManualRefinementPolicy.java
/* * This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html. * * This file is a derivative of code released by the University of * California under the terms listed below. * * Refinement Analysis Tools is Copyright (c) 2007 The Regents of the * University of California (Regents). Provided that this notice and * the following two paragraphs are included in any distribution of * Refinement Analysis Tools or its derivative work, Regents agrees * not to assert any of Regents' copyright rights in Refinement * Analysis Tools against recipient for recipient's reproduction, * preparation of derivative works, public display, public * performance, distribution or sublicensing of Refinement Analysis * Tools and derivative works, in source code and object code form. * This agreement not to assert does not confer, by implication, * estoppel, or otherwise any license or rights in any intellectual * property of Regents, including, but not limited to, any patents * of Regents or Regents' employees. * * IN NO EVENT SHALL REGENTS BE LIABLE TO ANY PARTY FOR DIRECT, * INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, * INCLUDING LOST PROFITS, ARISING OUT OF THE USE OF THIS SOFTWARE * AND ITS DOCUMENTATION, EVEN IF REGENTS HAS BEEN ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * REGENTS SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE AND FURTHER DISCLAIMS ANY STATUTORY * WARRANTY OF NON-INFRINGEMENT. THE SOFTWARE AND ACCOMPANYING * DOCUMENTATION, IF ANY, PROVIDED HEREUNDER IS PROVIDED "AS * IS". REGENTS HAS NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, * UPDATES, ENHANCEMENTS, OR MODIFICATIONS. */ package com.ibm.wala.demandpa.alg.refinepolicy; import com.ibm.wala.ipa.cha.IClassHierarchy; /** * A refinement policy specified manually with annotations. * * @author Manu Sridharan */ public class ManualRefinementPolicy extends AbstractRefinementPolicy { private ManualRefinementPolicy(IClassHierarchy cha) { // since we have specified what to refine manually, no need to run multiple passes super( new ContainersFieldPolicy(cha), new AlwaysRefineCGPolicy(), 1, new int[] {LONGER_PASS_BUDGET}); } public static class Factory implements RefinementPolicyFactory { private final IClassHierarchy cha; public Factory(IClassHierarchy cha) { this.cha = cha; } @Override public RefinementPolicy make() { return new ManualRefinementPolicy(cha); } } }
2,756
37.830986
86
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/demandpa/alg/refinepolicy/NeverRefineCGPolicy.java
/* * This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html. * * This file is a derivative of code released by the University of * California under the terms listed below. * * Refinement Analysis Tools is Copyright (c) 2007 The Regents of the * University of California (Regents). Provided that this notice and * the following two paragraphs are included in any distribution of * Refinement Analysis Tools or its derivative work, Regents agrees * not to assert any of Regents' copyright rights in Refinement * Analysis Tools against recipient for recipient's reproduction, * preparation of derivative works, public display, public * performance, distribution or sublicensing of Refinement Analysis * Tools and derivative works, in source code and object code form. * This agreement not to assert does not confer, by implication, * estoppel, or otherwise any license or rights in any intellectual * property of Regents, including, but not limited to, any patents * of Regents or Regents' employees. * * IN NO EVENT SHALL REGENTS BE LIABLE TO ANY PARTY FOR DIRECT, * INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, * INCLUDING LOST PROFITS, ARISING OUT OF THE USE OF THIS SOFTWARE * AND ITS DOCUMENTATION, EVEN IF REGENTS HAS BEEN ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * REGENTS SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE AND FURTHER DISCLAIMS ANY STATUTORY * WARRANTY OF NON-INFRINGEMENT. THE SOFTWARE AND ACCOMPANYING * DOCUMENTATION, IF ANY, PROVIDED HEREUNDER IS PROVIDED "AS * IS". REGENTS HAS NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, * UPDATES, ENHANCEMENTS, OR MODIFICATIONS. */ package com.ibm.wala.demandpa.alg.refinepolicy; import com.ibm.wala.ipa.callgraph.propagation.cfa.CallerSiteContext; public class NeverRefineCGPolicy implements CallGraphRefinePolicy { @Override public boolean shouldRefine(CallerSiteContext callSiteAndCGNode) { return false; } @Override public boolean nextPass() { return false; } }
2,276
41.166667
72
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/demandpa/alg/refinepolicy/NeverRefineFieldsPolicy.java
/* * This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html. * * This file is a derivative of code released by the University of * California under the terms listed below. * * Refinement Analysis Tools is Copyright (c) 2007 The Regents of the * University of California (Regents). Provided that this notice and * the following two paragraphs are included in any distribution of * Refinement Analysis Tools or its derivative work, Regents agrees * not to assert any of Regents' copyright rights in Refinement * Analysis Tools against recipient for recipient's reproduction, * preparation of derivative works, public display, public * performance, distribution or sublicensing of Refinement Analysis * Tools and derivative works, in source code and object code form. * This agreement not to assert does not confer, by implication, * estoppel, or otherwise any license or rights in any intellectual * property of Regents, including, but not limited to, any patents * of Regents or Regents' employees. * * IN NO EVENT SHALL REGENTS BE LIABLE TO ANY PARTY FOR DIRECT, * INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, * INCLUDING LOST PROFITS, ARISING OUT OF THE USE OF THIS SOFTWARE * AND ITS DOCUMENTATION, EVEN IF REGENTS HAS BEEN ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * REGENTS SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE AND FURTHER DISCLAIMS ANY STATUTORY * WARRANTY OF NON-INFRINGEMENT. THE SOFTWARE AND ACCOMPANYING * DOCUMENTATION, IF ANY, PROVIDED HEREUNDER IS PROVIDED "AS * IS". REGENTS HAS NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, * UPDATES, ENHANCEMENTS, OR MODIFICATIONS. */ package com.ibm.wala.demandpa.alg.refinepolicy; import com.ibm.wala.classLoader.IField; import com.ibm.wala.demandpa.alg.statemachine.StateMachine; import com.ibm.wala.demandpa.flowgraph.IFlowLabel; import com.ibm.wala.ipa.callgraph.propagation.PointerKey; public class NeverRefineFieldsPolicy implements FieldRefinePolicy { @Override public boolean shouldRefine( IField field, PointerKey basePtr, PointerKey val, IFlowLabel label, StateMachine.State state) { return false; } @Override public boolean nextPass() { return false; } }
2,504
39.403226
72
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/demandpa/alg/refinepolicy/OnlyArraysPolicy.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.demandpa.alg.refinepolicy; import com.ibm.wala.classLoader.IField; import com.ibm.wala.demandpa.alg.statemachine.StateMachine.State; import com.ibm.wala.demandpa.flowgraph.IFlowLabel; import com.ibm.wala.demandpa.util.ArrayContents; import com.ibm.wala.ipa.callgraph.propagation.PointerKey; /** * Only refines for the array contents pseudo-field. * * @author manu */ public class OnlyArraysPolicy implements FieldRefinePolicy { @Override public boolean shouldRefine( IField field, PointerKey basePtr, PointerKey val, IFlowLabel label, State state) { return field == ArrayContents.v(); } @Override public boolean nextPass() { return false; } }
1,066
27.837838
88
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/demandpa/alg/refinepolicy/RefinementPolicy.java
/* * This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html. * * This file is a derivative of code released by the University of * California under the terms listed below. * * Refinement Analysis Tools is Copyright (c) 2007 The Regents of the * University of California (Regents). Provided that this notice and * the following two paragraphs are included in any distribution of * Refinement Analysis Tools or its derivative work, Regents agrees * not to assert any of Regents' copyright rights in Refinement * Analysis Tools against recipient for recipient's reproduction, * preparation of derivative works, public display, public * performance, distribution or sublicensing of Refinement Analysis * Tools and derivative works, in source code and object code form. * This agreement not to assert does not confer, by implication, * estoppel, or otherwise any license or rights in any intellectual * property of Regents, including, but not limited to, any patents * of Regents or Regents' employees. * * IN NO EVENT SHALL REGENTS BE LIABLE TO ANY PARTY FOR DIRECT, * INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, * INCLUDING LOST PROFITS, ARISING OUT OF THE USE OF THIS SOFTWARE * AND ITS DOCUMENTATION, EVEN IF REGENTS HAS BEEN ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * REGENTS SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE AND FURTHER DISCLAIMS ANY STATUTORY * WARRANTY OF NON-INFRINGEMENT. THE SOFTWARE AND ACCOMPANYING * DOCUMENTATION, IF ANY, PROVIDED HEREUNDER IS PROVIDED "AS * IS". REGENTS HAS NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, * UPDATES, ENHANCEMENTS, OR MODIFICATIONS. */ package com.ibm.wala.demandpa.alg.refinepolicy; /** * A complete refinement policy for a points-to analysis. Specifies a {@link FieldRefinePolicy}, a * {@link CallGraphRefinePolicy}, and budgets for analysis passes. * * @author Manu Sridharan */ public interface RefinementPolicy { /** @return the maximum number of refinement iterations for the query */ int getNumPasses(); /** @return the maximum number of nodes to traverse in pass {@code passNum} */ int getBudgetForPass(int passNum); /** @return the field refinement policy */ FieldRefinePolicy getFieldRefinePolicy(); /** @return the call graph refinement policy */ CallGraphRefinePolicy getCallGraphRefinePolicy(); /** * @return {@code true} if more refinement can be done, and hence another pass can be attempted; * {@code false} otherwise */ boolean nextPass(); }
2,785
41.212121
98
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/demandpa/alg/refinepolicy/RefinementPolicyFactory.java
/* * This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html. * * This file is a derivative of code released by the University of * California under the terms listed below. * * Refinement Analysis Tools is Copyright (c) 2007 The Regents of the * University of California (Regents). Provided that this notice and * the following two paragraphs are included in any distribution of * Refinement Analysis Tools or its derivative work, Regents agrees * not to assert any of Regents' copyright rights in Refinement * Analysis Tools against recipient for recipient's reproduction, * preparation of derivative works, public display, public * performance, distribution or sublicensing of Refinement Analysis * Tools and derivative works, in source code and object code form. * This agreement not to assert does not confer, by implication, * estoppel, or otherwise any license or rights in any intellectual * property of Regents, including, but not limited to, any patents * of Regents or Regents' employees. * * IN NO EVENT SHALL REGENTS BE LIABLE TO ANY PARTY FOR DIRECT, * INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, * INCLUDING LOST PROFITS, ARISING OUT OF THE USE OF THIS SOFTWARE * AND ITS DOCUMENTATION, EVEN IF REGENTS HAS BEEN ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * REGENTS SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE AND FURTHER DISCLAIMS ANY STATUTORY * WARRANTY OF NON-INFRINGEMENT. THE SOFTWARE AND ACCOMPANYING * DOCUMENTATION, IF ANY, PROVIDED HEREUNDER IS PROVIDED "AS * IS". REGENTS HAS NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, * UPDATES, ENHANCEMENTS, OR MODIFICATIONS. */ package com.ibm.wala.demandpa.alg.refinepolicy; public interface RefinementPolicyFactory { RefinementPolicy make(); }
2,040
45.386364
72
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/demandpa/alg/refinepolicy/SinglePassRefinementPolicy.java
/* * This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html. * * This file is a derivative of code released by the University of * California under the terms listed below. * * Refinement Analysis Tools is Copyright (c) 2007 The Regents of the * University of California (Regents). Provided that this notice and * the following two paragraphs are included in any distribution of * Refinement Analysis Tools or its derivative work, Regents agrees * not to assert any of Regents' copyright rights in Refinement * Analysis Tools against recipient for recipient's reproduction, * preparation of derivative works, public display, public * performance, distribution or sublicensing of Refinement Analysis * Tools and derivative works, in source code and object code form. * This agreement not to assert does not confer, by implication, * estoppel, or otherwise any license or rights in any intellectual * property of Regents, including, but not limited to, any patents * of Regents or Regents' employees. * * IN NO EVENT SHALL REGENTS BE LIABLE TO ANY PARTY FOR DIRECT, * INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, * INCLUDING LOST PROFITS, ARISING OUT OF THE USE OF THIS SOFTWARE * AND ITS DOCUMENTATION, EVEN IF REGENTS HAS BEEN ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * REGENTS SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE AND FURTHER DISCLAIMS ANY STATUTORY * WARRANTY OF NON-INFRINGEMENT. THE SOFTWARE AND ACCOMPANYING * DOCUMENTATION, IF ANY, PROVIDED HEREUNDER IS PROVIDED "AS * IS". REGENTS HAS NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, * UPDATES, ENHANCEMENTS, OR MODIFICATIONS. */ package com.ibm.wala.demandpa.alg.refinepolicy; /** * A policy for performing a single analysis pass, i.e., with no refinement. * * @author Manu Sridharan */ public class SinglePassRefinementPolicy extends AbstractRefinementPolicy { private SinglePassRefinementPolicy( FieldRefinePolicy fieldRefinePolicy, CallGraphRefinePolicy cgRefinePolicy, int budget) { super(fieldRefinePolicy, cgRefinePolicy, 1, new int[] {budget}); } @Override public boolean nextPass() { return false; } public static class Factory implements RefinementPolicyFactory { private final FieldRefinePolicy fieldRefinePolicy; private final CallGraphRefinePolicy cgRefinePolicy; private final int budget; public Factory(FieldRefinePolicy fieldRefinePolicy, CallGraphRefinePolicy cgRefinePolicy) { this(fieldRefinePolicy, cgRefinePolicy, Integer.MAX_VALUE); } public Factory( FieldRefinePolicy fieldRefinePolicy, CallGraphRefinePolicy cgRefinePolicy, int budget) { this.fieldRefinePolicy = fieldRefinePolicy; this.cgRefinePolicy = cgRefinePolicy; this.budget = budget; } @Override public RefinementPolicy make() { return new SinglePassRefinementPolicy(fieldRefinePolicy, cgRefinePolicy, budget); } } }
3,207
38.121951
96
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/demandpa/alg/refinepolicy/TunedFieldRefinementPolicy.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.demandpa.alg.refinepolicy; import com.ibm.wala.classLoader.IClass; import com.ibm.wala.classLoader.IField; import com.ibm.wala.demandpa.alg.statemachine.StateMachine; import com.ibm.wala.demandpa.flowgraph.IFlowLabel; import com.ibm.wala.demandpa.util.ArrayContents; import com.ibm.wala.ipa.callgraph.propagation.PointerKey; import com.ibm.wala.ipa.cha.IClassHierarchy; import com.ibm.wala.types.ClassLoaderReference; import com.ibm.wala.types.TypeReference; import com.ibm.wala.util.collections.HashSetFactory; import java.util.Collection; public class TunedFieldRefinementPolicy implements FieldRefinePolicy { private static final boolean DEBUG = false; private final IClassHierarchy cha; private final Collection<IClass> typesToRefine = HashSetFactory.make(); private IClass firstSkippedClass = null; @Override public boolean nextPass() { if (firstSkippedClass != null) { typesToRefine.add(firstSkippedClass); if (DEBUG) { System.err.println("now refining " + firstSkippedClass); } firstSkippedClass = null; return true; } else { return false; } } @Override public boolean shouldRefine( IField field, PointerKey basePtr, PointerKey val, IFlowLabel label, StateMachine.State state) { if (field == null) { throw new IllegalArgumentException("null field"); } if (field == ArrayContents.v()) { return true; } IClass classToCheck = removeInner(field.getDeclaringClass()); if (superOfAnyEncountered(classToCheck)) { return true; } else { if (firstSkippedClass == null) { firstSkippedClass = classToCheck; } return false; } } private boolean superOfAnyEncountered(IClass klass) { for (IClass toRefine : typesToRefine) { if (cha.isAssignableFrom(klass, toRefine) || cha.isAssignableFrom(toRefine, klass)) { return true; } } return false; } /** * @return the top-level {@link IClass} where klass is declared, or klass itself if klass is * top-level or if top-level class not loaded */ private IClass removeInner(IClass klass) { ClassLoaderReference cl = klass.getClassLoader().getReference(); String klassStr = klass.getName().toString(); int dollarIndex = klassStr.indexOf('$'); if (dollarIndex == -1) { return klass; } else { String topMostName = klassStr.substring(0, dollarIndex); IClass topMostClass = cha.lookupClass(TypeReference.findOrCreate(cl, topMostName)); return (topMostClass != null) ? topMostClass : klass; } } public TunedFieldRefinementPolicy(IClassHierarchy cha) { this.cha = cha; } }
3,091
29.019417
94
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/demandpa/alg/refinepolicy/TunedRefinementPolicy.java
/* * This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html. * * This file is a derivative of code released by the University of * California under the terms listed below. * * Refinement Analysis Tools is Copyright (c) 2007 The Regents of the * University of California (Regents). Provided that this notice and * the following two paragraphs are included in any distribution of * Refinement Analysis Tools or its derivative work, Regents agrees * not to assert any of Regents' copyright rights in Refinement * Analysis Tools against recipient for recipient's reproduction, * preparation of derivative works, public display, public * performance, distribution or sublicensing of Refinement Analysis * Tools and derivative works, in source code and object code form. * This agreement not to assert does not confer, by implication, * estoppel, or otherwise any license or rights in any intellectual * property of Regents, including, but not limited to, any patents * of Regents or Regents' employees. * * IN NO EVENT SHALL REGENTS BE LIABLE TO ANY PARTY FOR DIRECT, * INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, * INCLUDING LOST PROFITS, ARISING OUT OF THE USE OF THIS SOFTWARE * AND ITS DOCUMENTATION, EVEN IF REGENTS HAS BEEN ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * REGENTS SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE AND FURTHER DISCLAIMS ANY STATUTORY * WARRANTY OF NON-INFRINGEMENT. THE SOFTWARE AND ACCOMPANYING * DOCUMENTATION, IF ANY, PROVIDED HEREUNDER IS PROVIDED "AS * IS". REGENTS HAS NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, * UPDATES, ENHANCEMENTS, OR MODIFICATIONS. */ package com.ibm.wala.demandpa.alg.refinepolicy; import com.ibm.wala.ipa.cha.IClassHierarchy; /** * A refinement policy that iteratively adds more types to refine, based on which type was * encountered first in each analysis pass. * * @author Manu Sridharan */ public class TunedRefinementPolicy extends AbstractRefinementPolicy { public TunedRefinementPolicy(IClassHierarchy cha) { super(new TunedFieldRefinementPolicy(cha), new AlwaysRefineCGPolicy()); } public static class Factory implements RefinementPolicyFactory { private final IClassHierarchy cha; public Factory(IClassHierarchy cha) { this.cha = cha; } @Override public RefinementPolicy make() { return new TunedRefinementPolicy(cha); } } }
2,678
38.397059
90
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/demandpa/alg/statemachine/DummyStateMachine.java
/* * This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html. * * This file is a derivative of code released by the University of * California under the terms listed below. * * Refinement Analysis Tools is Copyright (c) 2007 The Regents of the * University of California (Regents). Provided that this notice and * the following two paragraphs are included in any distribution of * Refinement Analysis Tools or its derivative work, Regents agrees * not to assert any of Regents' copyright rights in Refinement * Analysis Tools against recipient for recipient's reproduction, * preparation of derivative works, public display, public * performance, distribution or sublicensing of Refinement Analysis * Tools and derivative works, in source code and object code form. * This agreement not to assert does not confer, by implication, * estoppel, or otherwise any license or rights in any intellectual * property of Regents, including, but not limited to, any patents * of Regents or Regents' employees. * * IN NO EVENT SHALL REGENTS BE LIABLE TO ANY PARTY FOR DIRECT, * INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, * INCLUDING LOST PROFITS, ARISING OUT OF THE USE OF THIS SOFTWARE * AND ITS DOCUMENTATION, EVEN IF REGENTS HAS BEEN ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * REGENTS SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE AND FURTHER DISCLAIMS ANY STATUTORY * WARRANTY OF NON-INFRINGEMENT. THE SOFTWARE AND ACCOMPANYING * DOCUMENTATION, IF ANY, PROVIDED HEREUNDER IS PROVIDED "AS * IS". REGENTS HAS NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, * UPDATES, ENHANCEMENTS, OR MODIFICATIONS. */ package com.ibm.wala.demandpa.alg.statemachine; /** * A dummy state machine with a single, non-error state. Primarily for testing purposes. * * @author Manu Sridharan */ public class DummyStateMachine<T> implements StateMachine<T> { public static class Factory<T> implements StateMachineFactory<T> { @Override public StateMachine<T> make() { return new DummyStateMachine<>(); } } private static final State DUMMY = new State() { @Override public String toString() { return "DUMMY"; } }; /* * (non-Javadoc) * * @see statemachine.StateMachine#transition(int, java.lang.Object) */ @Override public State transition(State prevState, T label) { return DUMMY; } @Override public State getStartState() { return DUMMY; } private DummyStateMachine() {} }
2,781
33.775
88
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/demandpa/alg/statemachine/StateMachine.java
/* * This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html. * * This file is a derivative of code released by the University of * California under the terms listed below. * * Refinement Analysis Tools is Copyright (c) 2007 The Regents of the * University of California (Regents). Provided that this notice and * the following two paragraphs are included in any distribution of * Refinement Analysis Tools or its derivative work, Regents agrees * not to assert any of Regents' copyright rights in Refinement * Analysis Tools against recipient for recipient's reproduction, * preparation of derivative works, public display, public * performance, distribution or sublicensing of Refinement Analysis * Tools and derivative works, in source code and object code form. * This agreement not to assert does not confer, by implication, * estoppel, or otherwise any license or rights in any intellectual * property of Regents, including, but not limited to, any patents * of Regents or Regents' employees. * * IN NO EVENT SHALL REGENTS BE LIABLE TO ANY PARTY FOR DIRECT, * INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, * INCLUDING LOST PROFITS, ARISING OUT OF THE USE OF THIS SOFTWARE * AND ITS DOCUMENTATION, EVEN IF REGENTS HAS BEEN ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * REGENTS SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE AND FURTHER DISCLAIMS ANY STATUTORY * WARRANTY OF NON-INFRINGEMENT. THE SOFTWARE AND ACCOMPANYING * DOCUMENTATION, IF ANY, PROVIDED HEREUNDER IS PROVIDED "AS * IS". REGENTS HAS NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, * UPDATES, ENHANCEMENTS, OR MODIFICATIONS. */ package com.ibm.wala.demandpa.alg.statemachine; /** * A state machine with an error state. Non-error states must be represented externally as natural * numbers. * * @author Manu Sridharan */ public interface StateMachine<T> { interface State {} State ERROR = new State() {}; State getStartState(); /** * @return the successor state of prevState for the transition labelled label, or {@code null} if * no such transition exists * @throws StatesMergedException if merging of states is detected * @see StatesMergedException */ State transition(State prevState, T label); }
2,527
39.774194
99
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/demandpa/alg/statemachine/StateMachineFactory.java
/* * This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html. * * This file is a derivative of code released by the University of * California under the terms listed below. * * Refinement Analysis Tools is Copyright (c) 2007 The Regents of the * University of California (Regents). Provided that this notice and * the following two paragraphs are included in any distribution of * Refinement Analysis Tools or its derivative work, Regents agrees * not to assert any of Regents' copyright rights in Refinement * Analysis Tools against recipient for recipient's reproduction, * preparation of derivative works, public display, public * performance, distribution or sublicensing of Refinement Analysis * Tools and derivative works, in source code and object code form. * This agreement not to assert does not confer, by implication, * estoppel, or otherwise any license or rights in any intellectual * property of Regents, including, but not limited to, any patents * of Regents or Regents' employees. * * IN NO EVENT SHALL REGENTS BE LIABLE TO ANY PARTY FOR DIRECT, * INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, * INCLUDING LOST PROFITS, ARISING OUT OF THE USE OF THIS SOFTWARE * AND ITS DOCUMENTATION, EVEN IF REGENTS HAS BEEN ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * REGENTS SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE AND FURTHER DISCLAIMS ANY STATUTORY * WARRANTY OF NON-INFRINGEMENT. THE SOFTWARE AND ACCOMPANYING * DOCUMENTATION, IF ANY, PROVIDED HEREUNDER IS PROVIDED "AS * IS". REGENTS HAS NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, * UPDATES, ENHANCEMENTS, OR MODIFICATIONS. */ package com.ibm.wala.demandpa.alg.statemachine; public interface StateMachineFactory<T> { StateMachine<T> make(); }
2,038
45.340909
72
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/demandpa/alg/statemachine/StatesMergedException.java
/* * This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html. * * This file is a derivative of code released by the University of * California under the terms listed below. * * Refinement Analysis Tools is Copyright (c) 2007 The Regents of the * University of California (Regents). Provided that this notice and * the following two paragraphs are included in any distribution of * Refinement Analysis Tools or its derivative work, Regents agrees * not to assert any of Regents' copyright rights in Refinement * Analysis Tools against recipient for recipient's reproduction, * preparation of derivative works, public display, public * performance, distribution or sublicensing of Refinement Analysis * Tools and derivative works, in source code and object code form. * This agreement not to assert does not confer, by implication, * estoppel, or otherwise any license or rights in any intellectual * property of Regents, including, but not limited to, any patents * of Regents or Regents' employees. * * IN NO EVENT SHALL REGENTS BE LIABLE TO ANY PARTY FOR DIRECT, * INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, * INCLUDING LOST PROFITS, ARISING OUT OF THE USE OF THIS SOFTWARE * AND ITS DOCUMENTATION, EVEN IF REGENTS HAS BEEN ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * REGENTS SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE AND FURTHER DISCLAIMS ANY STATUTORY * WARRANTY OF NON-INFRINGEMENT. THE SOFTWARE AND ACCOMPANYING * DOCUMENTATION, IF ANY, PROVIDED HEREUNDER IS PROVIDED "AS * IS". REGENTS HAS NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, * UPDATES, ENHANCEMENTS, OR MODIFICATIONS. */ package com.ibm.wala.demandpa.alg.statemachine; /** * Exception thrown when a state machine needs to merge states and treat them as equivalent. For * example, a state machine for context sensitivity may throw this exception in its {@link * StateMachine#transition(com.ibm.wala.demandpa.alg.statemachine.StateMachine.State, Object)} * method when recursive method calls are detected. * * @author Manu Sridharan */ public class StatesMergedException extends RuntimeException { private static final long serialVersionUID = 7769961571949421524L; }
2,473
46.576923
96
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/demandpa/flowgraph/AbstractDemandFlowGraph.java
/* * This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html. * * This file is a derivative of code released by the University of * California under the terms listed below. * * Refinement Analysis Tools is Copyright (c) 2007 The Regents of the * University of California (Regents). Provided that this notice and * the following two paragraphs are included in any distribution of * Refinement Analysis Tools or its derivative work, Regents agrees * not to assert any of Regents' copyright rights in Refinement * Analysis Tools against recipient for recipient's reproduction, * preparation of derivative works, public display, public * performance, distribution or sublicensing of Refinement Analysis * Tools and derivative works, in source code and object code form. * This agreement not to assert does not confer, by implication, * estoppel, or otherwise any license or rights in any intellectual * property of Regents, including, but not limited to, any patents * of Regents or Regents' employees. * * IN NO EVENT SHALL REGENTS BE LIABLE TO ANY PARTY FOR DIRECT, * INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, * INCLUDING LOST PROFITS, ARISING OUT OF THE USE OF THIS SOFTWARE * AND ITS DOCUMENTATION, EVEN IF REGENTS HAS BEEN ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * REGENTS SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE AND FURTHER DISCLAIMS ANY STATUTORY * WARRANTY OF NON-INFRINGEMENT. THE SOFTWARE AND ACCOMPANYING * DOCUMENTATION, IF ANY, PROVIDED HEREUNDER IS PROVIDED "AS * IS". REGENTS HAS NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, * UPDATES, ENHANCEMENTS, OR MODIFICATIONS. */ package com.ibm.wala.demandpa.flowgraph; import com.ibm.wala.cfg.ControlFlowGraph; import com.ibm.wala.classLoader.CallSiteReference; import com.ibm.wala.core.util.ref.ReferenceCleanser; import com.ibm.wala.demandpa.util.MemoryAccessMap; import com.ibm.wala.ipa.callgraph.CGNode; import com.ibm.wala.ipa.callgraph.CallGraph; import com.ibm.wala.ipa.callgraph.propagation.HeapModel; import com.ibm.wala.ipa.callgraph.propagation.LocalPointerKey; import com.ibm.wala.ipa.callgraph.propagation.PointerKey; import com.ibm.wala.ipa.callgraph.propagation.ReturnValueKey; import com.ibm.wala.ipa.callgraph.propagation.SSAPropagationCallGraphBuilder; import com.ibm.wala.ipa.callgraph.propagation.cfa.CallerSiteContext; import com.ibm.wala.ipa.cha.IClassHierarchy; import com.ibm.wala.ssa.IR; import com.ibm.wala.ssa.ISSABasicBlock; import com.ibm.wala.ssa.SSAAbstractInvokeInstruction; import com.ibm.wala.ssa.SSAInstruction; import com.ibm.wala.ssa.SSAPhiInstruction; import com.ibm.wala.util.collections.EmptyIterator; import com.ibm.wala.util.collections.HashMapFactory; import com.ibm.wala.util.collections.HashSetFactory; import com.ibm.wala.util.collections.Iterator2Iterable; import com.ibm.wala.util.intset.BitVectorIntSet; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import java.util.Map; import java.util.Set; /** A graph representing program flow, constructed method-by-method on demand */ public abstract class AbstractDemandFlowGraph extends AbstractFlowGraph { /** */ private static final long serialVersionUID = 1L; private static final boolean DEBUG = false; /** Counter for wiping soft caches */ private static int wipeCount = 0; /** node numbers of CGNodes we have already visited */ final BitVectorIntSet cgNodesVisited = new BitVectorIntSet(); /** * @see * com.ibm.wala.demandpa.flowgraph.IFlowGraph#addSubgraphForNode(com.ibm.wala.ipa.callgraph.CGNode) */ @Override public void addSubgraphForNode(CGNode node) throws IllegalArgumentException { if (node == null) { throw new IllegalArgumentException("node == null"); } IR ir = node.getIR(); if (ir == null) { throw new IllegalArgumentException("no ir for node " + node); } int n = cg.getNumber(node); if (!cgNodesVisited.contains(n)) { cgNodesVisited.add(n); unconditionallyAddConstraintsFromNode(node, ir); addNodesForInvocations(node, ir); addNodesForParameters(node, ir); } } /** * @see * com.ibm.wala.demandpa.flowgraph.IFlowGraph#hasSubgraphForNode(com.ibm.wala.ipa.callgraph.CGNode) */ @Override public boolean hasSubgraphForNode(CGNode node) { return cgNodesVisited.contains(cg.getNumber(node)); } /** @see com.ibm.wala.demandpa.flowgraph.IFlowGraph#getInstrsPassingParam(LocalPointerKey) */ public Iterator<PointerKeyAndCallSite> getParamSuccs(LocalPointerKey pk) { // TODO cache this result // TODO take some cgnode as parameter if we have calling context? CGNode cgNode = params.get(pk); if (cgNode == null) { return EmptyIterator.instance(); } int paramPos = pk.getValueNumber() - 1; ArrayList<PointerKeyAndCallSite> paramSuccs = new ArrayList<>(); // iterate over callers for (CGNode caller : cg) { // TODO optimization: we don't need to add the graph if null is passed // as the argument addSubgraphForNode(caller); IR ir = caller.getIR(); for (CallSiteReference call : Iterator2Iterable.make(ir.iterateCallSites())) { if (cg.getPossibleTargets(caller, call).contains(cgNode)) { SSAAbstractInvokeInstruction[] callInstrs = ir.getCalls(call); for (SSAAbstractInvokeInstruction callInstr : callInstrs) { PointerKey actualPk = heapModel.getPointerKeyForLocal(caller, callInstr.getUse(paramPos)); assert containsNode(actualPk); assert containsNode(pk); paramSuccs.add(new PointerKeyAndCallSite(actualPk, call)); } } } } return paramSuccs.iterator(); } /** @see com.ibm.wala.demandpa.flowgraph.IFlowGraph#getInstrsPassingParam(LocalPointerKey) */ public Iterator<PointerKeyAndCallSite> getParamPreds(LocalPointerKey pk) { // TODO Set<SSAAbstractInvokeInstruction> instrs = callParams.get(pk); if (instrs == null) { return EmptyIterator.instance(); } ArrayList<PointerKeyAndCallSite> paramPreds = new ArrayList<>(); for (SSAAbstractInvokeInstruction callInstr : instrs) { for (int i = 0; i < callInstr.getNumberOfUses(); i++) { if (pk.getValueNumber() != callInstr.getUse(i)) continue; CallSiteReference callSiteRef = callInstr.getCallSite(); // get call targets Collection<CGNode> possibleCallees = cg.getPossibleTargets(pk.getNode(), callSiteRef); // construct graph for each target for (CGNode callee : possibleCallees) { addSubgraphForNode(callee); // TODO test this!!! // TODO test passing null as an argument PointerKey paramVal = heapModel.getPointerKeyForLocal(callee, i + 1); assert containsNode(paramVal); paramPreds.add(new PointerKeyAndCallSite(paramVal, callSiteRef)); } } } return paramPreds.iterator(); } /** @see com.ibm.wala.demandpa.flowgraph.IFlowGraph#getInstrReturningTo(LocalPointerKey) */ public Iterator<PointerKeyAndCallSite> getReturnSuccs(LocalPointerKey pk) { SSAAbstractInvokeInstruction callInstr = callDefs.get(pk); if (callInstr == null) return EmptyIterator.instance(); ArrayList<PointerKeyAndCallSite> returnSuccs = new ArrayList<>(); boolean isExceptional = pk.getValueNumber() == callInstr.getException(); CallSiteReference callSiteRef = callInstr.getCallSite(); // get call targets Collection<CGNode> possibleCallees = cg.getPossibleTargets(pk.getNode(), callSiteRef); // construct graph for each target for (CGNode callee : possibleCallees) { addSubgraphForNode(callee); PointerKey retVal = isExceptional ? heapModel.getPointerKeyForExceptionalReturnValue(callee) : heapModel.getPointerKeyForReturnValue(callee); assert containsNode(retVal); returnSuccs.add(new PointerKeyAndCallSite(retVal, callSiteRef)); } return returnSuccs.iterator(); } /** @see com.ibm.wala.demandpa.flowgraph.IFlowGraph#getInstrReturningTo(LocalPointerKey) */ public Iterator<PointerKeyAndCallSite> getReturnPreds(LocalPointerKey pk) { CGNode cgNode = returns.get(pk); if (cgNode == null) { return EmptyIterator.instance(); } boolean isExceptional = pk == heapModel.getPointerKeyForExceptionalReturnValue(cgNode); ArrayList<PointerKeyAndCallSite> returnPreds = new ArrayList<>(); // iterate over callers for (CGNode caller : cg) { // TODO we don't need to add the graph if null is passed // as the argument addSubgraphForNode(caller); IR ir = caller.getIR(); for (CallSiteReference call : Iterator2Iterable.make(ir.iterateCallSites())) { if (cg.getPossibleTargets(caller, call).contains(cgNode)) { SSAAbstractInvokeInstruction[] callInstrs = ir.getCalls(call); for (SSAAbstractInvokeInstruction callInstr : callInstrs) { PointerKey returnPk = heapModel.getPointerKeyForLocal( caller, isExceptional ? callInstr.getException() : callInstr.getDef()); assert containsNode(returnPk); assert containsNode(pk); returnPreds.add(new PointerKeyAndCallSite(returnPk, call)); } } } } return returnPreds.iterator(); } protected abstract void addNodesForParameters(CGNode node, IR ir); protected void unconditionallyAddConstraintsFromNode(CGNode node, IR ir) { if (DEBUG) { System.err.println(("Adding constraints for CGNode " + node)); } if (SSAPropagationCallGraphBuilder.PERIODIC_WIPE_SOFT_CACHES) { wipeCount++; if (wipeCount >= SSAPropagationCallGraphBuilder.WIPE_SOFT_CACHE_INTERVAL) { wipeCount = 0; ReferenceCleanser.clearSoftCaches(); } } debugPrintIR(ir); if (ir == null) { return; } addNodeInstructionConstraints(node, ir); addNodePassthruExceptionConstraints(node, ir); addNodeConstantConstraints(node, ir); } /** Add pointer flow constraints based on instructions in a given node */ protected void addNodeInstructionConstraints(CGNode node, IR ir) { FlowStatementVisitor v = makeVisitor(node); ControlFlowGraph<SSAInstruction, ISSABasicBlock> cfg = ir.getControlFlowGraph(); for (ISSABasicBlock b : cfg) { addBlockInstructionConstraints(node, cfg, b, v); } } /** Add constraints for a particular basic block. */ protected void addBlockInstructionConstraints( CGNode node, ControlFlowGraph<SSAInstruction, ISSABasicBlock> cfg, ISSABasicBlock b, FlowStatementVisitor v) { v.setBasicBlock(b); // visit each instruction in the basic block. for (SSAInstruction s : b) { if (s != null) { s.visit(v); } } addPhiConstraints(node, cfg, b); } private void addPhiConstraints( CGNode node, ControlFlowGraph<SSAInstruction, ISSABasicBlock> cfg, ISSABasicBlock b) { // visit each phi instruction in each successor block for (ISSABasicBlock sb : Iterator2Iterable.make(cfg.getSuccNodes(b))) { if (sb.isExitBlock()) { // an optimization based on invariant that exit blocks should // have no // phis. continue; } int n = 0; // set n to be whichPred(this, sb); for (ISSABasicBlock back : Iterator2Iterable.make(cfg.getPredNodes(sb))) { if (back == b) { break; } ++n; } assert n < cfg.getPredNodeCount(sb); for (SSAPhiInstruction phi : Iterator2Iterable.make(sb.iteratePhis())) { // Assertions.UNREACHABLE(); if (phi == null) { continue; } PointerKey def = heapModel.getPointerKeyForLocal(node, phi.getDef()); if (phi.getUse(n) > 0) { PointerKey use = heapModel.getPointerKeyForLocal(node, phi.getUse(n)); addNode(def); addNode(use); addEdge(def, use, AssignLabel.noFilter()); } // } // } } } } protected abstract FlowStatementVisitor makeVisitor(CGNode node); private static void debugPrintIR(IR ir) { if (DEBUG) { if (ir == null) { System.err.println("\n No statements\n"); } else { try { System.err.println(ir); } catch (Error e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } final Map<CGNode, Set<CallerSiteContext>> callerCache = HashMapFactory.make(); @Override public Set<CallerSiteContext> getPotentialCallers(PointerKey formalPk) { CGNode callee = null; if (formalPk instanceof LocalPointerKey) { callee = ((LocalPointerKey) formalPk).getNode(); } else if (formalPk instanceof ReturnValueKey) { callee = ((ReturnValueKey) formalPk).getNode(); } else { throw new IllegalArgumentException("formalPk must represent a local"); } Set<CallerSiteContext> ret = callerCache.get(callee); if (ret == null) { ret = HashSetFactory.make(); for (CGNode caller : Iterator2Iterable.make(cg.getPredNodes(callee))) { for (CallSiteReference call : Iterator2Iterable.make(cg.getPossibleSites(caller, callee))) { ret.add(new CallerSiteContext(caller, call)); } } callerCache.put(callee, ret); } return ret; } @Override public Set<CGNode> getPossibleTargets( CGNode node, CallSiteReference site, LocalPointerKey actualPk) { return cg.getPossibleTargets(node, site); } protected interface FlowStatementVisitor extends SSAInstruction.IVisitor { void setBasicBlock(ISSABasicBlock b); } public AbstractDemandFlowGraph( final CallGraph cg, final HeapModel heapModel, final MemoryAccessMap mam, final IClassHierarchy cha) { super(mam, heapModel, cha, cg); } }
14,252
36.507895
105
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/demandpa/flowgraph/AbstractFlowGraph.java
/* * This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html. * * This file is a derivative of code released by the University of * California under the terms listed below. * * Refinement Analysis Tools is Copyright (c) 2007 The Regents of the * University of California (Regents). Provided that this notice and * the following two paragraphs are included in any distribution of * Refinement Analysis Tools or its derivative work, Regents agrees * not to assert any of Regents' copyright rights in Refinement * Analysis Tools against recipient for recipient's reproduction, * preparation of derivative works, public display, public * performance, distribution or sublicensing of Refinement Analysis * Tools and derivative works, in source code and object code form. * This agreement not to assert does not confer, by implication, * estoppel, or otherwise any license or rights in any intellectual * property of Regents, including, but not limited to, any patents * of Regents or Regents' employees. * * IN NO EVENT SHALL REGENTS BE LIABLE TO ANY PARTY FOR DIRECT, * INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, * INCLUDING LOST PROFITS, ARISING OUT OF THE USE OF THIS SOFTWARE * AND ITS DOCUMENTATION, EVEN IF REGENTS HAS BEEN ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * REGENTS SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE AND FURTHER DISCLAIMS ANY STATUTORY * WARRANTY OF NON-INFRINGEMENT. THE SOFTWARE AND ACCOMPANYING * DOCUMENTATION, IF ANY, PROVIDED HEREUNDER IS PROVIDED "AS * IS". REGENTS HAS NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, * UPDATES, ENHANCEMENTS, OR MODIFICATIONS. */ package com.ibm.wala.demandpa.flowgraph; import com.ibm.wala.classLoader.CallSiteReference; import com.ibm.wala.classLoader.IClass; import com.ibm.wala.classLoader.IField; import com.ibm.wala.classLoader.ProgramCounter; import com.ibm.wala.demandpa.flowgraph.DemandPointerFlowGraph.NewMultiDimInfo; import com.ibm.wala.demandpa.flowgraph.IFlowLabel.IFlowLabelVisitor; import com.ibm.wala.demandpa.util.ArrayContents; import com.ibm.wala.demandpa.util.MemoryAccess; import com.ibm.wala.demandpa.util.MemoryAccessMap; import com.ibm.wala.ipa.callgraph.CGNode; import com.ibm.wala.ipa.callgraph.CallGraph; import com.ibm.wala.ipa.callgraph.propagation.ArrayContentsKey; import com.ibm.wala.ipa.callgraph.propagation.ConcreteTypeKey; import com.ibm.wala.ipa.callgraph.propagation.HeapModel; import com.ibm.wala.ipa.callgraph.propagation.InstanceKey; import com.ibm.wala.ipa.callgraph.propagation.LocalPointerKey; import com.ibm.wala.ipa.callgraph.propagation.NormalAllocationInNode; import com.ibm.wala.ipa.callgraph.propagation.PointerKey; import com.ibm.wala.ipa.callgraph.propagation.PropagationCallGraphBuilder; import com.ibm.wala.ipa.callgraph.propagation.ReturnValueKey; import com.ibm.wala.ipa.callgraph.propagation.SSAPropagationCallGraphBuilder; import com.ibm.wala.ipa.callgraph.propagation.StaticFieldKey; import com.ibm.wala.ipa.cha.IClassHierarchy; import com.ibm.wala.ssa.IR; import com.ibm.wala.ssa.SSAAbstractInvokeInstruction; import com.ibm.wala.ssa.SSAAbstractThrowInstruction; import com.ibm.wala.ssa.SSAArrayLoadInstruction; import com.ibm.wala.ssa.SSAArrayStoreInstruction; import com.ibm.wala.ssa.SSAGetInstruction; import com.ibm.wala.ssa.SSAInstruction; import com.ibm.wala.ssa.SSAInvokeInstruction; import com.ibm.wala.ssa.SSANewInstruction; import com.ibm.wala.ssa.SSAPutInstruction; import com.ibm.wala.ssa.SymbolTable; import com.ibm.wala.types.TypeReference; import com.ibm.wala.util.collections.EmptyIterator; import com.ibm.wala.util.collections.HashMapFactory; import com.ibm.wala.util.collections.Iterator2Iterable; import com.ibm.wala.util.collections.MapUtil; import com.ibm.wala.util.collections.Pair; import com.ibm.wala.util.debug.Assertions; import com.ibm.wala.util.graph.labeled.SlowSparseNumberedLabeledGraph; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; /** * A graph whose edges are labeled with {@link IFlowLabel}s. * * @author Manu Sridharan */ public abstract class AbstractFlowGraph extends SlowSparseNumberedLabeledGraph<Object, IFlowLabel> implements IFlowGraph { /** */ private static final long serialVersionUID = 1L; private static final IFlowLabel defaultLabel = new IFlowLabel() { @Override public IFlowLabel bar() { return defaultLabel; } @Override public boolean isBarred() { return false; } @Override public void visit(IFlowLabelVisitor v, Object dst) {} }; /** * Map: LocalPointerKey -&gt; SSAInvokeInstruction. If we have (x, foo()), that means that x was * def'fed by the return value from the call to foo() */ protected final Map<PointerKey, SSAAbstractInvokeInstruction> callDefs = HashMapFactory.make(); /** * Map: {@link LocalPointerKey} -&gt; {@link Set}&lt;{@link SSAInvokeInstruction}&gt;. If we have * (x, foo()), that means x was passed as a parameter to the call to foo(). The parameter position * is not represented and must be recovered. */ protected final Map<PointerKey, Set<SSAAbstractInvokeInstruction>> callParams = HashMapFactory.make(); /** * Map: LocalPointerKey -&gt; CGNode. If we have (x, foo), then x is a parameter of method foo. * For now, we have to re-discover the parameter position. TODO this should just be a set; we can * get the CGNode from the {@link LocalPointerKey} */ protected final Map<PointerKey, CGNode> params = HashMapFactory.make(); /** * Map: {@link LocalPointerKey} -&gt; {@link CGNode}. If we have (x, foo), then x is a return * value of method foo. Must re-discover if x is normal or exceptional return value. */ protected final Map<PointerKey, CGNode> returns = HashMapFactory.make(); protected final MemoryAccessMap mam; protected final HeapModel heapModel; protected final IClassHierarchy cha; protected final CallGraph cg; public AbstractFlowGraph( MemoryAccessMap mam, HeapModel heapModel, IClassHierarchy cha, CallGraph cg) { super(defaultLabel); this.mam = mam; this.heapModel = heapModel; this.cha = cha; this.cg = cg; } @Override public void visitSuccs(Object node, IFlowLabelVisitor v) { for (final IFlowLabel label : Iterator2Iterable.make(getSuccLabels(node))) { for (Object succNode : Iterator2Iterable.make(getSuccNodes(node, label))) { label.visit(v, succNode); } } } @Override public void visitPreds(Object node, IFlowLabelVisitor v) { for (final IFlowLabel label : Iterator2Iterable.make(getPredLabels(node))) { for (Object predNode : Iterator2Iterable.make(getPredNodes(node, label))) { label.visit(v, predNode); } } } /** For each invocation in the method, add nodes for actual parameters and return values */ protected void addNodesForInvocations(CGNode node, IR ir) { for (CallSiteReference site : Iterator2Iterable.make(ir.iterateCallSites())) { SSAAbstractInvokeInstruction[] calls = ir.getCalls(site); for (SSAAbstractInvokeInstruction invokeInstr : calls) { for (int i = 0; i < invokeInstr.getNumberOfUses(); i++) { // just make nodes for parameters; we'll get to them when // traversing // from the callee PointerKey use = heapModel.getPointerKeyForLocal(node, invokeInstr.getUse(i)); addNode(use); Set<SSAAbstractInvokeInstruction> s = MapUtil.findOrCreateSet(callParams, use); s.add(invokeInstr); } // for any def'd values, keep track of the fact that they are def'd // by a call if (invokeInstr.hasDef()) { PointerKey def = heapModel.getPointerKeyForLocal(node, invokeInstr.getDef()); addNode(def); callDefs.put(def, invokeInstr); } PointerKey exc = heapModel.getPointerKeyForLocal(node, invokeInstr.getException()); addNode(exc); callDefs.put(exc, invokeInstr); } } } @Override public boolean isParam(LocalPointerKey pk) { return params.get(pk) != null; } @Override public Iterator<SSAAbstractInvokeInstruction> getInstrsPassingParam(LocalPointerKey pk) { Set<SSAAbstractInvokeInstruction> instrs = callParams.get(pk); if (instrs == null) { return EmptyIterator.instance(); } else { return instrs.iterator(); } } @Override public SSAAbstractInvokeInstruction getInstrReturningTo(LocalPointerKey pk) { return callDefs.get(pk); } @Override public Iterator<? extends Object> getWritesToStaticField(StaticFieldKey sfk) throws IllegalArgumentException { if (sfk == null) { throw new IllegalArgumentException("sfk == null"); } Collection<MemoryAccess> fieldWrites = mam.getStaticFieldWrites(sfk.getField()); for (MemoryAccess a : fieldWrites) { addSubgraphForNode(a.getNode()); } return getSuccNodes(sfk, AssignGlobalLabel.v()); } @Override public Iterator<? extends Object> getReadsOfStaticField(StaticFieldKey sfk) throws IllegalArgumentException { if (sfk == null) { throw new IllegalArgumentException("sfk == null"); } Collection<MemoryAccess> fieldReads = mam.getStaticFieldReads(sfk.getField()); for (MemoryAccess a : fieldReads) { addSubgraphForNode(a.getNode()); } return getPredNodes(sfk, AssignGlobalLabel.v()); } @Override public Iterator<PointerKey> getWritesToInstanceField(PointerKey pk, IField f) { // TODO: cache this!! if (f == ArrayContents.v()) { return getArrayWrites(pk); } pk = convertPointerKeyToHeapModel(pk, mam.getHeapModel()); Collection<MemoryAccess> writes = mam.getFieldWrites(pk, f); for (MemoryAccess a : writes) { addSubgraphForNode(a.getNode()); } ArrayList<PointerKey> written = new ArrayList<>(); for (MemoryAccess a : writes) { IR ir = a.getNode().getIR(); SSAPutInstruction s = (SSAPutInstruction) ir.getInstructions()[a.getInstructionIndex()]; if (s == null) { // s can be null because the memory access map may be constructed from bytecode, // and the write instruction may have been eliminated from SSA because it's dead // TODO clean this up continue; } PointerKey r = heapModel.getPointerKeyForLocal(a.getNode(), s.getVal()); // if (Assertions.verifyAssertions) { // Assertions._assert(containsNode(r)); // } written.add(r); } return written.iterator(); } /** * convert a pointer key to one in the memory access map's heap model * * <p>TODO move this somewhere more appropriate * * @throws UnsupportedOperationException if it doesn't know how to handle a {@link PointerKey} */ public static PointerKey convertPointerKeyToHeapModel(PointerKey pk, HeapModel h) { if (pk == null) { throw new IllegalArgumentException("null pk"); } if (pk instanceof LocalPointerKey) { LocalPointerKey lpk = (LocalPointerKey) pk; return h.getPointerKeyForLocal(lpk.getNode(), lpk.getValueNumber()); } else if (pk instanceof ArrayContentsKey) { ArrayContentsKey ack = (ArrayContentsKey) pk; InstanceKey ik = ack.getInstanceKey(); if (ik instanceof NormalAllocationInNode) { NormalAllocationInNode nain = (NormalAllocationInNode) ik; ik = h.getInstanceKeyForAllocation(nain.getNode(), nain.getSite()); } else { assert false : "need to handle " + ik.getClass(); } return h.getPointerKeyForArrayContents(ik); } else if (pk instanceof ReturnValueKey) { ReturnValueKey rvk = (ReturnValueKey) pk; return h.getPointerKeyForReturnValue(rvk.getNode()); } throw new UnsupportedOperationException("need to handle " + pk.getClass()); } @Override public Iterator<PointerKey> getReadsOfInstanceField(PointerKey pk, IField f) { // TODO: cache this!! if (f == ArrayContents.v()) { return getArrayReads(pk); } pk = convertPointerKeyToHeapModel(pk, mam.getHeapModel()); Collection<MemoryAccess> reads = mam.getFieldReads(pk, f); for (MemoryAccess a : reads) { addSubgraphForNode(a.getNode()); } ArrayList<PointerKey> readInto = new ArrayList<>(); for (MemoryAccess a : reads) { IR ir = a.getNode().getIR(); SSAGetInstruction s = (SSAGetInstruction) ir.getInstructions()[a.getInstructionIndex()]; if (s == null) { // actually dead code continue; } PointerKey r = heapModel.getPointerKeyForLocal(a.getNode(), s.getDef()); // if (Assertions.verifyAssertions) { // Assertions._assert(containsNode(r)); // } readInto.add(r); } return readInto.iterator(); } Iterator<PointerKey> getArrayWrites(PointerKey arrayRef) { arrayRef = convertPointerKeyToHeapModel(arrayRef, mam.getHeapModel()); Collection<MemoryAccess> arrayWrites = mam.getArrayWrites(arrayRef); for (MemoryAccess a : arrayWrites) { addSubgraphForNode(a.getNode()); } ArrayList<PointerKey> written = new ArrayList<>(); for (MemoryAccess a : arrayWrites) { final CGNode node = a.getNode(); IR ir = node.getIR(); SSAInstruction instruction = ir.getInstructions()[a.getInstructionIndex()]; if (instruction == null) { // this means the array store found was in fact dead code // TODO detect this earlier and don't keep it in the MemoryAccessMap continue; } if (instruction instanceof SSAArrayStoreInstruction) { SSAArrayStoreInstruction s = (SSAArrayStoreInstruction) instruction; PointerKey r = heapModel.getPointerKeyForLocal(node, s.getValue()); written.add(r); } else if (instruction instanceof SSANewInstruction) { NewMultiDimInfo multiDimInfo = DemandPointerFlowGraph.getInfoForNewMultiDim( (SSANewInstruction) instruction, heapModel, node); for (Pair<PointerKey, PointerKey> arrStoreInstr : multiDimInfo.arrStoreInstrs) { written.add(arrStoreInstr.snd); } } else { Assertions.UNREACHABLE(); } } return written.iterator(); } protected Iterator<PointerKey> getArrayReads(PointerKey arrayRef) { arrayRef = convertPointerKeyToHeapModel(arrayRef, mam.getHeapModel()); Collection<MemoryAccess> arrayReads = mam.getArrayReads(arrayRef); for (MemoryAccess a : arrayReads) { addSubgraphForNode(a.getNode()); } ArrayList<PointerKey> read = new ArrayList<>(); for (MemoryAccess a : arrayReads) { IR ir = a.getNode().getIR(); SSAArrayLoadInstruction s = (SSAArrayLoadInstruction) ir.getInstructions()[a.getInstructionIndex()]; if (s == null) { // actually dead code continue; } PointerKey r = heapModel.getPointerKeyForLocal(a.getNode(), s.getDef()); // if (Assertions.verifyAssertions) { // Assertions._assert(containsNode(r)); // } read.add(r); } return read.iterator(); } /** * Add constraints to represent the flow of exceptions to the exceptional return value for this * node */ protected void addNodePassthruExceptionConstraints(CGNode node, IR ir) { // add constraints relating to thrown exceptions that reach the exit // block. List<ProgramCounter> peis = SSAPropagationCallGraphBuilder.getIncomingPEIs(ir, ir.getExitBlock()); PointerKey exception = heapModel.getPointerKeyForExceptionalReturnValue(node); IClass c = node.getClassHierarchy().lookupClass(TypeReference.JavaLangThrowable); addExceptionDefConstraints(ir, node, peis, exception, Collections.singleton(c)); } /** * Generate constraints which assign exception values into an exception pointer * * @param node governing node * @param peis list of PEI instructions * @param exceptionVar PointerKey representing a pointer to an exception value * @param catchClasses the types "caught" by the exceptionVar */ protected void addExceptionDefConstraints( IR ir, CGNode node, List<ProgramCounter> peis, PointerKey exceptionVar, Set<IClass> catchClasses) { for (ProgramCounter peiLoc : peis) { SSAInstruction pei = ir.getPEI(peiLoc); if (pei instanceof SSAAbstractInvokeInstruction) { SSAAbstractInvokeInstruction s = (SSAAbstractInvokeInstruction) pei; PointerKey e = heapModel.getPointerKeyForLocal(node, s.getException()); addNode(exceptionVar); addNode(e); addEdge(exceptionVar, e, AssignLabel.noFilter()); } else if (pei instanceof SSAAbstractThrowInstruction) { SSAAbstractThrowInstruction s = (SSAAbstractThrowInstruction) pei; PointerKey e = heapModel.getPointerKeyForLocal(node, s.getException()); addNode(exceptionVar); addNode(e); addEdge(exceptionVar, e, AssignLabel.noFilter()); } // Account for those exceptions for which we do not actually have a // points-to set for // the pei, but just instance keys Collection<TypeReference> types = pei.getExceptionTypes(); if (types != null) { for (TypeReference type : types) { if (type != null) { InstanceKey ik = heapModel.getInstanceKeyForPEI(node, peiLoc, type); if (ik == null) { // ugh. hope someone somewhere else knows what they are doing. // this is probably due to analysis scope exclusions. continue; } if (!(ik instanceof ConcreteTypeKey)) { assert ik instanceof ConcreteTypeKey : "uh oh: need to implement getCaughtException constraints for instance " + ik; } ConcreteTypeKey ck = (ConcreteTypeKey) ik; IClass klass = ck.getType(); if (PropagationCallGraphBuilder.catches(catchClasses, klass, cha)) { addNode(exceptionVar); addNode(ik); addEdge(exceptionVar, ik, NewLabel.v()); } } } } } } /** add constraints for reference constants assigned to vars */ protected void addNodeConstantConstraints(CGNode node, IR ir) { SymbolTable symbolTable = ir.getSymbolTable(); for (int i = 1; i <= symbolTable.getMaxValueNumber(); i++) { if (symbolTable.isConstant(i)) { Object v = symbolTable.getConstantValue(i); if (!(v instanceof Number)) { Object S = symbolTable.getConstantValue(i); TypeReference type = node.getMethod() .getDeclaringClass() .getClassLoader() .getLanguage() .getConstantType(S); if (type != null) { InstanceKey ik = heapModel.getInstanceKeyForConstant(type, S); if (ik != null) { PointerKey pk = heapModel.getPointerKeyForLocal(node, i); addNode(pk); addNode(ik); addEdge(pk, ik, NewLabel.v()); } } } } } } }
19,595
37.727273
100
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/demandpa/flowgraph/AbstractFlowLabelVisitor.java
/* * This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html. * * This file is a derivative of code released by the University of * California under the terms listed below. * * Refinement Analysis Tools is Copyright (c) 2007 The Regents of the * University of California (Regents). Provided that this notice and * the following two paragraphs are included in any distribution of * Refinement Analysis Tools or its derivative work, Regents agrees * not to assert any of Regents' copyright rights in Refinement * Analysis Tools against recipient for recipient's reproduction, * preparation of derivative works, public display, public * performance, distribution or sublicensing of Refinement Analysis * Tools and derivative works, in source code and object code form. * This agreement not to assert does not confer, by implication, * estoppel, or otherwise any license or rights in any intellectual * property of Regents, including, but not limited to, any patents * of Regents or Regents' employees. * * IN NO EVENT SHALL REGENTS BE LIABLE TO ANY PARTY FOR DIRECT, * INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, * INCLUDING LOST PROFITS, ARISING OUT OF THE USE OF THIS SOFTWARE * AND ITS DOCUMENTATION, EVEN IF REGENTS HAS BEEN ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * REGENTS SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE AND FURTHER DISCLAIMS ANY STATUTORY * WARRANTY OF NON-INFRINGEMENT. THE SOFTWARE AND ACCOMPANYING * DOCUMENTATION, IF ANY, PROVIDED HEREUNDER IS PROVIDED "AS * IS". REGENTS HAS NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, * UPDATES, ENHANCEMENTS, OR MODIFICATIONS. */ package com.ibm.wala.demandpa.flowgraph; import com.ibm.wala.demandpa.flowgraph.IFlowLabel.IFlowLabelVisitor; /** * An {@link IFlowLabelVisitor} that does nothing. Subclasses can override only the label types they * care about. * * @author Manu Sridharan */ public class AbstractFlowLabelVisitor implements IFlowLabelVisitor { @Override public void visitParam(ParamLabel label, Object dst) {} @Override public void visitReturn(ReturnLabel label, Object dst) {} @Override public void visitAssign(AssignLabel label, Object dst) {} @Override public void visitAssignGlobal(AssignGlobalLabel label, Object dst) {} @Override public void visitGetField(GetFieldLabel label, Object dst) {} @Override public void visitMatch(MatchLabel label, Object dst) {} @Override public void visitNew(NewLabel label, Object dst) {} @Override public void visitPutField(PutFieldLabel label, Object dst) {} @Override public void visitAssignGlobalBar(AssignGlobalBarLabel label, Object dst) {} @Override public void visitAssignBar(AssignBarLabel label, Object dst) {} @Override public void visitGetFieldBar(GetFieldBarLabel label, Object dst) {} @Override public void visitMatchBar(MatchBarLabel label, Object dst) {} @Override public void visitNewBar(NewBarLabel label, Object dst) {} @Override public void visitPutFieldBar(PutFieldBarLabel label, Object dst) {} @Override public void visitReturnBar(ReturnBarLabel label, Object dst) {} @Override public void visitParamBar(ParamBarLabel label, Object dst) {} }
3,490
34.622449
100
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/demandpa/flowgraph/AssignBarLabel.java
/* * This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html. * * This file is a derivative of code released by the University of * California under the terms listed below. * * Refinement Analysis Tools is Copyright (c) 2007 The Regents of the * University of California (Regents). Provided that this notice and * the following two paragraphs are included in any distribution of * Refinement Analysis Tools or its derivative work, Regents agrees * not to assert any of Regents' copyright rights in Refinement * Analysis Tools against recipient for recipient's reproduction, * preparation of derivative works, public display, public * performance, distribution or sublicensing of Refinement Analysis * Tools and derivative works, in source code and object code form. * This agreement not to assert does not confer, by implication, * estoppel, or otherwise any license or rights in any intellectual * property of Regents, including, but not limited to, any patents * of Regents or Regents' employees. * * IN NO EVENT SHALL REGENTS BE LIABLE TO ANY PARTY FOR DIRECT, * INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, * INCLUDING LOST PROFITS, ARISING OUT OF THE USE OF THIS SOFTWARE * AND ITS DOCUMENTATION, EVEN IF REGENTS HAS BEEN ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * REGENTS SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE AND FURTHER DISCLAIMS ANY STATUTORY * WARRANTY OF NON-INFRINGEMENT. THE SOFTWARE AND ACCOMPANYING * DOCUMENTATION, IF ANY, PROVIDED HEREUNDER IS PROVIDED "AS * IS". REGENTS HAS NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, * UPDATES, ENHANCEMENTS, OR MODIFICATIONS. */ package com.ibm.wala.demandpa.flowgraph; import com.ibm.wala.ipa.callgraph.propagation.FilteredPointerKey.TypeFilter; /** @author Manu Sridharan */ public class AssignBarLabel implements IFlowLabelWithFilter { private static final AssignBarLabel noFilter = new AssignBarLabel(null); private final TypeFilter filter; private AssignBarLabel(TypeFilter filter) { this.filter = filter; } public static AssignBarLabel noFilter() { return noFilter; } public static AssignBarLabel make(TypeFilter filter) { return new AssignBarLabel(filter); } /* * (non-Javadoc) * @see demandGraph.IFlowLabel#bar() */ @Override public AssignLabel bar() { return (this == noFilter) ? AssignLabel.noFilter() : AssignLabel.make(filter); } /* * (non-Javadoc) * @see demandGraph.IFlowLabel#visit(demandGraph.IFlowLabel.IFlowLabelVisitor, java.lang.Object) */ @Override public void visit(IFlowLabelVisitor v, Object dst) throws IllegalArgumentException { if (v == null) { throw new IllegalArgumentException("v == null"); } v.visitAssignBar(this, dst); } @Override public boolean isBarred() { return true; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((filter == null) ? 0 : filter.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 AssignBarLabel other = (AssignBarLabel) obj; if (filter == null) { if (other.filter != null) return false; } else if (!filter.equals(other.filter)) return false; return true; } @Override public TypeFilter getFilter() { return filter; } }
3,733
32.339286
98
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/demandpa/flowgraph/AssignGlobalBarLabel.java
/* * This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html. * * This file is a derivative of code released by the University of * California under the terms listed below. * * Refinement Analysis Tools is Copyright (c) 2007 The Regents of the * University of California (Regents). Provided that this notice and * the following two paragraphs are included in any distribution of * Refinement Analysis Tools or its derivative work, Regents agrees * not to assert any of Regents' copyright rights in Refinement * Analysis Tools against recipient for recipient's reproduction, * preparation of derivative works, public display, public * performance, distribution or sublicensing of Refinement Analysis * Tools and derivative works, in source code and object code form. * This agreement not to assert does not confer, by implication, * estoppel, or otherwise any license or rights in any intellectual * property of Regents, including, but not limited to, any patents * of Regents or Regents' employees. * * IN NO EVENT SHALL REGENTS BE LIABLE TO ANY PARTY FOR DIRECT, * INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, * INCLUDING LOST PROFITS, ARISING OUT OF THE USE OF THIS SOFTWARE * AND ITS DOCUMENTATION, EVEN IF REGENTS HAS BEEN ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * REGENTS SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE AND FURTHER DISCLAIMS ANY STATUTORY * WARRANTY OF NON-INFRINGEMENT. THE SOFTWARE AND ACCOMPANYING * DOCUMENTATION, IF ANY, PROVIDED HEREUNDER IS PROVIDED "AS * IS". REGENTS HAS NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, * UPDATES, ENHANCEMENTS, OR MODIFICATIONS. */ package com.ibm.wala.demandpa.flowgraph; /** @author Manu Sridharan */ public class AssignGlobalBarLabel implements IFlowLabel { private static final AssignGlobalBarLabel theInstance = new AssignGlobalBarLabel(); private AssignGlobalBarLabel() {} public static AssignGlobalBarLabel v() { return theInstance; } /* * (non-Javadoc) * * @see demandGraph.IFlowLabel#bar() */ @Override public AssignGlobalLabel bar() { return AssignGlobalLabel.v(); } /* * (non-Javadoc) * * @see demandGraph.IFlowLabel#visit(demandGraph.IFlowLabel.IFlowLabelVisitor, * java.lang.Object) */ @Override public void visit(IFlowLabelVisitor v, Object dst) throws IllegalArgumentException { if (v == null) { throw new IllegalArgumentException("v == null"); } v.visitAssignGlobalBar(this, dst); } @Override public boolean isBarred() { return true; } @Override public String toString() { return "assignGlobalBar"; } }
2,915
33.305882
86
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/demandpa/flowgraph/AssignGlobalLabel.java
/* * This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html. * * This file is a derivative of code released by the University of * California under the terms listed below. * * Refinement Analysis Tools is Copyright (c) 2007 The Regents of the * University of California (Regents). Provided that this notice and * the following two paragraphs are included in any distribution of * Refinement Analysis Tools or its derivative work, Regents agrees * not to assert any of Regents' copyright rights in Refinement * Analysis Tools against recipient for recipient's reproduction, * preparation of derivative works, public display, public * performance, distribution or sublicensing of Refinement Analysis * Tools and derivative works, in source code and object code form. * This agreement not to assert does not confer, by implication, * estoppel, or otherwise any license or rights in any intellectual * property of Regents, including, but not limited to, any patents * of Regents or Regents' employees. * * IN NO EVENT SHALL REGENTS BE LIABLE TO ANY PARTY FOR DIRECT, * INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, * INCLUDING LOST PROFITS, ARISING OUT OF THE USE OF THIS SOFTWARE * AND ITS DOCUMENTATION, EVEN IF REGENTS HAS BEEN ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * REGENTS SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE AND FURTHER DISCLAIMS ANY STATUTORY * WARRANTY OF NON-INFRINGEMENT. THE SOFTWARE AND ACCOMPANYING * DOCUMENTATION, IF ANY, PROVIDED HEREUNDER IS PROVIDED "AS * IS". REGENTS HAS NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, * UPDATES, ENHANCEMENTS, OR MODIFICATIONS. */ package com.ibm.wala.demandpa.flowgraph; public class AssignGlobalLabel implements IFlowLabel { private static final AssignGlobalLabel theInstance = new AssignGlobalLabel(); private AssignGlobalLabel() {} public static AssignGlobalLabel v() { return theInstance; } @Override public void visit(IFlowLabelVisitor v, Object dst) throws IllegalArgumentException { if (v == null) { throw new IllegalArgumentException("v == null"); } v.visitAssignGlobal(this, dst); } @Override public AssignGlobalBarLabel bar() { return AssignGlobalBarLabel.v(); } @Override public boolean isBarred() { return false; } @Override public String toString() { return "assignGlobal"; } }
2,652
35.847222
86
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/demandpa/flowgraph/AssignLabel.java
/* * This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html. * * This file is a derivative of code released by the University of * California under the terms listed below. * * Refinement Analysis Tools is Copyright (c) 2007 The Regents of the * University of California (Regents). Provided that this notice and * the following two paragraphs are included in any distribution of * Refinement Analysis Tools or its derivative work, Regents agrees * not to assert any of Regents' copyright rights in Refinement * Analysis Tools against recipient for recipient's reproduction, * preparation of derivative works, public display, public * performance, distribution or sublicensing of Refinement Analysis * Tools and derivative works, in source code and object code form. * This agreement not to assert does not confer, by implication, * estoppel, or otherwise any license or rights in any intellectual * property of Regents, including, but not limited to, any patents * of Regents or Regents' employees. * * IN NO EVENT SHALL REGENTS BE LIABLE TO ANY PARTY FOR DIRECT, * INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, * INCLUDING LOST PROFITS, ARISING OUT OF THE USE OF THIS SOFTWARE * AND ITS DOCUMENTATION, EVEN IF REGENTS HAS BEEN ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * REGENTS SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE AND FURTHER DISCLAIMS ANY STATUTORY * WARRANTY OF NON-INFRINGEMENT. THE SOFTWARE AND ACCOMPANYING * DOCUMENTATION, IF ANY, PROVIDED HEREUNDER IS PROVIDED "AS * IS". REGENTS HAS NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, * UPDATES, ENHANCEMENTS, OR MODIFICATIONS. */ package com.ibm.wala.demandpa.flowgraph; import com.ibm.wala.ipa.callgraph.propagation.FilteredPointerKey.TypeFilter; public class AssignLabel implements IFlowLabelWithFilter { private static final AssignLabel noFilter = new AssignLabel(null); private final TypeFilter filter; private AssignLabel(TypeFilter filter) { this.filter = filter; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((filter == null) ? 0 : filter.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 AssignLabel other = (AssignLabel) obj; if (filter == null) { if (other.filter != null) return false; } else if (!filter.equals(other.filter)) return false; return true; } public static AssignLabel noFilter() { return noFilter; } public static AssignLabel make(TypeFilter filter) { return new AssignLabel(filter); } @Override public void visit(IFlowLabelVisitor v, Object dst) throws IllegalArgumentException { if (v == null) { throw new IllegalArgumentException("v == null"); } v.visitAssign(this, dst); } @Override public AssignBarLabel bar() { return this == noFilter ? AssignBarLabel.noFilter() : AssignBarLabel.make(filter); } @Override public String toString() { return "assign"; } @Override public boolean isBarred() { return false; } @Override public TypeFilter getFilter() { return filter; } }
3,550
31.87963
86
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/demandpa/flowgraph/CallLabel.java
/* * This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html. * * This file is a derivative of code released by the University of * California under the terms listed below. * * Refinement Analysis Tools is Copyright (c) 2007 The Regents of the * University of California (Regents). Provided that this notice and * the following two paragraphs are included in any distribution of * Refinement Analysis Tools or its derivative work, Regents agrees * not to assert any of Regents' copyright rights in Refinement * Analysis Tools against recipient for recipient's reproduction, * preparation of derivative works, public display, public * performance, distribution or sublicensing of Refinement Analysis * Tools and derivative works, in source code and object code form. * This agreement not to assert does not confer, by implication, * estoppel, or otherwise any license or rights in any intellectual * property of Regents, including, but not limited to, any patents * of Regents or Regents' employees. * * IN NO EVENT SHALL REGENTS BE LIABLE TO ANY PARTY FOR DIRECT, * INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, * INCLUDING LOST PROFITS, ARISING OUT OF THE USE OF THIS SOFTWARE * AND ITS DOCUMENTATION, EVEN IF REGENTS HAS BEEN ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * REGENTS SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE AND FURTHER DISCLAIMS ANY STATUTORY * WARRANTY OF NON-INFRINGEMENT. THE SOFTWARE AND ACCOMPANYING * DOCUMENTATION, IF ANY, PROVIDED HEREUNDER IS PROVIDED "AS * IS". REGENTS HAS NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, * UPDATES, ENHANCEMENTS, OR MODIFICATIONS. */ package com.ibm.wala.demandpa.flowgraph; import com.ibm.wala.ipa.callgraph.propagation.cfa.CallerSiteContext; public abstract class CallLabel implements IFlowLabel { protected final CallerSiteContext callSite; protected CallLabel(CallerSiteContext callSite) { this.callSite = callSite; } public CallerSiteContext getCallSite() { return callSite; } @Override public int hashCode() { final int PRIME = 31; int result = 1; result = PRIME * result + ((callSite == null) ? 0 : callSite.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 ParamBarLabel other = (ParamBarLabel) obj; if (callSite == null) { if (other.callSite != null) return false; } else if (!callSite.equals(other.callSite)) return false; return true; } }
2,862
37.689189
77
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/demandpa/flowgraph/DemandPointerFlowGraph.java
/* * This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html. * * This file is a derivative of code released by the University of * California under the terms listed below. * * Refinement Analysis Tools is Copyright (c) 2007 The Regents of the * University of California (Regents). Provided that this notice and * the following two paragraphs are included in any distribution of * Refinement Analysis Tools or its derivative work, Regents agrees * not to assert any of Regents' copyright rights in Refinement * Analysis Tools against recipient for recipient's reproduction, * preparation of derivative works, public display, public * performance, distribution or sublicensing of Refinement Analysis * Tools and derivative works, in source code and object code form. * This agreement not to assert does not confer, by implication, * estoppel, or otherwise any license or rights in any intellectual * property of Regents, including, but not limited to, any patents * of Regents or Regents' employees. * * IN NO EVENT SHALL REGENTS BE LIABLE TO ANY PARTY FOR DIRECT, * INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, * INCLUDING LOST PROFITS, ARISING OUT OF THE USE OF THIS SOFTWARE * AND ITS DOCUMENTATION, EVEN IF REGENTS HAS BEEN ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * REGENTS SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE AND FURTHER DISCLAIMS ANY STATUTORY * WARRANTY OF NON-INFRINGEMENT. THE SOFTWARE AND ACCOMPANYING * DOCUMENTATION, IF ANY, PROVIDED HEREUNDER IS PROVIDED "AS * IS". REGENTS HAS NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, * UPDATES, ENHANCEMENTS, OR MODIFICATIONS. */ package com.ibm.wala.demandpa.flowgraph; import com.ibm.wala.classLoader.ArrayClass; import com.ibm.wala.classLoader.IClass; import com.ibm.wala.classLoader.IField; import com.ibm.wala.classLoader.ProgramCounter; import com.ibm.wala.demandpa.util.ArrayContents; import com.ibm.wala.demandpa.util.MemoryAccessMap; import com.ibm.wala.demandpa.util.PointerParamValueNumIterator; import com.ibm.wala.ipa.callgraph.CGNode; import com.ibm.wala.ipa.callgraph.CallGraph; import com.ibm.wala.ipa.callgraph.propagation.ConcreteTypeKey; import com.ibm.wala.ipa.callgraph.propagation.FilteredPointerKey; import com.ibm.wala.ipa.callgraph.propagation.HeapModel; import com.ibm.wala.ipa.callgraph.propagation.InstanceKey; import com.ibm.wala.ipa.callgraph.propagation.PointerKey; import com.ibm.wala.ipa.callgraph.propagation.PropagationCallGraphBuilder; import com.ibm.wala.ipa.callgraph.propagation.SSAPropagationCallGraphBuilder; import com.ibm.wala.ipa.cha.IClassHierarchy; import com.ibm.wala.shrike.shrikeBT.IGetInstruction; import com.ibm.wala.shrike.shrikeBT.IInstruction.Visitor; import com.ibm.wala.shrike.shrikeBT.IInvokeInstruction; import com.ibm.wala.shrike.shrikeBT.IPutInstruction; import com.ibm.wala.shrike.shrikeBT.ITypeTestInstruction; import com.ibm.wala.shrike.shrikeBT.NewInstruction; import com.ibm.wala.shrike.shrikeBT.ReturnInstruction; import com.ibm.wala.shrike.shrikeBT.ThrowInstruction; import com.ibm.wala.ssa.DefUse; import com.ibm.wala.ssa.IR; import com.ibm.wala.ssa.ISSABasicBlock; import com.ibm.wala.ssa.SSAAbstractInvokeInstruction; import com.ibm.wala.ssa.SSAAbstractThrowInstruction; import com.ibm.wala.ssa.SSAArrayLoadInstruction; import com.ibm.wala.ssa.SSAArrayStoreInstruction; import com.ibm.wala.ssa.SSACheckCastInstruction; import com.ibm.wala.ssa.SSAGetCaughtExceptionInstruction; import com.ibm.wala.ssa.SSAGetInstruction; import com.ibm.wala.ssa.SSAInstruction; import com.ibm.wala.ssa.SSAInvokeInstruction; import com.ibm.wala.ssa.SSALoadMetadataInstruction; import com.ibm.wala.ssa.SSANewInstruction; import com.ibm.wala.ssa.SSAPiInstruction; import com.ibm.wala.ssa.SSAPutInstruction; import com.ibm.wala.ssa.SSAReturnInstruction; import com.ibm.wala.ssa.SSAThrowInstruction; import com.ibm.wala.ssa.SymbolTable; import com.ibm.wala.types.FieldReference; import com.ibm.wala.types.TypeReference; import com.ibm.wala.util.collections.HashSetFactory; import com.ibm.wala.util.collections.Iterator2Iterable; import com.ibm.wala.util.collections.Pair; import java.util.Collection; import java.util.List; import java.util.Set; /** * A graph representation of statements flowing pointer values, but <em>not</em> primitive values. * Nodes are variables, and edges are <em>against</em> value flow; assignment x = y yields edge from * x to y with label {@link AssignLabel#noFilter()} */ public class DemandPointerFlowGraph extends AbstractDemandFlowGraph implements IFlowGraph { /** */ private static final long serialVersionUID = 1L; public DemandPointerFlowGraph( CallGraph cg, HeapModel heapModel, MemoryAccessMap mam, IClassHierarchy cha) { super(cg, heapModel, mam, cha); } /** add nodes for parameters and return values */ @Override protected void addNodesForParameters(CGNode node, IR ir) { for (int parameter : Iterator2Iterable.make(new PointerParamValueNumIterator(node))) { PointerKey paramPk = heapModel.getPointerKeyForLocal(node, parameter); addNode(paramPk); params.put(paramPk, node); } PointerKey returnKey = heapModel.getPointerKeyForReturnValue(node); addNode(returnKey); returns.put(returnKey, node); PointerKey exceptionReturnKey = heapModel.getPointerKeyForExceptionalReturnValue(node); addNode(exceptionReturnKey); returns.put(exceptionReturnKey, node); } @Override protected FlowStatementVisitor makeVisitor(CGNode node) { return new StatementVisitor(heapModel, this, cha, cg, node); } /** * A visitor that generates graph nodes and edges for an IR. * * <p>strategy: when visiting a statement, for each use of that statement, add a graph edge from * def to use. * * <p>TODO: special treatment for parameter passing, etc. */ public static class StatementVisitor extends SSAInstruction.Visitor implements FlowStatementVisitor { private final HeapModel heapModel; private final IFlowGraph g; private final IClassHierarchy cha; private final CallGraph cg; /** The node whose statements we are currently traversing */ protected final CGNode node; /** The governing IR */ protected final IR ir; /** The basic block currently being processed */ private ISSABasicBlock basicBlock; /** Governing symbol table */ protected final SymbolTable symbolTable; /** Def-use information */ protected final DefUse du; public StatementVisitor( HeapModel heapModel, IFlowGraph g, IClassHierarchy cha, CallGraph cg, CGNode node) { super(); this.heapModel = heapModel; this.g = g; this.cha = cha; this.cg = cg; this.node = node; this.ir = node.getIR(); this.du = node.getDU(); this.symbolTable = ir.getSymbolTable(); assert symbolTable != null; } @Override public void visitArrayLoad(SSAArrayLoadInstruction instruction) { // skip arrays of primitive type if (instruction.typeIsPrimitive()) { return; } PointerKey result = heapModel.getPointerKeyForLocal(node, instruction.getDef()); PointerKey arrayRef = heapModel.getPointerKeyForLocal(node, instruction.getArrayRef()); // TODO optimizations for purely local stuff g.addNode(result); g.addNode(arrayRef); g.addEdge(result, arrayRef, GetFieldLabel.make(ArrayContents.v())); } /** @see Visitor#visitArrayStore(com.ibm.wala.shrike.shrikeBT.IArrayStoreInstruction) */ @Override public void visitArrayStore(SSAArrayStoreInstruction instruction) { // Assertions.UNREACHABLE(); // skip arrays of primitive type if (instruction.typeIsPrimitive()) { return; } // make node for used value PointerKey value = heapModel.getPointerKeyForLocal(node, instruction.getValue()); PointerKey arrayRef = heapModel.getPointerKeyForLocal(node, instruction.getArrayRef()); // TODO purely local optimizations g.addNode(value); g.addNode(arrayRef); g.addEdge(arrayRef, value, PutFieldLabel.make(ArrayContents.v())); } /** @see Visitor#visitCheckCast(ITypeTestInstruction) */ @Override public void visitCheckCast(SSACheckCastInstruction instruction) { Set<IClass> types = HashSetFactory.make(); for (TypeReference t : instruction.getDeclaredResultTypes()) { IClass cls = cha.lookupClass(t); if (cls == null) { return; } else { types.add(cls); } } FilteredPointerKey.MultipleClassesFilter filter = new FilteredPointerKey.MultipleClassesFilter(types.toArray(new IClass[0])); PointerKey result = heapModel.getPointerKeyForLocal(node, instruction.getResult()); PointerKey value = heapModel.getPointerKeyForLocal(node, instruction.getVal()); g.addNode(result); g.addNode(value); g.addEdge(result, value, AssignLabel.make(filter)); } /** @see Visitor#visitReturn(ReturnInstruction) */ @Override public void visitReturn(SSAReturnInstruction instruction) { // skip returns of primitive type if (instruction.returnsPrimitiveType() || instruction.returnsVoid()) { return; } else { // just make a node for the def'd value PointerKey def = heapModel.getPointerKeyForLocal(node, instruction.getResult()); g.addNode(def); PointerKey returnValue = heapModel.getPointerKeyForReturnValue(node); g.addNode(returnValue); g.addEdge(returnValue, def, AssignLabel.noFilter()); } } /** @see Visitor#visitGet(IGetInstruction) */ @Override public void visitGet(SSAGetInstruction instruction) { visitGetInternal( instruction.getDef(), instruction.getRef(), instruction.isStatic(), instruction.getDeclaredField()); } protected void visitGetInternal(int lval, int ref, boolean isStatic, FieldReference field) { // skip getfields of primitive type (optimisation) if (field.getFieldType().isPrimitiveType()) { return; } IField f = cg.getClassHierarchy().resolveField(field); if (f == null) { return; } PointerKey def = heapModel.getPointerKeyForLocal(node, lval); assert def != null; if (isStatic) { PointerKey fKey = heapModel.getPointerKeyForStaticField(f); g.addNode(def); g.addNode(fKey); g.addEdge(def, fKey, AssignGlobalLabel.v()); } else { PointerKey refKey = heapModel.getPointerKeyForLocal(node, ref); g.addNode(def); g.addNode(refKey); // TODO purely local optimizations g.addEdge(def, refKey, GetFieldLabel.make(f)); } } /** @see Visitor#visitPut(IPutInstruction) */ @Override public void visitPut(SSAPutInstruction instruction) { visitPutInternal( instruction.getVal(), instruction.getRef(), instruction.isStatic(), instruction.getDeclaredField()); } public void visitPutInternal(int rval, int ref, boolean isStatic, FieldReference field) { // skip putfields of primitive type (optimisation) if (field.getFieldType().isPrimitiveType()) { return; } IField f = cg.getClassHierarchy().resolveField(field); if (f == null) { return; } PointerKey use = heapModel.getPointerKeyForLocal(node, rval); assert use != null; if (isStatic) { PointerKey fKey = heapModel.getPointerKeyForStaticField(f); g.addNode(use); g.addNode(fKey); g.addEdge(fKey, use, AssignGlobalLabel.v()); } else { PointerKey refKey = heapModel.getPointerKeyForLocal(node, ref); g.addNode(use); g.addNode(refKey); g.addEdge(refKey, use, PutFieldLabel.make(f)); } } /** @see Visitor#visitInvoke(IInvokeInstruction) */ @Override public void visitInvoke(SSAInvokeInstruction instruction) { // for (int i = 0; i < instruction.getNumberOfUses(); i++) { // // just make nodes for parameters; we'll get to them when // // traversing // // from the callee // PointerKey use = heapModel.getPointerKeyForLocal(node, instruction.getUse(i)); // g.addNode(use); // Set<SSAInvokeInstruction> s = MapUtil.findOrCreateSet(callParams, use); // s.add(instruction); // } // // // for any def'd values, keep track of the fact that they are def'd // // by a call // if (instruction.hasDef()) { // PointerKey def = heapModel.getPointerKeyForLocal(node, instruction.getDef()); // g.addNode(def); // callDefs.put(def, instruction); // } // PointerKey exc = heapModel.getPointerKeyForLocal(node, instruction.getException()); // g.addNode(exc); // callDefs.put(exc, instruction); } /** @see Visitor#visitNew(NewInstruction) */ @Override public void visitNew(SSANewInstruction instruction) { InstanceKey iKey = heapModel.getInstanceKeyForAllocation(node, instruction.getNewSite()); if (iKey == null) { // something went wrong. I hope someone raised a warning. return; } PointerKey def = heapModel.getPointerKeyForLocal(node, instruction.getDef()); g.addNode(iKey); g.addNode(def); g.addEdge(def, iKey, NewLabel.v()); NewMultiDimInfo multiDimInfo = getInfoForNewMultiDim(instruction, heapModel, node); if (multiDimInfo != null) { for (Pair<PointerKey, InstanceKey> newInstr : multiDimInfo.newInstrs) { g.addNode(newInstr.fst); g.addNode(newInstr.snd); g.addEdge(newInstr.fst, newInstr.snd, NewLabel.v()); } for (Pair<PointerKey, PointerKey> arrStoreInstr : multiDimInfo.arrStoreInstrs) { g.addNode(arrStoreInstr.fst); g.addNode(arrStoreInstr.snd); g.addEdge(arrStoreInstr.fst, arrStoreInstr.snd, PutFieldLabel.make(ArrayContents.v())); } } } /** @see Visitor#visitThrow(ThrowInstruction) */ @Override public void visitThrow(SSAThrowInstruction instruction) { // don't do anything: we handle exceptional edges // in a separate pass } @Override public void visitGetCaughtException(SSAGetCaughtExceptionInstruction instruction) { List<ProgramCounter> peis = SSAPropagationCallGraphBuilder.getIncomingPEIs(ir, getBasicBlock()); PointerKey def = heapModel.getPointerKeyForLocal(node, instruction.getDef()); Set<IClass> types = SSAPropagationCallGraphBuilder.getCaughtExceptionTypes(instruction, ir); addExceptionDefConstraints(ir, node, peis, def, types); } /** * Generate constraints which assign exception values into an exception pointer * * @param node governing node * @param peis list of PEI instructions * @param exceptionVar PointerKey representing a pointer to an exception value * @param catchClasses the types "caught" by the exceptionVar */ protected void addExceptionDefConstraints( IR ir, CGNode node, List<ProgramCounter> peis, PointerKey exceptionVar, Set<IClass> catchClasses) { for (ProgramCounter peiLoc : peis) { SSAInstruction pei = ir.getPEI(peiLoc); if (pei instanceof SSAAbstractInvokeInstruction) { SSAAbstractInvokeInstruction s = (SSAAbstractInvokeInstruction) pei; PointerKey e = heapModel.getPointerKeyForLocal(node, s.getException()); g.addNode(exceptionVar); g.addNode(e); g.addEdge(exceptionVar, e, AssignLabel.noFilter()); } else if (pei instanceof SSAAbstractThrowInstruction) { SSAAbstractThrowInstruction s = (SSAAbstractThrowInstruction) pei; PointerKey e = heapModel.getPointerKeyForLocal(node, s.getException()); g.addNode(exceptionVar); g.addNode(e); g.addEdge(exceptionVar, e, AssignLabel.noFilter()); } // Account for those exceptions for which we do not actually have a // points-to set for // the pei, but just instance keys Collection<TypeReference> types = pei.getExceptionTypes(); if (types != null) { for (TypeReference type : types) { if (type != null) { InstanceKey ik = heapModel.getInstanceKeyForPEI(node, peiLoc, type); if (ik == null) { // probably due to exclusions continue; } assert ik instanceof ConcreteTypeKey : "uh oh: need to implement getCaughtException constraints for instance " + ik; ConcreteTypeKey ck = (ConcreteTypeKey) ik; IClass klass = ck.getType(); if (PropagationCallGraphBuilder.catches(catchClasses, klass, cha)) { g.addNode(exceptionVar); g.addNode(ik); g.addEdge(exceptionVar, ik, NewLabel.v()); } } } } } } /* * (non-Javadoc) * * @see com.ibm.domo.ssa.SSAInstruction.Visitor#visitPi(com.ibm.domo.ssa.SSAPiInstruction) */ @Override public void visitPi(SSAPiInstruction instruction) { // for now, ignore condition and just treat it as a copy PointerKey def = heapModel.getPointerKeyForLocal(node, instruction.getDef()); PointerKey use = heapModel.getPointerKeyForLocal(node, instruction.getVal()); g.addNode(def); g.addNode(use); g.addEdge(def, use, AssignLabel.noFilter()); } public ISSABasicBlock getBasicBlock() { return basicBlock; } /** The calling loop must call this in each iteration! */ @Override public void setBasicBlock(ISSABasicBlock block) { basicBlock = block; } @Override public void visitLoadMetadata(SSALoadMetadataInstruction instruction) { PointerKey def = heapModel.getPointerKeyForLocal(node, instruction.getDef()); assert instruction.getType() == TypeReference.JavaLangClass; InstanceKey iKey = heapModel.getInstanceKeyForMetadataObject(instruction.getToken(), instruction.getType()); g.addNode(iKey); g.addNode(def); g.addEdge(def, iKey, NewLabel.v()); } } public static class NewMultiDimInfo { public final Collection<Pair<PointerKey, InstanceKey>> newInstrs; // pairs of (base pointer, stored val) public final Collection<Pair<PointerKey, PointerKey>> arrStoreInstrs; public NewMultiDimInfo( Collection<Pair<PointerKey, InstanceKey>> newInstrs, Collection<Pair<PointerKey, PointerKey>> arrStoreInstrs) { this.newInstrs = newInstrs; this.arrStoreInstrs = arrStoreInstrs; } } /** * collect information about the new instructions and putfield instructions used to model an * allocation of a multi-dimensional array. excludes the new instruction itself (i.e., the * allocation of the top-level multi-dim array). */ public static NewMultiDimInfo getInfoForNewMultiDim( SSANewInstruction instruction, HeapModel heapModel, CGNode node) { if (heapModel == null) { throw new IllegalArgumentException("null heapModel"); } Collection<Pair<PointerKey, InstanceKey>> newInstrs = HashSetFactory.make(); Collection<Pair<PointerKey, PointerKey>> arrStoreInstrs = HashSetFactory.make(); InstanceKey iKey = heapModel.getInstanceKeyForAllocation(node, instruction.getNewSite()); if (iKey == null) { // something went wrong. I hope someone raised a warning. return null; } IClass klass = iKey.getConcreteType(); // if not a multi-dim array allocation, return null if (!klass.isArrayClass() || ((ArrayClass) klass).getElementClass() == null || !((ArrayClass) klass).getElementClass().isArrayClass()) { return null; } PointerKey def = heapModel.getPointerKeyForLocal(node, instruction.getDef()); int dim = 0; InstanceKey lastInstance = iKey; PointerKey lastVar = def; while (klass != null && klass.isArrayClass()) { klass = ((ArrayClass) klass).getElementClass(); // klass == null means it's a primitive if (klass != null && klass.isArrayClass()) { InstanceKey ik = heapModel.getInstanceKeyForMultiNewArray(node, instruction.getNewSite(), dim); PointerKey pk = heapModel.getPointerKeyForArrayContents(lastInstance); // if (DEBUG_MULTINEWARRAY) { // Trace.println("multinewarray constraint: "); // Trace.println(" pk: " + pk); // Trace.println(" ik: " + system.findOrCreateIndexForInstanceKey(ik) // + " concrete type " + ik.getConcreteType() // + " is " + ik); // Trace.println(" klass:" + klass); // } // g.addEdge(pk, ik, NewLabel.v()); newInstrs.add(Pair.make(pk, ik)); arrStoreInstrs.add(Pair.make(lastVar, pk)); lastInstance = ik; lastVar = pk; dim++; } } return new NewMultiDimInfo(newInstrs, arrStoreInstrs); } }
21,471
37.411449
100
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/demandpa/flowgraph/DemandValueFlowGraph.java
/* * This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html. * * This file is a derivative of code released by the University of * California under the terms listed below. * * Refinement Analysis Tools is Copyright (c) 2007 The Regents of the * University of California (Regents). Provided that this notice and * the following two paragraphs are included in any distribution of * Refinement Analysis Tools or its derivative work, Regents agrees * not to assert any of Regents' copyright rights in Refinement * Analysis Tools against recipient for recipient's reproduction, * preparation of derivative works, public display, public * performance, distribution or sublicensing of Refinement Analysis * Tools and derivative works, in source code and object code form. * This agreement not to assert does not confer, by implication, * estoppel, or otherwise any license or rights in any intellectual * property of Regents, including, but not limited to, any patents * of Regents or Regents' employees. * * IN NO EVENT SHALL REGENTS BE LIABLE TO ANY PARTY FOR DIRECT, * INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, * INCLUDING LOST PROFITS, ARISING OUT OF THE USE OF THIS SOFTWARE * AND ITS DOCUMENTATION, EVEN IF REGENTS HAS BEEN ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * REGENTS SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE AND FURTHER DISCLAIMS ANY STATUTORY * WARRANTY OF NON-INFRINGEMENT. THE SOFTWARE AND ACCOMPANYING * DOCUMENTATION, IF ANY, PROVIDED HEREUNDER IS PROVIDED "AS * IS". REGENTS HAS NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, * UPDATES, ENHANCEMENTS, OR MODIFICATIONS. */ package com.ibm.wala.demandpa.flowgraph; import com.ibm.wala.classLoader.ArrayClass; import com.ibm.wala.classLoader.IClass; import com.ibm.wala.classLoader.IField; import com.ibm.wala.classLoader.ProgramCounter; import com.ibm.wala.demandpa.util.ArrayContents; import com.ibm.wala.demandpa.util.MemoryAccessMap; import com.ibm.wala.ipa.callgraph.CGNode; import com.ibm.wala.ipa.callgraph.CallGraph; import com.ibm.wala.ipa.callgraph.propagation.FilteredPointerKey; import com.ibm.wala.ipa.callgraph.propagation.HeapModel; import com.ibm.wala.ipa.callgraph.propagation.InstanceKey; import com.ibm.wala.ipa.callgraph.propagation.PointerKey; import com.ibm.wala.ipa.callgraph.propagation.SSAPropagationCallGraphBuilder; import com.ibm.wala.ipa.cha.ClassHierarchy; import com.ibm.wala.ssa.IR; import com.ibm.wala.ssa.ISSABasicBlock; import com.ibm.wala.ssa.SSAAbstractInvokeInstruction; import com.ibm.wala.ssa.SSAArrayLengthInstruction; import com.ibm.wala.ssa.SSAArrayLoadInstruction; import com.ibm.wala.ssa.SSAArrayStoreInstruction; import com.ibm.wala.ssa.SSABinaryOpInstruction; import com.ibm.wala.ssa.SSACheckCastInstruction; import com.ibm.wala.ssa.SSAComparisonInstruction; import com.ibm.wala.ssa.SSAConversionInstruction; import com.ibm.wala.ssa.SSAGetCaughtExceptionInstruction; import com.ibm.wala.ssa.SSAGetInstruction; import com.ibm.wala.ssa.SSAInstanceofInstruction; import com.ibm.wala.ssa.SSAInstruction; import com.ibm.wala.ssa.SSAInstruction.Visitor; import com.ibm.wala.ssa.SSAInvokeInstruction; import com.ibm.wala.ssa.SSALoadMetadataInstruction; import com.ibm.wala.ssa.SSANewInstruction; import com.ibm.wala.ssa.SSAPiInstruction; import com.ibm.wala.ssa.SSAPutInstruction; import com.ibm.wala.ssa.SSAReturnInstruction; import com.ibm.wala.ssa.SSAThrowInstruction; import com.ibm.wala.ssa.SSAUnaryOpInstruction; import com.ibm.wala.ssa.SymbolTable; import com.ibm.wala.types.FieldReference; import com.ibm.wala.types.TypeReference; import com.ibm.wala.util.collections.HashSetFactory; import com.ibm.wala.util.collections.MapUtil; import com.ibm.wala.util.debug.Assertions; import java.util.List; import java.util.Set; /** * A flow graph including both pointer and primitive values. * * <p>TODO share more code with {@link DemandPointerFlowGraph} * * @author Manu Sridharan */ public class DemandValueFlowGraph extends AbstractDemandFlowGraph { /** */ private static final long serialVersionUID = 1L; public DemandValueFlowGraph( CallGraph cg, HeapModel heapModel, MemoryAccessMap mam, ClassHierarchy cha) { super(cg, heapModel, mam, cha); } @Override protected void addNodesForParameters(CGNode node, IR ir) { SymbolTable symbolTable = ir.getSymbolTable(); int numParams = symbolTable.getNumberOfParameters(); for (int i = 0; i < numParams; i++) { int parameter = symbolTable.getParameter(i); PointerKey paramPk = heapModel.getPointerKeyForLocal(node, parameter); addNode(paramPk); params.put(paramPk, node); } PointerKey returnKey = heapModel.getPointerKeyForReturnValue(node); addNode(returnKey); returns.put(returnKey, node); PointerKey exceptionReturnKey = heapModel.getPointerKeyForExceptionalReturnValue(node); addNode(exceptionReturnKey); returns.put(exceptionReturnKey, node); } @Override protected FlowStatementVisitor makeVisitor(CGNode node) { return new AllValsStatementVisitor(node); } private class AllValsStatementVisitor extends Visitor implements FlowStatementVisitor { /** The node whose statements we are currently traversing */ protected final CGNode node; /** The governing IR */ protected final IR ir; /** The basic block currently being processed */ private ISSABasicBlock basicBlock; /** Governing symbol table */ protected final SymbolTable symbolTable; public AllValsStatementVisitor(CGNode node) { this.node = node; this.ir = node.getIR(); this.symbolTable = ir.getSymbolTable(); assert symbolTable != null; } @Override public void visitArrayLoad(SSAArrayLoadInstruction instruction) { PointerKey result = heapModel.getPointerKeyForLocal(node, instruction.getDef()); PointerKey arrayRef = heapModel.getPointerKeyForLocal(node, instruction.getArrayRef()); // TODO optimizations for purely local stuff addNode(result); addNode(arrayRef); addEdge(result, arrayRef, GetFieldLabel.make(ArrayContents.v())); } @Override public void visitArrayStore(SSAArrayStoreInstruction instruction) { // make node for used value PointerKey value = heapModel.getPointerKeyForLocal(node, instruction.getValue()); PointerKey arrayRef = heapModel.getPointerKeyForLocal(node, instruction.getArrayRef()); // TODO purely local optimizations addNode(value); addNode(arrayRef); addEdge(arrayRef, value, PutFieldLabel.make(ArrayContents.v())); } @Override public void visitCheckCast(SSACheckCastInstruction instruction) { Set<IClass> types = HashSetFactory.make(); for (TypeReference t : instruction.getDeclaredResultTypes()) { IClass cls = cha.lookupClass(t); if (cls == null) { return; } else { types.add(cls); } } PointerKey result = heapModel.getFilteredPointerKeyForLocal( node, instruction.getResult(), new FilteredPointerKey.MultipleClassesFilter(types.toArray(new IClass[0]))); PointerKey value = heapModel.getPointerKeyForLocal(node, instruction.getVal()); addNode(result); addNode(value); addEdge(result, value, AssignLabel.noFilter()); } @Override public void visitReturn(SSAReturnInstruction instruction) { // skip returns of primitive type if (instruction.returnsVoid()) { return; } else { // just make a node for the def'd value PointerKey def = heapModel.getPointerKeyForLocal(node, instruction.getResult()); addNode(def); PointerKey returnValue = heapModel.getPointerKeyForReturnValue(node); addNode(returnValue); addEdge(returnValue, def, AssignLabel.noFilter()); } } @Override public void visitGet(SSAGetInstruction instruction) { visitGetInternal( instruction.getDef(), instruction.getRef(), instruction.isStatic(), instruction.getDeclaredField()); } protected void visitGetInternal(int lval, int ref, boolean isStatic, FieldReference field) { IField f = cg.getClassHierarchy().resolveField(field); if (f == null) { return; } PointerKey def = heapModel.getPointerKeyForLocal(node, lval); assert def != null; if (isStatic) { PointerKey fKey = heapModel.getPointerKeyForStaticField(f); addNode(def); addNode(fKey); // TODO assign global edge for context-sensitive addEdge(def, fKey, AssignGlobalLabel.v()); } else { PointerKey refKey = heapModel.getPointerKeyForLocal(node, ref); addNode(def); addNode(refKey); // TODO purely local optimizations addEdge(def, refKey, GetFieldLabel.make(f)); } } @Override public void visitPut(SSAPutInstruction instruction) { visitPutInternal( instruction.getVal(), instruction.getRef(), instruction.isStatic(), instruction.getDeclaredField()); } public void visitPutInternal(int rval, int ref, boolean isStatic, FieldReference field) { IField f = cg.getClassHierarchy().resolveField(field); if (f == null) { return; } PointerKey use = heapModel.getPointerKeyForLocal(node, rval); assert use != null; if (isStatic) { PointerKey fKey = heapModel.getPointerKeyForStaticField(f); addNode(use); addNode(fKey); // TODO assign global edge addEdge(fKey, use, AssignGlobalLabel.v()); } else { PointerKey refKey = heapModel.getPointerKeyForLocal(node, ref); addNode(use); addNode(refKey); addEdge(refKey, use, PutFieldLabel.make(f)); } } @Override public void visitInvoke(SSAInvokeInstruction instruction) { for (int i = 0; i < instruction.getNumberOfUses(); i++) { // just make nodes for parameters; we'll get to them when // traversing // from the callee PointerKey use = heapModel.getPointerKeyForLocal(node, instruction.getUse(i)); addNode(use); Set<SSAAbstractInvokeInstruction> s = MapUtil.findOrCreateSet(callParams, use); s.add(instruction); } // for any def'd values, keep track of the fact that they are def'd // by a call if (instruction.hasDef()) { PointerKey def = heapModel.getPointerKeyForLocal(node, instruction.getDef()); addNode(def); callDefs.put(def, instruction); } PointerKey exc = heapModel.getPointerKeyForLocal(node, instruction.getException()); addNode(exc); callDefs.put(exc, instruction); } @Override public void visitNew(SSANewInstruction instruction) { InstanceKey iKey = heapModel.getInstanceKeyForAllocation(node, instruction.getNewSite()); if (iKey == null) { // something went wrong. I hope someone raised a warning. return; } PointerKey def = heapModel.getPointerKeyForLocal(node, instruction.getDef()); addNode(iKey); addNode(def); addEdge(def, iKey, NewLabel.v()); IClass klass = iKey.getConcreteType(); int dim = 0; InstanceKey lastInstance = iKey; PointerKey lastVar = def; while (klass != null && klass.isArrayClass()) { klass = ((ArrayClass) klass).getElementClass(); // klass == null means it's a primitive if (klass != null && klass.isArrayClass()) { InstanceKey ik = heapModel.getInstanceKeyForMultiNewArray(node, instruction.getNewSite(), dim); PointerKey pk = heapModel.getPointerKeyForArrayContents(lastInstance); addNode(ik); addNode(pk); addEdge(pk, ik, NewLabel.v()); addEdge(lastVar, pk, PutFieldLabel.make(ArrayContents.v())); lastInstance = ik; lastVar = pk; dim++; } } } /* * (non-Javadoc) * * @see com.ibm.wala.Instruction.Visitor#visitThrow(com.ibm.wala.ThrowInstruction) */ @Override public void visitThrow(SSAThrowInstruction instruction) { // don't do anything: we handle exceptional edges // in a separate pass } @Override public void visitGetCaughtException(SSAGetCaughtExceptionInstruction instruction) { List<ProgramCounter> peis = SSAPropagationCallGraphBuilder.getIncomingPEIs(ir, getBasicBlock()); PointerKey def = heapModel.getPointerKeyForLocal(node, instruction.getDef()); Set<IClass> types = SSAPropagationCallGraphBuilder.getCaughtExceptionTypes(instruction, ir); addExceptionDefConstraints(ir, node, peis, def, types); } @Override public void visitPi(SSAPiInstruction instruction) { PointerKey src = heapModel.getPointerKeyForLocal(node, instruction.getDef()); PointerKey dst = heapModel.getPointerKeyForLocal(node, instruction.getVal()); addNode(src); addNode(dst); addEdge(src, dst, AssignLabel.noFilter()); } private void handleNonHeapInstruction(SSAInstruction instruction) { for (int i = 0; i < instruction.getNumberOfDefs(); i++) { int def = instruction.getDef(i); PointerKey defPk = heapModel.getPointerKeyForLocal(node, def); addNode(defPk); for (int j = 0; j < instruction.getNumberOfUses(); j++) { int use = instruction.getUse(j); PointerKey usePk = heapModel.getPointerKeyForLocal(node, use); addNode(usePk); addEdge(defPk, usePk, AssignLabel.noFilter()); } } } @Override public void visitArrayLength(SSAArrayLengthInstruction instruction) { handleNonHeapInstruction(instruction); } @Override public void visitBinaryOp(SSABinaryOpInstruction instruction) { handleNonHeapInstruction(instruction); } @Override public void visitComparison(SSAComparisonInstruction instruction) { handleNonHeapInstruction(instruction); } @Override public void visitConversion(SSAConversionInstruction instruction) { handleNonHeapInstruction(instruction); } @Override public void visitInstanceof(SSAInstanceofInstruction instruction) { handleNonHeapInstruction(instruction); } @Override public void visitUnaryOp(SSAUnaryOpInstruction instruction) { handleNonHeapInstruction(instruction); } public ISSABasicBlock getBasicBlock() { return basicBlock; } /** The calling loop must call this in each iteration! */ @Override public void setBasicBlock(ISSABasicBlock block) { basicBlock = block; } @Override public void visitLoadMetadata(SSALoadMetadataInstruction instruction) { Assertions.UNREACHABLE(); } } }
15,205
34.947991
98
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/demandpa/flowgraph/GetFieldBarLabel.java
/* * This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html. * * This file is a derivative of code released by the University of * California under the terms listed below. * * Refinement Analysis Tools is Copyright (c) 2007 The Regents of the * University of California (Regents). Provided that this notice and * the following two paragraphs are included in any distribution of * Refinement Analysis Tools or its derivative work, Regents agrees * not to assert any of Regents' copyright rights in Refinement * Analysis Tools against recipient for recipient's reproduction, * preparation of derivative works, public display, public * performance, distribution or sublicensing of Refinement Analysis * Tools and derivative works, in source code and object code form. * This agreement not to assert does not confer, by implication, * estoppel, or otherwise any license or rights in any intellectual * property of Regents, including, but not limited to, any patents * of Regents or Regents' employees. * * IN NO EVENT SHALL REGENTS BE LIABLE TO ANY PARTY FOR DIRECT, * INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, * INCLUDING LOST PROFITS, ARISING OUT OF THE USE OF THIS SOFTWARE * AND ITS DOCUMENTATION, EVEN IF REGENTS HAS BEEN ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * REGENTS SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE AND FURTHER DISCLAIMS ANY STATUTORY * WARRANTY OF NON-INFRINGEMENT. THE SOFTWARE AND ACCOMPANYING * DOCUMENTATION, IF ANY, PROVIDED HEREUNDER IS PROVIDED "AS * IS". REGENTS HAS NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, * UPDATES, ENHANCEMENTS, OR MODIFICATIONS. */ package com.ibm.wala.demandpa.flowgraph; import com.ibm.wala.classLoader.IField; /** @author Manu Sridharan */ public class GetFieldBarLabel implements IFlowLabel { private final IField field; private GetFieldBarLabel(final IField field) { this.field = field; } public static GetFieldBarLabel make(IField field) { // TODO cache these? return new GetFieldBarLabel(field); } public IField getField() { return field; } /* * (non-Javadoc) * * @see demandGraph.IFlowLabel#bar() */ @Override public GetFieldLabel bar() { return GetFieldLabel.make(field); } /* * (non-Javadoc) * * @see demandGraph.IFlowLabel#visit(demandGraph.IFlowLabel.IFlowLabelVisitor, * java.lang.Object) */ @Override public void visit(IFlowLabelVisitor v, Object dst) throws IllegalArgumentException { if (v == null) { throw new IllegalArgumentException("v == null"); } v.visitGetFieldBar(this, dst); } @Override public int hashCode() { final int PRIME = 31; int result = 1; result = PRIME * result + ((field == null) ? 0 : field.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 GetFieldBarLabel other = (GetFieldBarLabel) obj; if (field == null) { if (other.field != null) return false; } else if (!field.equals(other.field)) return false; return true; } @Override public boolean isBarred() { return true; } }
3,520
31.302752
86
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/demandpa/flowgraph/GetFieldLabel.java
/* * This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html. * * This file is a derivative of code released by the University of * California under the terms listed below. * * Refinement Analysis Tools is Copyright (c) 2007 The Regents of the * University of California (Regents). Provided that this notice and * the following two paragraphs are included in any distribution of * Refinement Analysis Tools or its derivative work, Regents agrees * not to assert any of Regents' copyright rights in Refinement * Analysis Tools against recipient for recipient's reproduction, * preparation of derivative works, public display, public * performance, distribution or sublicensing of Refinement Analysis * Tools and derivative works, in source code and object code form. * This agreement not to assert does not confer, by implication, * estoppel, or otherwise any license or rights in any intellectual * property of Regents, including, but not limited to, any patents * of Regents or Regents' employees. * * IN NO EVENT SHALL REGENTS BE LIABLE TO ANY PARTY FOR DIRECT, * INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, * INCLUDING LOST PROFITS, ARISING OUT OF THE USE OF THIS SOFTWARE * AND ITS DOCUMENTATION, EVEN IF REGENTS HAS BEEN ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * REGENTS SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE AND FURTHER DISCLAIMS ANY STATUTORY * WARRANTY OF NON-INFRINGEMENT. THE SOFTWARE AND ACCOMPANYING * DOCUMENTATION, IF ANY, PROVIDED HEREUNDER IS PROVIDED "AS * IS". REGENTS HAS NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, * UPDATES, ENHANCEMENTS, OR MODIFICATIONS. */ package com.ibm.wala.demandpa.flowgraph; import com.ibm.wala.classLoader.IField; public class GetFieldLabel implements IFlowLabel { private final IField field; private GetFieldLabel(final IField field) { this.field = field; } public static GetFieldLabel make(IField field) { // TODO cache these? return new GetFieldLabel(field); } public IField getField() { return field; } @Override public int hashCode() { final int PRIME = 31; int result = 1; result = PRIME * result + ((field == null) ? 0 : field.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 GetFieldLabel other = (GetFieldLabel) obj; if (field == null) { if (other.field != null) return false; } else if (!field.equals(other.field)) return false; return true; } @Override public void visit(IFlowLabelVisitor v, Object dst) throws IllegalArgumentException { if (v == null) { throw new IllegalArgumentException("v == null"); } v.visitGetField(this, dst); } @Override public String toString() { return "getfield[" + field + ']'; } @Override public GetFieldBarLabel bar() { return GetFieldBarLabel.make(field); } @Override public boolean isBarred() { return false; } }
3,342
31.77451
86
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/demandpa/flowgraph/IFlowGraph.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.demandpa.flowgraph; import com.ibm.wala.classLoader.CallSiteReference; import com.ibm.wala.classLoader.IField; import com.ibm.wala.demandpa.flowgraph.IFlowLabel.IFlowLabelVisitor; import com.ibm.wala.ipa.callgraph.CGNode; import com.ibm.wala.ipa.callgraph.propagation.LocalPointerKey; import com.ibm.wala.ipa.callgraph.propagation.PointerKey; import com.ibm.wala.ipa.callgraph.propagation.StaticFieldKey; import com.ibm.wala.ipa.callgraph.propagation.cfa.CallerSiteContext; import com.ibm.wala.ssa.SSAAbstractInvokeInstruction; import com.ibm.wala.ssa.SSAInvokeInstruction; import com.ibm.wala.util.graph.labeled.LabeledGraph; import java.util.Iterator; import java.util.Set; public interface IFlowGraph extends LabeledGraph<Object, IFlowLabel> { /** Apply a visitor to the successors of some node. */ void visitSuccs(Object node, IFlowLabelVisitor v); /** Apply a visitor to the predecessors of some node. */ void visitPreds(Object node, IFlowLabelVisitor v); /** * add representation of flow for a node, if not already present * * @throws IllegalArgumentException if node == null */ void addSubgraphForNode(CGNode node) throws IllegalArgumentException; boolean hasSubgraphForNode(CGNode node); /** @return {@code true} iff {@code pk} is a formal parameter */ boolean isParam(LocalPointerKey pk); /** @return the {@link SSAInvokeInstruction}s passing some pointer as a parameter */ Iterator<SSAAbstractInvokeInstruction> getInstrsPassingParam(LocalPointerKey pk); /** * get the {@link SSAInvokeInstruction} whose return value is assigned to a pointer key. * * @return the instruction, or {@code null} if no return value is assigned to pk */ SSAAbstractInvokeInstruction getInstrReturningTo(LocalPointerKey pk); /** * @param sfk the static field * @return all the variables whose values are written to sfk * @throws IllegalArgumentException if sfk == null */ Iterator<? extends Object> getWritesToStaticField(StaticFieldKey sfk) throws IllegalArgumentException; /** * @param sfk the static field * @return all the variables that get the value of sfk * @throws IllegalArgumentException if sfk == null */ Iterator<? extends Object> getReadsOfStaticField(StaticFieldKey sfk) throws IllegalArgumentException; Iterator<PointerKey> getWritesToInstanceField(PointerKey pk, IField f); Iterator<PointerKey> getReadsOfInstanceField(PointerKey pk, IField f); /** * @param formalPk a {@link PointerKey} representing either a formal parameter or return value * @return the {@link CallerSiteContext}s representing pointer callers of {@code formalPk}'s * method */ Set<CallerSiteContext> getPotentialCallers(PointerKey formalPk); /** * get the callees that should be considered at a particular call site * * @param caller the caller * @param site the call site * @param actualPk a {@link LocalPointerKey} corresponding to the actual parameter or return value * of interest. This may be used to filter out certain callees. * @return the callees of interest */ Set<CGNode> getPossibleTargets(CGNode caller, CallSiteReference site, LocalPointerKey actualPk); }
3,597
36.873684
100
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/demandpa/flowgraph/IFlowLabel.java
/* * This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html. * * This file is a derivative of code released by the University of * California under the terms listed below. * * Refinement Analysis Tools is Copyright (c) 2007 The Regents of the * University of California (Regents). Provided that this notice and * the following two paragraphs are included in any distribution of * Refinement Analysis Tools or its derivative work, Regents agrees * not to assert any of Regents' copyright rights in Refinement * Analysis Tools against recipient for recipient's reproduction, * preparation of derivative works, public display, public * performance, distribution or sublicensing of Refinement Analysis * Tools and derivative works, in source code and object code form. * This agreement not to assert does not confer, by implication, * estoppel, or otherwise any license or rights in any intellectual * property of Regents, including, but not limited to, any patents * of Regents or Regents' employees. * * IN NO EVENT SHALL REGENTS BE LIABLE TO ANY PARTY FOR DIRECT, * INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, * INCLUDING LOST PROFITS, ARISING OUT OF THE USE OF THIS SOFTWARE * AND ITS DOCUMENTATION, EVEN IF REGENTS HAS BEEN ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * REGENTS SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE AND FURTHER DISCLAIMS ANY STATUTORY * WARRANTY OF NON-INFRINGEMENT. THE SOFTWARE AND ACCOMPANYING * DOCUMENTATION, IF ANY, PROVIDED HEREUNDER IS PROVIDED "AS * IS". REGENTS HAS NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, * UPDATES, ENHANCEMENTS, OR MODIFICATIONS. */ package com.ibm.wala.demandpa.flowgraph; /** * An edge label in a flow graph * * @author manu */ public interface IFlowLabel { void visit(IFlowLabelVisitor v, Object dst); /** @return the bar (inverse) edge corresponding to this edge */ IFlowLabel bar(); interface IFlowLabelVisitor { void visitAssignGlobal(AssignGlobalLabel label, Object dst); void visitAssign(AssignLabel label, Object dst); void visitGetField(GetFieldLabel label, Object dst); void visitMatch(MatchLabel label, Object dst); void visitNew(NewLabel label, Object dst); void visitPutField(PutFieldLabel label, Object dst); void visitParam(ParamLabel label, Object dst); void visitReturn(ReturnLabel label, Object dst); void visitAssignGlobalBar(AssignGlobalBarLabel label, Object dst); void visitAssignBar(AssignBarLabel label, Object dst); void visitGetFieldBar(GetFieldBarLabel label, Object dst); void visitMatchBar(MatchBarLabel label, Object dst); void visitNewBar(NewBarLabel label, Object dst); void visitPutFieldBar(PutFieldBarLabel label, Object dst); void visitReturnBar(ReturnBarLabel label, Object dst); void visitParamBar(ParamBarLabel label, Object dst); } /** @return true if this is a "barred" edge */ boolean isBarred(); }
3,229
34.888889
72
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/demandpa/flowgraph/IFlowLabelWithFilter.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.demandpa.flowgraph; import com.ibm.wala.ipa.callgraph.propagation.FilteredPointerKey.TypeFilter; public interface IFlowLabelWithFilter extends IFlowLabel { TypeFilter getFilter(); }
576
29.368421
76
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/demandpa/flowgraph/MatchBarLabel.java
/* * This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html. * * This file is a derivative of code released by the University of * California under the terms listed below. * * Refinement Analysis Tools is Copyright (c) 2007 The Regents of the * University of California (Regents). Provided that this notice and * the following two paragraphs are included in any distribution of * Refinement Analysis Tools or its derivative work, Regents agrees * not to assert any of Regents' copyright rights in Refinement * Analysis Tools against recipient for recipient's reproduction, * preparation of derivative works, public display, public * performance, distribution or sublicensing of Refinement Analysis * Tools and derivative works, in source code and object code form. * This agreement not to assert does not confer, by implication, * estoppel, or otherwise any license or rights in any intellectual * property of Regents, including, but not limited to, any patents * of Regents or Regents' employees. * * IN NO EVENT SHALL REGENTS BE LIABLE TO ANY PARTY FOR DIRECT, * INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, * INCLUDING LOST PROFITS, ARISING OUT OF THE USE OF THIS SOFTWARE * AND ITS DOCUMENTATION, EVEN IF REGENTS HAS BEEN ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * REGENTS SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE AND FURTHER DISCLAIMS ANY STATUTORY * WARRANTY OF NON-INFRINGEMENT. THE SOFTWARE AND ACCOMPANYING * DOCUMENTATION, IF ANY, PROVIDED HEREUNDER IS PROVIDED "AS * IS". REGENTS HAS NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, * UPDATES, ENHANCEMENTS, OR MODIFICATIONS. */ package com.ibm.wala.demandpa.flowgraph; /** @author Manu Sridharan */ public class MatchBarLabel implements IFlowLabel { private static final MatchBarLabel theInstance = new MatchBarLabel(); private MatchBarLabel() {} public static MatchBarLabel v() { return theInstance; } @Override public MatchLabel bar() { return MatchLabel.v(); } @Override public void visit(IFlowLabelVisitor v, Object dst) throws IllegalArgumentException { if (v == null) { throw new IllegalArgumentException("v == null"); } v.visitMatchBar(this, dst); } @Override public boolean isBarred() { return true; } }
2,565
36.188406
86
java