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/demandpa/flowgraph/MatchLabel.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 MatchLabel implements IFlowLabel { private static final MatchLabel theInstance = new MatchLabel(); private MatchLabel() {} public static MatchLabel v() { return theInstance; } @Override public void visit(IFlowLabelVisitor v, Object dst) throws IllegalArgumentException { if (v == null) { throw new IllegalArgumentException("v == null"); } v.visitMatch(this, dst); } @Override public String toString() { return "match"; } @Override public MatchBarLabel bar() { return MatchBarLabel.v(); } @Override public boolean isBarred() { return false; } }
2,590
34.493151
86
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/demandpa/flowgraph/NewBarLabel.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 NewBarLabel implements IFlowLabel { private static final NewBarLabel theInstance = new NewBarLabel(); private NewBarLabel() {} public static NewBarLabel v() { return theInstance; } @Override public NewLabel bar() { return NewLabel.v(); } @Override public void visit(IFlowLabelVisitor v, Object dst) throws IllegalArgumentException { if (v == null) { throw new IllegalArgumentException("v == null"); } v.visitNewBar(this, dst); } @Override public boolean isBarred() { return true; } }
2,549
35.956522
86
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/demandpa/flowgraph/NewLabel.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 NewLabel implements IFlowLabel { private static final NewLabel theInstance = new NewLabel(); private NewLabel() {} public static NewLabel v() { return theInstance; } @Override public void visit(IFlowLabelVisitor v, Object dst) throws IllegalArgumentException { if (v == null) { throw new IllegalArgumentException("v == null"); } v.visitNew(this, dst); } @Override public String toString() { return "new"; } @Override public NewBarLabel bar() { return NewBarLabel.v(); } @Override public boolean isBarred() { return false; } }
2,572
34.246575
86
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/demandpa/flowgraph/ParamBarLabel.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 class ParamBarLabel extends CallLabel { private ParamBarLabel(CallerSiteContext callSite) { super(callSite); } public static ParamBarLabel make(CallerSiteContext callSite) { return new ParamBarLabel(callSite); } @Override public ParamLabel bar() { return ParamLabel.make(callSite); } @Override public void visit(IFlowLabelVisitor v, Object dst) throws IllegalArgumentException { if (v == null) { throw new IllegalArgumentException("v == null"); } v.visitParamBar(this, dst); } @Override public boolean isBarred() { return true; } @Override public String toString() { return "paramBar[" + callSite + ']'; } }
2,728
34.907895
86
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/demandpa/flowgraph/ParamLabel.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 class ParamLabel extends CallLabel { private ParamLabel(CallerSiteContext callSite) { super(callSite); } public static ParamLabel make(CallerSiteContext callSite) { return new ParamLabel(callSite); } @Override public void visit(IFlowLabelVisitor v, Object dst) throws IllegalArgumentException { if (v == null) { throw new IllegalArgumentException("v == null"); } v.visitParam(this, dst); } @Override public String toString() { return "param[" + callSite + ']'; } @Override public ParamBarLabel bar() { return ParamBarLabel.make(callSite); } @Override public boolean isBarred() { return false; } }
2,710
35.146667
86
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/demandpa/flowgraph/PointerKeyAndCallSite.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.ipa.callgraph.propagation.PointerKey; public class PointerKeyAndCallSite { private final PointerKey key; private final CallSiteReference callSiteRef; public PointerKeyAndCallSite(final PointerKey key, final CallSiteReference callSiteRef) { if (key == null) { throw new IllegalArgumentException("null key"); } if (callSiteRef == null) { throw new IllegalArgumentException("null callSiteRef"); } this.key = key; this.callSiteRef = callSiteRef; } public CallSiteReference getCallSiteRef() { return callSiteRef; } public PointerKey getKey() { return key; } @Override public int hashCode() { final int PRIME = 31; int result = 1; result = PRIME * result + callSiteRef.hashCode(); result = PRIME * result + key.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 PointerKeyAndCallSite other = (PointerKeyAndCallSite) obj; if (!callSiteRef.equals(other.callSiteRef)) return false; if (!key.equals(other.key)) return false; return true; } }
3,230
35.715909
91
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/demandpa/flowgraph/PutFieldBarLabel.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 PutFieldBarLabel implements IFlowLabel { private final IField 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 PutFieldBarLabel other = (PutFieldBarLabel) obj; if (field == null) { if (other.field != null) return false; } else if (!field.equals(other.field)) return false; return true; } private PutFieldBarLabel(final IField field) { this.field = field; } public static PutFieldBarLabel make(IField field) { // TODO cache these? return new PutFieldBarLabel(field); } public IField getField() { return field; } @Override public PutFieldLabel bar() { return PutFieldLabel.make(field); } @Override public void visit(IFlowLabelVisitor v, Object dst) throws IllegalArgumentException { if (v == null) { throw new IllegalArgumentException("v == null"); } v.visitPutFieldBar(this, dst); } @Override public boolean isBarred() { return true; } @Override public String toString() { return "putfield_bar[" + field + ']'; } }
3,390
31.92233
86
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/demandpa/flowgraph/PutFieldLabel.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 PutFieldLabel implements IFlowLabel { private final IField field; private PutFieldLabel(final IField field) { this.field = field; } public static PutFieldLabel make(IField field) { // TODO cache these? return new PutFieldLabel(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 PutFieldLabel other = (PutFieldLabel) 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.visitPutField(this, dst); } @Override public String toString() { return "putfield[" + field + ']'; } @Override public PutFieldBarLabel bar() { return PutFieldBarLabel.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/ReturnBarLabel.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 class ReturnBarLabel extends CallLabel { private ReturnBarLabel(CallerSiteContext callSite) { super(callSite); } public static ReturnBarLabel make(CallerSiteContext callSite) { return new ReturnBarLabel(callSite); } @Override public ReturnLabel bar() { return ReturnLabel.make(callSite); } @Override public void visit(IFlowLabelVisitor v, Object dst) throws IllegalArgumentException { if (v == null) { throw new IllegalArgumentException("v == null"); } v.visitReturnBar(this, dst); } @Override public boolean isBarred() { return true; } @Override public String toString() { return "returnBar[" + callSite + ']'; } }
2,736
35.013158
86
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/demandpa/flowgraph/ReturnLabel.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 class ReturnLabel extends CallLabel { private ReturnLabel(CallerSiteContext callSite) { super(callSite); } public static ReturnLabel make(CallerSiteContext callSite) { return new ReturnLabel(callSite); } @Override public void visit(IFlowLabelVisitor v, Object dst) throws IllegalArgumentException { if (v == null) { throw new IllegalArgumentException("v == null"); } v.visitReturn(this, dst); } @Override public String toString() { return "return[" + callSite + ']'; } @Override public ReturnBarLabel bar() { return ReturnBarLabel.make(callSite); } @Override public boolean isBarred() { return false; } }
2,718
35.253333
86
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/demandpa/flowgraph/SimpleDemandPointerFlowGraph.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.analysis.typeInference.TypeAbstraction; import com.ibm.wala.analysis.typeInference.TypeInference; import com.ibm.wala.cfg.ControlFlowGraph; 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.core.util.ref.ReferenceCleanser; 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.impl.ExplicitCallGraph; 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.LocalPointerKey; 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.callgraph.propagation.StaticFieldKey; import com.ibm.wala.ipa.cha.IClassHierarchy; 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.SSAPhiInstruction; import com.ibm.wala.ssa.SSAPiInstruction; import com.ibm.wala.ssa.SSAPutInstruction; import com.ibm.wala.ssa.SSAReturnInstruction; import com.ibm.wala.ssa.SSAThrowInstruction; import com.ibm.wala.ssa.SymbolTable; import com.ibm.wala.types.FieldReference; import com.ibm.wala.types.TypeReference; import com.ibm.wala.util.collections.HashMapFactory; import com.ibm.wala.util.collections.HashSetFactory; import com.ibm.wala.util.collections.Iterator2Iterable; import com.ibm.wala.util.debug.Assertions; import com.ibm.wala.util.debug.UnimplementedError; import com.ibm.wala.util.graph.impl.SlowSparseNumberedGraph; import com.ibm.wala.util.intset.BitVectorIntSet; import com.ibm.wala.util.intset.IntSet; import java.util.Collection; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; /** * The nodes in this graph are PointerKeys corresponding to local variables and static fields, * InstanceKeys, and FieldRefs (see below). * * <p>This graph is constructed on-demand during a traversal. * * <p>The edges represent * * <ul> * <li>flow from local -&gt; local representing assignment (i.e. phi,pi) * <li>flow from instancekey -&gt; local for news * <li>flow from formal -&gt; actual parameter * <li>flow from return value -&gt; local * <li>match edges * <li>local -&gt; local edges representing loads/stores (e.g. x = y.f will have a edge x-&gt;y, * labelled with f) for a getstatic x = Y.f, we have an edge from x -&gt; Y.f. * </ul> * * N.B: Edges go OPPOSITE the flow of values. * * <p>Edges carry labels if they arise from loads/stores, or calls */ public class SimpleDemandPointerFlowGraph extends SlowSparseNumberedGraph<Object> { private static final long serialVersionUID = 5208052568163692029L; private static final boolean DEBUG = false; /** Counter for wiping soft caches */ private static int wipeCount = 0; private final CallGraph cg; private final HeapModel heapModel; private final MemoryAccessMap fam; private final IClassHierarchy cha; /** node numbers of CGNodes we have already visited */ final BitVectorIntSet cgNodesVisited = new BitVectorIntSet(); /** * Map: LocalPointerKey -&gt; IField. if we have (x,f), that means x was def'fed by a getfield on * f. */ final Map<PointerKey, IField> getFieldDefs = HashMapFactory.make(); final Collection<PointerKey> arrayDefs = HashSetFactory.make(); /** * Map: LocalPointerKey -&gt; SSAInvokeInstruction. If we have (x, foo()), that means that x was * def'fed by the return value from a call to foo() */ final Map<PointerKey, SSAInvokeInstruction> callDefs = 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. */ final Map<PointerKey, CGNode> params = HashMapFactory.make(); public SimpleDemandPointerFlowGraph( CallGraph cg, HeapModel heapModel, MemoryAccessMap fam, IClassHierarchy cha) { super(); if (cg == null) { throw new IllegalArgumentException("null cg"); } this.cg = cg; this.heapModel = heapModel; this.fam = fam; this.cha = cha; } public void addSubgraphForNode(CGNode node) { int n = cg.getNumber(node); if (!cgNodesVisited.contains(n)) { cgNodesVisited.add(n); unconditionallyAddConstraintsFromNode(node); addNodesForParameters(node); } } /** add nodes for parameters and return values */ private void addNodesForParameters(CGNode node) { // TODO Auto-generated method stub IR ir = node.getIR(); TypeInference ti = TypeInference.make(ir, false); SymbolTable symbolTable = ir.getSymbolTable(); for (int i = 0; i < symbolTable.getNumberOfParameters(); i++) { int parameter = symbolTable.getParameter(i); TypeAbstraction t = ti.getType(parameter); if (t != null) { PointerKey paramPk = heapModel.getPointerKeyForLocal(node, parameter); addNode(paramPk); params.put(paramPk, node); } } addNode(heapModel.getPointerKeyForReturnValue(node)); addNode(heapModel.getPointerKeyForExceptionalReturnValue(node)); } /** @return Returns the heapModel. */ protected HeapModel getHeapModel() { return heapModel; } /** @see com.ibm.wala.util.graph.AbstractNumberedGraph#getPredNodeNumbers(java.lang.Object) */ @Override public IntSet getPredNodeNumbers(Object node) throws UnimplementedError { if (node instanceof StaticFieldKey) { Assertions.UNREACHABLE(); return null; } else { return super.getPredNodeNumbers(node); } } /** @see com.ibm.wala.util.graph.AbstractNumberedGraph#getSuccNodeNumbers(java.lang.Object) */ @Override public IntSet getSuccNodeNumbers(Object node) throws IllegalArgumentException { if (node instanceof com.ibm.wala.ipa.callgraph.propagation.StaticFieldKey) { throw new IllegalArgumentException( "node instanceof com.ibm.wala.ipa.callgraph.propagation.StaticFieldKey"); } return super.getSuccNodeNumbers(node); } /** @see com.ibm.wala.util.graph.AbstractGraph#getPredNodeCount(java.lang.Object) */ @Override public int getPredNodeCount(Object N) throws UnimplementedError { if (N instanceof StaticFieldKey) { Assertions.UNREACHABLE(); return -1; } else { return super.getPredNodeCount(N); } } /** @see com.ibm.wala.util.graph.AbstractGraph#getPredNodes(java.lang.Object) */ @Override public Iterator<Object> getPredNodes(Object N) throws IllegalArgumentException { if (N instanceof com.ibm.wala.ipa.callgraph.propagation.StaticFieldKey) { throw new IllegalArgumentException( "N instanceof com.ibm.wala.ipa.callgraph.propagation.StaticFieldKey"); } return super.getPredNodes(N); } /** @see com.ibm.wala.util.graph.AbstractGraph#getSuccNodeCount(java.lang.Object) */ @Override public int getSuccNodeCount(Object N) throws UnimplementedError { if (N instanceof StaticFieldKey) { Assertions.UNREACHABLE(); return -1; } else { return super.getSuccNodeCount(N); } } /** @see com.ibm.wala.util.graph.AbstractGraph#getSuccNodes(java.lang.Object) */ @Override public Iterator<Object> getSuccNodes(Object N) { if (N instanceof StaticFieldKey) { addNodesThatWriteToStaticField(((StaticFieldKey) N).getField()); } else { IField f = getFieldDefs.get(N); if (f != null) { addMatchEdges((LocalPointerKey) N, f); } else { SSAInvokeInstruction callInstr = callDefs.get(N); if (callInstr != null) { addReturnEdges((LocalPointerKey) N, callInstr); } else { CGNode node = params.get(N); if (node != null) { addParamEdges((LocalPointerKey) N, node); } else { if (arrayDefs.contains(N)) { addArrayMatchEdges((LocalPointerKey) N); } } } } } return super.getSuccNodes(N); } private void addArrayMatchEdges(LocalPointerKey pk) { Collection<MemoryAccess> arrayWrites = fam.getArrayWrites(null); for (MemoryAccess a : arrayWrites) { addSubgraphForNode(a.getNode()); } for (MemoryAccess a : arrayWrites) { IR ir = a.getNode().getIR(); SSAArrayStoreInstruction s = (SSAArrayStoreInstruction) ir.getInstructions()[a.getInstructionIndex()]; PointerKey r = heapModel.getPointerKeyForLocal(a.getNode(), s.getValue()); assert containsNode(r); assert containsNode(pk); addMatchEdge(pk, r); } } private void addParamEdges(LocalPointerKey pk, CGNode node) { // get parameter position: value number - 1? int paramPos = pk.getValueNumber() - 1; // 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(node)) { SSAAbstractInvokeInstruction[] callInstrs = ir.getCalls(call); for (SSAAbstractInvokeInstruction callInstr : callInstrs) { PointerKey actualPk = heapModel.getPointerKeyForLocal(caller, callInstr.getUse(paramPos)); assert containsNode(actualPk); assert containsNode(pk); addEdge(pk, actualPk); } } } } } /** @param pk value being def'fed by a call instruction (either normal or exceptional) */ private void addReturnEdges(LocalPointerKey pk, SSAInvokeInstruction callInstr) { boolean isExceptional = pk.getValueNumber() == callInstr.getException(); // get call targets Collection<CGNode> possibleCallees = cg.getPossibleTargets(pk.getNode(), callInstr.getCallSite()); // construct graph for each target for (CGNode callee : possibleCallees) { addSubgraphForNode(callee); PointerKey retVal = isExceptional ? heapModel.getPointerKeyForExceptionalReturnValue(callee) : heapModel.getPointerKeyForReturnValue(callee); assert containsNode(retVal); addEdge(pk, retVal); } } private void addMatchEdges(LocalPointerKey pk, IField f) { Collection<MemoryAccess> fieldWrites = fam.getFieldWrites(null, f); addMatchHelper(pk, fieldWrites); } private void addMatchHelper(LocalPointerKey pk, Collection<MemoryAccess> writes) { for (MemoryAccess a : writes) { addSubgraphForNode(a.getNode()); } for (MemoryAccess a : writes) { IR ir = a.getNode().getIR(); SSAPutInstruction s = (SSAPutInstruction) ir.getInstructions()[a.getInstructionIndex()]; PointerKey r = heapModel.getPointerKeyForLocal(a.getNode(), s.getVal()); assert containsNode(r); assert containsNode(pk); addMatchEdge(pk, r); } } private void addMatchEdge(LocalPointerKey pk, PointerKey r) { addEdge(pk, r); } private void addNodesThatWriteToStaticField(IField field) { Collection<MemoryAccess> fieldWrites = fam.getStaticFieldWrites(field); for (MemoryAccess a : fieldWrites) { addSubgraphForNode(a.getNode()); } } /* * (non-Javadoc) * * @see com.ibm.wala.util.graph.AbstractGraph#hasEdge(java.lang.Object, java.lang.Object) */ public boolean hasEdge(PointerKey src, PointerKey dst) { // TODO Auto-generated method stub return super.hasEdge(src, dst); } protected void unconditionallyAddConstraintsFromNode(CGNode node) { if (DEBUG) { System.err.println(("Visiting CGNode " + node)); } if (SSAPropagationCallGraphBuilder.PERIODIC_WIPE_SOFT_CACHES) { wipeCount++; if (wipeCount >= SSAPropagationCallGraphBuilder.WIPE_SOFT_CACHE_INTERVAL) { wipeCount = 0; ReferenceCleanser.clearSoftCaches(); } } IR ir = node.getIR(); debugPrintIR(ir); if (ir == null) { return; } DefUse du = node.getDU(); addNodeInstructionConstraints(node, ir, du); addNodePassthruExceptionConstraints(node, ir); } /** * 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 */ private 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); } else if (pei instanceof SSAAbstractThrowInstruction) { SSAAbstractThrowInstruction s = (SSAAbstractThrowInstruction) pei; PointerKey e = heapModel.getPointerKeyForLocal(node, s.getException()); addNode(exceptionVar); addNode(e); addEdge(exceptionVar, e); } // Account for those exceptions for which we do not actually have a // points-to set for // the pei, but just instance keys Collection<TypeReference> types = pei.getExceptionTypes(); if (types != null) { for (TypeReference type : types) { if (type != null) { InstanceKey ik = heapModel.getInstanceKeyForPEI(node, peiLoc, type); 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); } } } } } } /** Add pointer flow constraints based on instructions in a given node */ protected void addNodeInstructionConstraints(CGNode node, IR ir, DefUse du) { StatementVisitor v = makeVisitor((ExplicitCallGraph.ExplicitNode) node, ir, du); 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, StatementVisitor 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())) { 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); } // } // } } } } protected StatementVisitor makeVisitor(ExplicitCallGraph.ExplicitNode node, IR ir, DefUse du) { return new StatementVisitor(node, ir, du); } 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(); } } } } /** * 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. */ protected class StatementVisitor extends SSAInstruction.Visitor { /** 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(CGNode node, IR ir, DefUse du) { this.node = node; this.ir = ir; this.symbolTable = ir.getSymbolTable(); assert symbolTable != null; this.du = du; } /* * (non-Javadoc) * * @see com.ibm.domo.ssa.SSAInstruction.Visitor#visitArrayLoad(com.ibm.domo.ssa.SSAArrayLoadInstruction) */ @Override public void visitArrayLoad(SSAArrayLoadInstruction instruction) { // skip arrays of primitive type if (instruction.typeIsPrimitive()) { return; } PointerKey result = heapModel.getPointerKeyForLocal(node, instruction.getDef()); arrayDefs.add(result); // PointerKey arrayRef = getPointerKeyForLocal(node, // instruction.getArrayRef()); // if (hasNoInterestingUses(instruction.getDef(), du)) { // system.recordImplicitPointsToSet(result); // } else { // if (contentsAreInvariant(symbolTable, du, instruction.getArrayRef())) { // system.recordImplicitPointsToSet(arrayRef); // InstanceKey[] ik = getInvariantContents(symbolTable, du, node, // instruction.getArrayRef(), // SSAPropagationCallGraphBuilder.this); // for (int i = 0; i < ik.length; i++) { // system.findOrCreateIndexForInstanceKey(ik[i]); // PointerKey p = getPointerKeyForArrayContents(ik[i]); // if (p == null) { // getWarnings().add(ResolutionFailure.create(node, // ik[i].getConcreteType())); // } else { // system.newConstraint(result, assignOperator, p); // } // } // } else { // if (Assertions.verifyAssertions) { // Assertions._assert(!system.isUnified(result)); // Assertions._assert(!system.isUnified(arrayRef)); // } // system.newSideEffect(new // ArrayLoadOperator(system.findOrCreatePointsToSet(result)), arrayRef); // } // } } /* * (non-Javadoc) * * @see com.ibm.domo.ssa.SSAInstruction.Visitor#visitArrayStore(com.ibm.domo.ssa.SSAArrayStoreInstruction) */ @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()); addNode(value); // // // (requires the creation of assign constraints as // // the set points-to(a[]) grows.) // PointerKey arrayRef = getPointerKeyForLocal(node, // instruction.getArrayRef()); // // if (!supportFullPointerFlowGraph && // // contentsAreInvariant(instruction.getArrayRef())) { // if (contentsAreInvariant(symbolTable, du, instruction.getArrayRef())) { // system.recordImplicitPointsToSet(arrayRef); // InstanceKey[] ik = getInvariantContents(symbolTable, du, node, // instruction.getArrayRef(), // SSAPropagationCallGraphBuilder.this); // // for (int i = 0; i < ik.length; i++) { // system.findOrCreateIndexForInstanceKey(ik[i]); // PointerKey p = getPointerKeyForArrayContents(ik[i]); // IClass contents = ((ArrayClass) // ik[i].getConcreteType()).getElementClass(); // if (p == null) { // getWarnings().add(ResolutionFailure.create(node, // ik[i].getConcreteType())); // } else { // if (DEBUG_TRACK_INSTANCE) { // if (system.findOrCreateIndexForInstanceKey(ik[i]) == // DEBUG_INSTANCE_KEY) { // Assertions.UNREACHABLE(); // } // } // if (contentsAreInvariant(symbolTable, du, instruction.getValue())) { // system.recordImplicitPointsToSet(value); // InstanceKey[] vk = getInvariantContents(symbolTable, du, node, // instruction.getValue(), // SSAPropagationCallGraphBuilder.this); // for (int j = 0; j < vk.length; j++) { // system.findOrCreateIndexForInstanceKey(vk[j]); // if (vk[j].getConcreteType() != null) { // if (contents.isInterface()) { // if (getClassHierarchy().implementsInterface(vk[j].getConcreteType(), // contents.getReference())) { // system.newConstraint(p, vk[j]); // } // } else { // if (getClassHierarchy().isSubclassOf(vk[j].getConcreteType(), // contents)) { // system.newConstraint(p, vk[j]); // } // } // } // } // } else { // if (isRootType(contents)) { // system.newConstraint(p, assignOperator, value); // } else { // system.newConstraint(p, filterOperator, value); // } // } // } // } // } else { // if (contentsAreInvariant(symbolTable, du, instruction.getValue())) { // system.recordImplicitPointsToSet(value); // InstanceKey[] ik = getInvariantContents(symbolTable, du, node, // instruction.getValue(), // SSAPropagationCallGraphBuilder.this); // for (int i = 0; i < ik.length; i++) { // system.findOrCreateIndexForInstanceKey(ik[i]); // if (Assertions.verifyAssertions) { // Assertions._assert(!system.isUnified(arrayRef)); // } // system.newSideEffect(new InstanceArrayStoreOperator(ik[i]), arrayRef); // } // } else { // system.newSideEffect(new // ArrayStoreOperator(system.findOrCreatePointsToSet(value)), arrayRef); // } // } } /* * (non-Javadoc) * * @see com.ibm.domo.ssa.SSAInstruction.Visitor#visitCheckCast(com.ibm.domo.ssa.SSACheckCastInstruction) */ @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()); // TODO actually use the cast type addNode(result); addNode(value); addEdge(result, value); // // if (hasNoInterestingUses(instruction.getDef(), du)) { // system.recordImplicitPointsToSet(result); // } else { // if (contentsAreInvariant(symbolTable, du, instruction.getVal())) { // system.recordImplicitPointsToSet(value); // InstanceKey[] ik = getInvariantContents(symbolTable, du, node, // instruction.getVal(), SSAPropagationCallGraphBuilder.this); // if (cls.isInterface()) { // for (int i = 0; i < ik.length; i++) { // system.findOrCreateIndexForInstanceKey(ik[i]); // if (getClassHierarchy().implementsInterface(ik[i].getConcreteType(), // cls.getReference())) { // system.newConstraint(result, ik[i]); // } // } // } else { // for (int i = 0; i < ik.length; i++) { // system.findOrCreateIndexForInstanceKey(ik[i]); // if (getClassHierarchy().isSubclassOf(ik[i].getConcreteType(), cls)) { // system.newConstraint(result, ik[i]); // } // } // } // } else { // if (cls == null) { // getWarnings().add(ResolutionFailure.create(node, // instruction.getDeclaredResultType())); // cls = getJavaLangObject(); // } // if (isRootType(cls)) { // system.newConstraint(result, assignOperator, value); // } else { // system.newConstraint(result, filterOperator, value); // } // } // } } /* * (non-Javadoc) * * @see com.ibm.domo.ssa.SSAInstruction.Visitor#visitReturn(com.ibm.domo.ssa.SSAReturnInstruction) */ @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()); addNode(def); PointerKey returnValue = heapModel.getPointerKeyForReturnValue(node); addNode(returnValue); addEdge(returnValue, def); } // PointerKey returnValue = getPointerKeyForReturnValue(node); // PointerKey result = getPointerKeyForLocal(node, // instruction.getResult()); // // if (!supportFullPointerFlowGraph && // // contentsAreInvariant(instruction.getResult())) { // if (contentsAreInvariant(symbolTable, du, instruction.getResult())) { // system.recordImplicitPointsToSet(result); // InstanceKey[] ik = getInvariantContents(symbolTable, du, node, // instruction.getResult(), SSAPropagationCallGraphBuilder.this); // for (int i = 0; i < ik.length; i++) { // system.newConstraint(returnValue, ik[i]); // } // } else { // system.newConstraint(returnValue, assignOperator, result); // } } /* * (non-Javadoc) * * @see com.ibm.domo.ssa.SSAInstruction.Visitor#visitGet(com.ibm.domo.ssa.SSAGetInstruction) */ @Override public void visitGet(SSAGetInstruction instruction) { visitGetInternal( instruction.getDef(), instruction.isStatic(), instruction.getDeclaredField()); } protected void visitGetInternal(int lval, 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); addNode(def); addNode(fKey); addEdge(def, fKey); } else { addNode(def); getFieldDefs.put(def, f); } // system.newConstraint(def, assignOperator, fKey); // IClass klass = getClassHierarchy().lookupClass(field.getType()); // if (klass == null) { // getWarnings().add(ResolutionFailure.create(node, field.getType())); // } else { // // side effect of getstatic: may call class initializer // if (DEBUG) { // Trace.guardedPrintln("getstatic call class init " + klass, // DEBUG_METHOD_SUBSTRING); // } // // if (hasNoInterestingUses(lval, du)) { // system.recordImplicitPointsToSet(def); // } else { // if (isStatic) { // PointerKey fKey = getPointerKeyForStaticField(f); // system.newConstraint(def, assignOperator, fKey); // IClass klass = getClassHierarchy().lookupClass(field.getType()); // if (klass == null) { // getWarnings().add(ResolutionFailure.create(node, field.getType())); // } else { // // side effect of getstatic: may call class initializer // if (DEBUG) { // Trace.guardedPrintln("getstatic call class init " + klass, // DEBUG_METHOD_SUBSTRING); // } // processClassInitializer(klass); // } // } else { // PointerKey refKey = getPointerKeyForLocal(node, ref); // // if (!supportFullPointerFlowGraph && // // contentsAreInvariant(ref)) { // if (contentsAreInvariant(symbolTable, du, ref)) { // system.recordImplicitPointsToSet(refKey); // InstanceKey[] ik = getInvariantContents(symbolTable, du, node, ref, // SSAPropagationCallGraphBuilder.this); // for (int i = 0; i < ik.length; i++) { // system.findOrCreateIndexForInstanceKey(ik[i]); // PointerKey p = getPointerKeyForInstanceField(ik[i], f); // system.newConstraint(def, assignOperator, p); // } // } else { // system.newSideEffect(new GetFieldOperator(f, // system.findOrCreatePointsToSet(def)), refKey); // } // } // } } /* * (non-Javadoc) * * @see com.ibm.domo.ssa.Instruction.Visitor#visitPut(com.ibm.domo.ssa.PutInstruction) */ @Override public void visitPut(SSAPutInstruction instruction) { visitPutInternal( instruction.getVal(), instruction.isStatic(), instruction.getDeclaredField()); } public void visitPutInternal(int rval, 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); addNode(use); addNode(fKey); addEdge(fKey, use); } else { addNode(use); } } @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); } // 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); // TODO handle exceptions // if (DEBUG && debug) { // Trace.println("visitInvoke: " + instruction); // } // // PointerKey uniqueCatch = null; // if (hasUniqueCatchBlock(instruction, ir)) { // uniqueCatch = getUniqueCatchKey(instruction, ir, node); // } // // if (instruction.getCallSite().isStatic()) { // CGNode n = getTargetForCall(node, instruction.getCallSite(), // (InstanceKey) null); // if (n == null) { // getWarnings().add(ResolutionFailure.create(node, instruction)); // } else { // processResolvedCall(node, instruction, n, // computeInvariantParameters(instruction), uniqueCatch); // if (DEBUG) { // Trace.guardedPrintln("visitInvoke class init " + n, // DEBUG_METHOD_SUBSTRING); // } // // // side effect of invoke: may call class initializer // processClassInitializer(n.getMethod().getDeclaringClass()); // } // } else { // // Add a side effect that will fire when we determine a value // // for the receiver. This side effect will create a new node // // and new constraints based on the new callee context. // // NOTE: This will not be adequate for CPA-style context selectors, // // where the callee context may depend on state other than the // // receiver. TODO: rectify this when needed. // PointerKey receiver = getPointerKeyForLocal(node, // instruction.getReceiver()); // // if (!supportFullPointerFlowGraph && // // contentsAreInvariant(instruction.getReceiver())) { // if (contentsAreInvariant(symbolTable, du, instruction.getReceiver())) { // system.recordImplicitPointsToSet(receiver); // InstanceKey[] ik = getInvariantContents(symbolTable, du, node, // instruction.getReceiver(), // SSAPropagationCallGraphBuilder.this); // for (int i = 0; i < ik.length; i++) { // system.findOrCreateIndexForInstanceKey(ik[i]); // CGNode n = getTargetForCall(node, instruction.getCallSite(), ik[i]); // if (n == null) { // getWarnings().add(ResolutionFailure.create(node, instruction)); // } else { // processResolvedCall(node, instruction, n, // computeInvariantParameters(instruction), uniqueCatch); // // side effect of invoke: may call class initializer // processClassInitializer(n.getMethod().getDeclaringClass()); // } // } // } else { // if (DEBUG && debug) { // Trace.println("Add side effect, dispatch to " + instruction + ", // receiver " + receiver); // } // DispatchOperator dispatchOperator = new DispatchOperator(instruction, // node, computeInvariantParameters(instruction), // uniqueCatch); // system.newSideEffect(dispatchOperator, receiver); // } // } } /* * (non-Javadoc) * * @see com.ibm.domo.ssa.Instruction.Visitor#visitNew(com.ibm.domo.ssa.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()); addNode(iKey); addNode(def); addEdge(def, iKey); // IClass klass = iKey.getConcreteType(); // // if (DEBUG && debug) { // Trace.println("visitNew: " + instruction + " " + iKey + " " + // system.findOrCreateIndexForInstanceKey(iKey)); // } // // if (klass == null) { // getWarnings().add(ResolutionFailure.create(node, // instruction.getConcreteType())); // return; // } // // if (!contentsAreInvariant(symbolTable, du, instruction.getDef())) { // system.newConstraint(def, iKey); // } else { // system.findOrCreateIndexForInstanceKey(iKey); // system.recordImplicitPointsToSet(def); // } // // // side effect of new: may call class initializer // if (DEBUG) { // Trace.guardedPrintln("visitNew call clinit: " + klass, // DEBUG_METHOD_SUBSTRING); // } // processClassInitializer(klass); // // // add instance keys and pointer keys for array contents // int dim = 0; // InstanceKey lastInstance = iKey; // while (klass != null && klass.isArrayClass()) { // klass = ((ArrayClass) klass).getElementClass(); // // klass == null means it's a primitive // if (klass != null && klass.isArrayClass()) { // InstanceKey ik = getInstanceKeyForMultiNewArray(node, // instruction.getNewSite(), dim); // PointerKey pk = 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); // } // system.newConstraint(pk, ik); // lastInstance = ik; // dim++; // } // } } /* * (non-Javadoc) * * @see com.ibm.domo.ssa.Instruction.Visitor#visitThrow(com.ibm.domo.ssa.ThrowInstruction) */ @Override public void visitThrow(SSAThrowInstruction instruction) { // Assertions.UNREACHABLE(); // don't do anything: we handle exceptional edges // in a separate pass } /* * (non-Javadoc) * * @see com.ibm.domo.ssa.Instruction.Visitor#visitGetCaughtException(com.ibm.domo.ssa.GetCaughtExceptionInstruction) */ @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); } // private int booleanConstantTest(SSAConditionalBranchInstruction c, int v) // { // int result = 0; // // // right for OPR_eq // if ((symbolTable.isZero(c.getUse(0)) && c.getUse(1) == v) || // (symbolTable.isZero(c.getUse(1)) && c.getUse(0) == v)) { // result = -1; // } else if ((symbolTable.isOne(c.getUse(0)) && c.getUse(1) == v) || // (symbolTable.isOne(c.getUse(1)) && c.getUse(0) == v)) { // result = 1; // } // // if (c.getOperator() == Constants.OPR_ne) { // result = -result; // } // // return result; // } // // private int nullConstantTest(SSAConditionalBranchInstruction c, int v) { // if ((symbolTable.isNullConstant(c.getUse(0)) && c.getUse(1) == v) // || (symbolTable.isNullConstant(c.getUse(1)) && c.getUse(0) == v)) { // if (c.getOperator() == Constants.OPR_eq) { // return 1; // } else { // return -1; // } // } else { // return 0; // } // } /* * (non-Javadoc) * * @see com.ibm.domo.ssa.SSAInstruction.Visitor#visitPi(com.ibm.domo.ssa.SSAPiInstruction) */ @Override public void visitPi(SSAPiInstruction instruction) { Assertions.UNREACHABLE(); // int dir; // ControlFlowGraph CFG = ir.getControlFlowGraph(); // PointerKey src = getPointerKeyForLocal(node, instruction.getVal()); // if (hasNoInterestingUses(instruction.getDef(), du)) { // PointerKey dst = getPointerKeyForLocal(node, instruction.getDef()); // system.recordImplicitPointsToSet(dst); // } else { // if (com.ibm.domo.cfg.Util.endsWithConditionalBranch(CFG, // getBasicBlock()) && CFG.getSuccNodeCount(getBasicBlock()) == 2) { // SSAConditionalBranchInstruction cond = // com.ibm.domo.cfg.Util.getConditionalBranch(CFG, getBasicBlock()); // SSAInstruction cause = instruction.getCause(); // BasicBlock target = (BasicBlock) // CFG.getNode(instruction.getSuccessor()); // if ((cause instanceof SSAInstanceofInstruction) && ((dir = // booleanConstantTest(cond, cause.getDef())) != 0)) { // TypeReference type = ((SSAInstanceofInstruction) // cause).getCheckedType(); // IClass cls = cha.lookupClass(type); // if (cls == null) { // getWarnings().add(ResolutionFailure.create(node, type)); // PointerKey dst = getPointerKeyForLocal(node, instruction.getDef()); // system.newConstraint(dst, assignOperator, src); // } else { // PointerKey dst = getFilteredPointerKeyForLocal(node, // instruction.getDef(), cls); // if ((target == com.ibm.domo.cfg.Util.getTrueSuccessor(CFG, // getBasicBlock()) && dir == 1) // || (target == com.ibm.domo.cfg.Util.getFalseSuccessor(CFG, // getBasicBlock()) && dir == -1)) { // system.newConstraint(dst, filterOperator, src); // // System.err.println("PI " + dst + " " + src); // } else { // system.newConstraint(dst, inverseFilterOperator, src); // } // } // } else if ((dir = nullConstantTest(cond, instruction.getVal())) != 0) { // if ((target == com.ibm.domo.cfg.Util.getTrueSuccessor(CFG, // getBasicBlock()) && dir == -1) // || (target == com.ibm.domo.cfg.Util.getFalseSuccessor(CFG, // getBasicBlock()) && dir == 1)) { // PointerKey dst = getPointerKeyForLocal(node, instruction.getDef()); // system.newConstraint(dst, assignOperator, src); // } // } else { // PointerKey dst = getPointerKeyForLocal(node, instruction.getDef()); // system.newConstraint(dst, assignOperator, src); // } // } else { // PointerKey dst = getPointerKeyForLocal(node, instruction.getDef()); // system.newConstraint(dst, assignOperator, src); // } // } } public ISSABasicBlock getBasicBlock() { return basicBlock; } /** The calling loop must call this in each iteration! */ public void setBasicBlock(ISSABasicBlock block) { basicBlock = block; } // /** // * Side effect: records invariant parameters as implicit points-to-sets. // * // * @return if non-null, then result[i] holds the set of instance keys // which // * may be passed as the ith parameter. (which must be invariant) // */ // protected InstanceKey[][] // computeInvariantParameters(SSAAbstractInvokeInstruction call) { // InstanceKey[][] constParams = null; // for (int i = 0; i < call.getNumberOfUses(); i++) { // // not sure how getUse(i) <= 0 .. dead code? // // TODO: investigate // if (call.getUse(i) > 0) { // if (contentsAreInvariant(symbolTable, du, call.getUse(i))) { // system.recordImplicitPointsToSet(getPointerKeyForLocal(node, // call.getUse(i))); // if (constParams == null) { // constParams = new InstanceKey[call.getNumberOfUses()][]; // } // constParams[i] = getInvariantContents(symbolTable, du, node, // call.getUse(i), SSAPropagationCallGraphBuilder.this); // for (int j = 0; j < constParams[i].length; j++) { // system.findOrCreateIndexForInstanceKey(constParams[i][j]); // } // } // } // } // return constParams; // } @Override public void visitLoadMetadata(SSALoadMetadataInstruction instruction) { Assertions.UNREACHABLE(); // PointerKey def = getPointerKeyForLocal(node, instruction.getDef()); // InstanceKey iKey = // getInstanceKeyForClassObject(instruction.getLoadedClass()); // // if (!contentsAreInvariant(symbolTable, du, instruction.getDef())) { // system.newConstraint(def, iKey); // } else { // system.findOrCreateIndexForInstanceKey(iKey); // system.recordImplicitPointsToSet(def); // } } } // private final class FieldExpression { // LocalPointerKey x; // // IField f; // // public FieldExpression(IField f, LocalPointerKey x) { // this.f = f; // this.x = x; // } // // /* // * (non-Javadoc) // * // * @see java.lang.Object#equals(java.lang.Object) // */ // public boolean equals(Object obj) { // if (obj instanceof FieldExpression) { // FieldExpression other = (FieldExpression) obj; // return x.equals(other.x) && f.equals(other.f); // } else { // return false; // } // } // // /* // * (non-Javadoc) // * // * @see java.lang.Object#hashCode() // */ // public int hashCode() { // return x.hashCode() + 4729 * f.hashCode(); // } // } }
46,349
34.736315
120
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/demandpa/util/ArrayContents.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.util; import com.ibm.wala.classLoader.IClass; import com.ibm.wala.classLoader.IField; import com.ibm.wala.core.util.strings.Atom; import com.ibm.wala.ipa.cha.ClassHierarchy; import com.ibm.wala.types.FieldReference; import com.ibm.wala.types.TypeReference; import com.ibm.wala.types.annotations.Annotation; import com.ibm.wala.util.debug.Assertions; import com.ibm.wala.util.debug.UnimplementedError; import java.util.Collection; import java.util.Collections; /** * Pseudo-field modelling the contents of an array of reference type. Only for convenience; many of * the methods don't actually work. Also, a singleton. * * @author manu */ public class ArrayContents implements IField { private static final ArrayContents theContents = new ArrayContents(); public static final ArrayContents v() { return theContents; } private ArrayContents() {} @Override public TypeReference getFieldTypeReference() throws UnimplementedError { Assertions.UNREACHABLE(); return null; } @Override public boolean isFinal() throws UnimplementedError { Assertions.UNREACHABLE(); return false; } @Override public boolean isPrivate() throws UnimplementedError { Assertions.UNREACHABLE(); return false; } @Override public boolean isProtected() throws UnimplementedError { Assertions.UNREACHABLE(); return false; } @Override public boolean isPublic() throws UnimplementedError { Assertions.UNREACHABLE(); return false; } @Override public boolean isStatic() throws UnimplementedError { Assertions.UNREACHABLE(); return false; } @Override public IClass getDeclaringClass() throws UnsupportedOperationException { throw new UnsupportedOperationException(); } @Override public Atom getName() throws UnimplementedError { Assertions.UNREACHABLE(); return null; } @Override public String toString() { return "arr"; } @Override public boolean isVolatile() { return false; } @Override public ClassHierarchy getClassHierarchy() throws UnimplementedError { Assertions.UNREACHABLE(); return null; } @Override public FieldReference getReference() { return null; } @Override public Collection<Annotation> getAnnotations() { return Collections.emptySet(); } }
4,262
29.234043
99
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/demandpa/util/CallGraphMapUtil.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.util; import com.ibm.wala.analysis.reflection.InstanceKeyWithNode; 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.AllocationSiteInNode; 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.MultiNewArrayInNode; import com.ibm.wala.ipa.callgraph.propagation.NormalAllocationInNode; import com.ibm.wala.ipa.callgraph.propagation.PointerKey; import com.ibm.wala.ipa.callgraph.propagation.ReturnValueKey; import com.ibm.wala.ipa.callgraph.propagation.cfa.ExceptionReturnValueKey; import com.ibm.wala.types.MethodReference; import com.ibm.wala.util.debug.Assertions; import com.ibm.wala.util.debug.UnimplementedError; import java.util.Set; /** * utility methods for mapping various program entities from one call graph to the corresponding * entity in another one * * @author Manu Sridharan */ public class CallGraphMapUtil { /** * map a call graph node from one call graph to the corresponding node in another. Note that the * target call graph must be context-insensitive for the method, i.e., the only context for the * method should be Everywhere.EVERYWHERE. * * @return the corresponding node, or {@code null} if the method is not in the target call graph * @throws IllegalArgumentException if fromCG == null */ public static CGNode mapCGNode(CGNode orig, CallGraph fromCG, CallGraph toCG) throws IllegalArgumentException { if (fromCG == null) { throw new IllegalArgumentException("fromCG == null"); } if (orig == fromCG.getFakeRootNode()) { return toCG.getFakeRootNode(); } else { MethodReference methodRef = orig.getMethod().getReference(); if (methodRef .toString() .equals("< Primordial, Ljava/lang/Object, clone()Ljava/lang/Object; >")) { // NOTE: clone() is cloned one level, even by RTA, so we need to handle it CGNode ret = toCG.getNode(orig.getMethod(), orig.getContext()); if (ret == null) { System.err.println(("WEIRD can't map node " + orig)); } return ret; } else { Set<CGNode> nodes = toCG.getNodes(methodRef); int size = nodes.size(); assert size <= 1; return (size == 0) ? null : nodes.iterator().next(); } } } public static InstanceKey mapInstKey( InstanceKey ik, CallGraph fromCG, CallGraph toCG, HeapModel heapModel) throws UnimplementedError, NullPointerException { InstanceKey ret = null; if (ik instanceof InstanceKeyWithNode) { CGNode oldCGNode = ((InstanceKeyWithNode) ik).getNode(); CGNode newCGNode = mapCGNode(oldCGNode, fromCG, toCG); if (newCGNode == null) { return null; } if (ik instanceof AllocationSiteInNode) { if (ik instanceof NormalAllocationInNode) { ret = heapModel.getInstanceKeyForAllocation( newCGNode, ((AllocationSiteInNode) ik).getSite()); } else if (ik instanceof MultiNewArrayInNode) { MultiNewArrayInNode mnik = (MultiNewArrayInNode) ik; ret = heapModel.getInstanceKeyForMultiNewArray(newCGNode, mnik.getSite(), mnik.getDim()); } else { Assertions.UNREACHABLE(); } } else { Assertions.UNREACHABLE(); } } else if (ik instanceof ConcreteTypeKey) { return ik; } else { Assertions.UNREACHABLE(); } assert ret != null; assert ret.getClass() == ik.getClass(); return ret; } public static PointerKey mapPointerKey( PointerKey pk, CallGraph fromCG, CallGraph toCG, HeapModel heapModel) throws UnimplementedError { PointerKey ret = null; if (pk instanceof AbstractLocalPointerKey) { CGNode oldCGNode = ((AbstractLocalPointerKey) pk).getNode(); CGNode newCGNode = mapCGNode(oldCGNode, fromCG, toCG); if (newCGNode == null) { return null; } if (pk instanceof LocalPointerKey) { ret = heapModel.getPointerKeyForLocal(newCGNode, ((LocalPointerKey) pk).getValueNumber()); } else if (pk instanceof ReturnValueKey) { // NOTE: must check for ExceptionReturnValueKey first, // since its a subclass if ReturnValueKey if (pk instanceof ExceptionReturnValueKey) { ret = heapModel.getPointerKeyForExceptionalReturnValue(newCGNode); } else { ret = heapModel.getPointerKeyForReturnValue(newCGNode); } } else { Assertions.UNREACHABLE(); } } else { Assertions.UNREACHABLE(); } assert ret != null; return ret; } }
6,876
40.179641
99
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/demandpa/util/MemoryAccess.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.util; import com.ibm.wala.ipa.callgraph.CGNode; /** * * represents a single static occurrence of a memory access (i.e., an access to a field or to the * contents of an array) in the code * * @author sfink */ public class MemoryAccess { private final CGNode node; /** index of the field access instruction in a shrikeBt or SSA instruction array */ private final int instructionIndex; public MemoryAccess(int index, CGNode node) { super(); instructionIndex = index; this.node = node; } /** @return Returns the instructionIndex. */ public int getInstructionIndex() { return instructionIndex; } @Override public String toString() { return "MemAccess: " + getNode() + ':' + getInstructionIndex(); } /** @return Returns the node. */ public CGNode getNode() { return node; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + instructionIndex; result = prime * result + ((node == null) ? 0 : node.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; MemoryAccess other = (MemoryAccess) obj; if (instructionIndex != other.instructionIndex) return false; if (node == null) { if (other.node != null) return false; } else if (!node.equals(other.node)) return false; return true; } }
1,886
25.577465
99
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/demandpa/util/MemoryAccessMap.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.util; import com.ibm.wala.classLoader.IField; import com.ibm.wala.ipa.callgraph.propagation.HeapModel; import com.ibm.wala.ipa.callgraph.propagation.PointerKey; import java.util.Collection; public interface MemoryAccessMap { /** @return {@link Collection}&lt;{@link MemoryAccess}&gt; */ Collection<MemoryAccess> getFieldReads(PointerKey baseRef, IField field); /** @return {@link Collection}&lt;{@link MemoryAccess}&gt; */ Collection<MemoryAccess> getFieldWrites(PointerKey baseRef, IField field); Collection<MemoryAccess> getArrayReads(PointerKey arrayRef); Collection<MemoryAccess> getArrayWrites(PointerKey arrayRef); Collection<MemoryAccess> getStaticFieldReads(IField field); Collection<MemoryAccess> getStaticFieldWrites(IField field); /** get the heap model used in this memory access map */ HeapModel getHeapModel(); }
1,254
32.918919
76
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/demandpa/util/PABasedMemoryAccessMap.java
/* * Copyright (c) 2002 - 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.demandpa.util; import com.ibm.wala.classLoader.IField; 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.PointerAnalysis; import com.ibm.wala.ipa.callgraph.propagation.PointerKey; import com.ibm.wala.ipa.modref.ModRef; import com.ibm.wala.ipa.slicer.NormalStatement; import com.ibm.wala.ipa.slicer.SDG; import com.ibm.wala.ipa.slicer.Slicer.ControlDependenceOptions; import com.ibm.wala.ipa.slicer.Slicer.DataDependenceOptions; import com.ibm.wala.ipa.slicer.Statement; import com.ibm.wala.ipa.slicer.thin.CISlicer; import com.ibm.wala.util.collections.MapUtil; import com.ibm.wala.util.debug.Assertions; import java.util.ArrayList; import java.util.Collection; import java.util.Map; import java.util.Set; /** * A {@link MemoryAccessMap} that makes use of a pre-computed {@link PointerAnalysis} to reduce the * number of considered accesses. * * @author manu */ public class PABasedMemoryAccessMap implements MemoryAccessMap { private static final boolean DEBUG = false; private final PointerAnalysis<InstanceKey> pa; private final HeapModel heapModel; private final Map<PointerKey, Set<Statement>> invMod; private final Map<PointerKey, Set<Statement>> invRef; public PABasedMemoryAccessMap(CallGraph cg, PointerAnalysis<InstanceKey> pa) { this( pa, new SDG<>( cg, pa, DataDependenceOptions.NO_BASE_NO_HEAP_NO_EXCEPTIONS, ControlDependenceOptions.NONE)); } public PABasedMemoryAccessMap(PointerAnalysis<InstanceKey> pa, SDG<InstanceKey> sdg) { this(pa, CISlicer.scanForMod(sdg, pa, true, ModRef.make()), CISlicer.scanForRef(sdg, pa)); } public PABasedMemoryAccessMap( PointerAnalysis<InstanceKey> pa, Map<Statement, Set<PointerKey>> mod, Map<Statement, Set<PointerKey>> ref) { if (pa == null) { throw new IllegalArgumentException("null pa"); } this.pa = pa; this.heapModel = pa.getHeapModel(); invMod = MapUtil.inverseMap(mod); invRef = MapUtil.inverseMap(ref); } @Override public Collection<MemoryAccess> getArrayReads(PointerKey arrayRef) { Collection<MemoryAccess> memAccesses = new ArrayList<>(); if (DEBUG) { System.err.println(("looking at reads of array ref " + arrayRef)); } for (InstanceKey ik : pa.getPointsToSet(arrayRef)) { PointerKey ack = heapModel.getPointerKeyForArrayContents(ik); convertStmtsToMemoryAccess(invRef.get(ack), memAccesses); } return memAccesses; } @Override public Collection<MemoryAccess> getArrayWrites(PointerKey arrayRef) { Collection<MemoryAccess> memAccesses = new ArrayList<>(); if (DEBUG) { System.err.println(("looking at writes to array ref " + arrayRef)); } for (InstanceKey ik : pa.getPointsToSet(arrayRef)) { if (DEBUG) { System.err.println(("instance key " + ik + " class " + ik.getClass())); } PointerKey ack = heapModel.getPointerKeyForArrayContents(ik); convertStmtsToMemoryAccess(invMod.get(ack), memAccesses); } return memAccesses; } @Override public Collection<MemoryAccess> getFieldReads(PointerKey baseRef, IField field) { Collection<MemoryAccess> memAccesses = new ArrayList<>(); for (InstanceKey ik : pa.getPointsToSet(baseRef)) { PointerKey ifk = heapModel.getPointerKeyForInstanceField(ik, field); convertStmtsToMemoryAccess(invRef.get(ifk), memAccesses); } return memAccesses; } @Override public Collection<MemoryAccess> getFieldWrites(PointerKey baseRef, IField field) { Collection<MemoryAccess> memAccesses = new ArrayList<>(); for (InstanceKey ik : pa.getPointsToSet(baseRef)) { PointerKey ifk = heapModel.getPointerKeyForInstanceField(ik, field); convertStmtsToMemoryAccess(invMod.get(ifk), memAccesses); } return memAccesses; } @Override public Collection<MemoryAccess> getStaticFieldReads(IField field) { Collection<MemoryAccess> result = new ArrayList<>(); convertStmtsToMemoryAccess(invRef.get(heapModel.getPointerKeyForStaticField(field)), result); return result; } @Override public Collection<MemoryAccess> getStaticFieldWrites(IField field) { Collection<MemoryAccess> result = new ArrayList<>(); convertStmtsToMemoryAccess(invMod.get(heapModel.getPointerKeyForStaticField(field)), result); return result; } private static void convertStmtsToMemoryAccess( Collection<Statement> stmts, Collection<MemoryAccess> result) { if (stmts == null) { return; } if (DEBUG) { System.err.println(("statements: " + stmts)); } for (Statement s : stmts) { switch (s.getKind()) { case NORMAL: NormalStatement normStmt = (NormalStatement) s; result.add(new MemoryAccess(normStmt.getInstructionIndex(), normStmt.getNode())); break; default: Assertions.UNREACHABLE(); } } } @Override public HeapModel getHeapModel() { return heapModel; } }
5,552
32.251497
99
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/demandpa/util/PointerParamValueNumIterator.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.util; import com.ibm.wala.analysis.typeInference.TypeAbstraction; import com.ibm.wala.analysis.typeInference.TypeInference; import com.ibm.wala.ipa.callgraph.CGNode; import com.ibm.wala.ssa.IR; import com.ibm.wala.ssa.SymbolTable; import java.util.Iterator; import java.util.NoSuchElementException; /** * Iterates over the value numbers of the pointer parameters of a method. * * @author Manu Sridharan */ public class PointerParamValueNumIterator implements Iterator<Integer> { final TypeInference ti; final SymbolTable symbolTable; final int numParams; int paramInd; int nextParameter; public PointerParamValueNumIterator(CGNode node) throws IllegalArgumentException { if (node == null) { throw new IllegalArgumentException("node == null"); } IR ir = node.getIR(); ti = TypeInference.make(ir, false); symbolTable = ir.getSymbolTable(); numParams = symbolTable.getNumberOfParameters(); paramInd = 0; setNextParameter(); } private void setNextParameter() { int i = paramInd; for (; i < numParams; i++) { int parameter = symbolTable.getParameter(i); TypeAbstraction t = ti.getType(parameter); if (t != null) { nextParameter = parameter; break; } } paramInd = ++i; } @Override public boolean hasNext() { return paramInd <= numParams; } @Override public Integer next() { if (!hasNext()) { throw new NoSuchElementException(); } int ret = nextParameter; setNextParameter(); return ret; } @Override public void remove() throws UnsupportedOperationException { throw new UnsupportedOperationException(); } }
3,628
31.990909
84
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/demandpa/util/SimpleMemoryAccessMap.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.util; import com.ibm.wala.classLoader.IField; import com.ibm.wala.classLoader.ShrikeCTMethod; import com.ibm.wala.core.util.shrike.ShrikeUtil; 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.PointerKey; import com.ibm.wala.ipa.cha.IClassHierarchy; import com.ibm.wala.shrike.shrikeBT.IArrayLoadInstruction; import com.ibm.wala.shrike.shrikeBT.IArrayStoreInstruction; import com.ibm.wala.shrike.shrikeBT.IGetInstruction; import com.ibm.wala.shrike.shrikeBT.IInstruction; import com.ibm.wala.shrike.shrikeBT.IPutInstruction; import com.ibm.wala.shrike.shrikeBT.NewInstruction; import com.ibm.wala.shrike.shrikeCT.InvalidClassFileException; import com.ibm.wala.ssa.IR; import com.ibm.wala.ssa.SSAArrayLoadInstruction; import com.ibm.wala.ssa.SSAArrayReferenceInstruction; import com.ibm.wala.ssa.SSAArrayStoreInstruction; import com.ibm.wala.ssa.SSAGetInstruction; import com.ibm.wala.ssa.SSAInstruction; import com.ibm.wala.ssa.SSANewInstruction; import com.ibm.wala.ssa.SSAPutInstruction; import com.ibm.wala.types.ClassLoaderReference; import com.ibm.wala.types.FieldReference; import com.ibm.wala.types.TypeReference; import com.ibm.wala.util.collections.CompoundIterator; import com.ibm.wala.util.collections.HashMapFactory; import com.ibm.wala.util.collections.HashSetFactory; import com.ibm.wala.util.collections.Iterator2Iterable; import com.ibm.wala.util.collections.MapUtil; import com.ibm.wala.util.debug.Assertions; import java.util.Collection; import java.util.Collections; import java.util.Map; import java.util.Objects; import java.util.Set; /** @author sfink */ public class SimpleMemoryAccessMap implements MemoryAccessMap { private static final boolean DEBUG = false; /** * if true, always use IR from CGNode when reasoning about method statements; otherwise, try to * use bytecodes when possible. Note that current code may not work if set to false. */ private static final boolean ALWAYS_BUILD_IR = true; /** Map: IField -&gt; Set&lt;MemoryAccess&gt; */ private final Map<IField, Set<MemoryAccess>> readMap = HashMapFactory.make(); /** Map: IField -&gt; Set&lt;MemoryAccess&gt; */ private final Map<IField, Set<MemoryAccess>> writeMap = HashMapFactory.make(); private final Set<MemoryAccess> arrayReads = HashSetFactory.make(); private final Set<MemoryAccess> arrayWrites = HashSetFactory.make(); private final IClassHierarchy cha; private final boolean includePrimOps; private final HeapModel heapModel; public SimpleMemoryAccessMap(CallGraph cg, HeapModel heapModel, boolean includePrimOps) { if (cg == null) { throw new IllegalArgumentException("null cg"); } this.cha = cg.getClassHierarchy(); this.heapModel = heapModel; this.includePrimOps = includePrimOps; populate(cg); } private void populate(CallGraph cg) { for (CGNode n : cg) { populate(n); } } @SuppressWarnings("unused") private void populate(CGNode n) { // we analyze bytecodes to avoid the cost of IR construction, except // for synthetic methods, where we must use the synthetic IR if (ALWAYS_BUILD_IR || n.getMethod().isWalaSynthetic()) { if (DEBUG) { System.err.println("synthetic method"); } IR ir = n.getIR(); if (ir == null) { return; } SSAInstruction[] statements = ir.getInstructions(); SSAMemoryAccessVisitor v = new SSAMemoryAccessVisitor(n); for (int i = 0; i < statements.length; i++) { SSAInstruction s = statements[i]; if (s != null) { v.setInstructionIndex(i); s.visit(v); } } } else { if (DEBUG) { System.err.println("Shrike method"); } ShrikeCTMethod sm = (ShrikeCTMethod) n.getMethod(); MemoryAccessVisitor v = new MemoryAccessVisitor( n.getMethod().getReference().getDeclaringClass().getClassLoader(), n); try { IInstruction[] statements = sm.getInstructions(); if (statements == null) { // System.err.println("no statements for " + n.getMethod()); return; } if (DEBUG) { for (int i = 0; i < statements.length; i++) { System.err.println(i + ": " + statements[i]); } } for (int i = 0; i < statements.length; i++) { IInstruction s = statements[i]; if (s != null) { v.setInstructionIndex(i); s.visit(v); } } } catch (InvalidClassFileException e) { e.printStackTrace(); Assertions.UNREACHABLE(); } } } private class SSAMemoryAccessVisitor extends SSAInstruction.Visitor { private final CGNode node; private int instructionIndex; public SSAMemoryAccessVisitor(CGNode n) { this.node = n; } public void setInstructionIndex(int i) { this.instructionIndex = i; } @Override public void visitNew(SSANewInstruction instruction) { TypeReference declaredType = instruction.getNewSite().getDeclaredType(); // check for multidimensional array if (declaredType.isArrayType() && declaredType.getArrayElementType().isArrayType()) { arrayWrites.add(new MemoryAccess(instructionIndex, node)); } } @Override public void visitArrayLoad(SSAArrayLoadInstruction instruction) { if (!includePrimOps && instruction.typeIsPrimitive()) { return; } arrayReads.add(new MemoryAccess(instructionIndex, node)); } @Override public void visitArrayStore(SSAArrayStoreInstruction instruction) { if (!includePrimOps && instruction.typeIsPrimitive()) { return; } arrayWrites.add(new MemoryAccess(instructionIndex, node)); } @Override public void visitGet(SSAGetInstruction instruction) { if (!includePrimOps && instruction.getDeclaredFieldType().isPrimitiveType()) { return; } FieldReference fr = instruction.getDeclaredField(); IField f = cha.resolveField(fr); if (f == null) { return; } Set<MemoryAccess> s = MapUtil.findOrCreateSet(readMap, f); MemoryAccess fa = new MemoryAccess(instructionIndex, node); s.add(fa); } @Override public void visitPut(SSAPutInstruction instruction) { if (!includePrimOps && instruction.getDeclaredFieldType().isPrimitiveType()) { return; } FieldReference fr = instruction.getDeclaredField(); IField f = cha.resolveField(fr); if (f == null) { return; } Set<MemoryAccess> s = MapUtil.findOrCreateSet(writeMap, f); MemoryAccess fa = new MemoryAccess(instructionIndex, node); s.add(fa); } } private class MemoryAccessVisitor extends IInstruction.Visitor { int instructionIndex; final ClassLoaderReference loader; final CGNode node; public MemoryAccessVisitor(ClassLoaderReference loader, CGNode node) { super(); this.loader = loader; this.node = node; } protected void setInstructionIndex(int instructionIndex) { this.instructionIndex = instructionIndex; } @Override public void visitNew(NewInstruction instruction) { TypeReference tr = ShrikeUtil.makeTypeReference(loader, instruction.getType()); // chekc for multi-dimensional array allocation if (tr.isArrayType() && tr.getArrayElementType().isArrayType()) { if (DEBUG) { System.err.println("found multi-dim array write at " + instructionIndex); } arrayWrites.add(new MemoryAccess(instructionIndex, node)); } } /* * (non-Javadoc) * * @see com.ibm.shrikeBT.Instruction.Visitor#visitArrayLoad(com.ibm.shrikeBT.ArrayLoadInstruction) */ @Override public void visitArrayLoad(IArrayLoadInstruction instruction) { if (!includePrimOps) { TypeReference tr = ShrikeUtil.makeTypeReference(loader, instruction.getType()); // ISSUE is this the right check? if (tr.isPrimitiveType()) { return; } } arrayReads.add(new MemoryAccess(instructionIndex, node)); } /* * (non-Javadoc) * * @see com.ibm.shrikeBT.Instruction.Visitor#visitArrayStore(com.ibm.shrikeBT.ArrayStoreInstruction) */ @Override public void visitArrayStore(IArrayStoreInstruction instruction) { if (!includePrimOps) { TypeReference tr = ShrikeUtil.makeTypeReference(loader, instruction.getType()); if (tr.isPrimitiveType()) { return; } } if (DEBUG) { System.err.println("found array write at " + instructionIndex); } arrayWrites.add(new MemoryAccess(instructionIndex, node)); } /* * (non-Javadoc) * * @see com.ibm.shrikeBT.Instruction.Visitor#visitGet(com.ibm.shrikeBT.GetInstruction) */ @Override public void visitGet(IGetInstruction instruction) { FieldReference fr = FieldReference.findOrCreate( loader, instruction.getClassType(), instruction.getFieldName(), instruction.getFieldType()); if (!includePrimOps && fr.getFieldType().isPrimitiveType()) { return; } IField f = cha.resolveField(fr); if (f == null) { return; } Set<MemoryAccess> s = MapUtil.findOrCreateSet(readMap, f); MemoryAccess fa = new MemoryAccess(instructionIndex, node); s.add(fa); } /* * (non-Javadoc) * * @see com.ibm.shrikeBT.Instruction.Visitor#visitPut(com.ibm.shrikeBT.PutInstruction) */ @Override public void visitPut(IPutInstruction instruction) { FieldReference fr = FieldReference.findOrCreate( loader, instruction.getClassType(), instruction.getFieldName(), instruction.getFieldType()); if (!includePrimOps && fr.getFieldType().isPrimitiveType()) { return; } IField f = cha.resolveField(fr); if (f == null) { return; } Set<MemoryAccess> s = MapUtil.findOrCreateSet(writeMap, f); MemoryAccess fa = new MemoryAccess(instructionIndex, node); s.add(fa); } } @Override public Collection<MemoryAccess> getFieldReads(PointerKey pk, IField field) { Collection<MemoryAccess> result = readMap.get(field); return Objects.requireNonNullElse(result, Collections.emptySet()); } @Override public Collection<MemoryAccess> getFieldWrites(PointerKey pk, IField field) { Collection<MemoryAccess> result = writeMap.get(field); return Objects.requireNonNullElse(result, Collections.emptySet()); } @Override public Collection<MemoryAccess> getArrayReads(PointerKey pk) { return arrayReads; } @Override public Collection<MemoryAccess> getArrayWrites(PointerKey pk) { return arrayWrites; } @Override public String toString() { StringBuilder result = new StringBuilder(); Collection<IField> allFields = HashSetFactory.make(); allFields.addAll(readMap.keySet()); allFields.addAll(writeMap.keySet()); for (IField f : allFields) { result.append("FIELD ").append(f).append(":\n"); Collection<MemoryAccess> reads = getFieldReads(null, f); if (!reads.isEmpty()) { result.append(" reads:\n"); for (MemoryAccess memoryAccess : reads) { result.append(" ").append(memoryAccess).append('\n'); } } Collection<MemoryAccess> writes = getFieldWrites(null, f); if (!writes.isEmpty()) { result.append(" writes:\n"); for (MemoryAccess memoryAccess : writes) { result.append(" ").append(memoryAccess).append('\n'); } } } // arrays result.append("ARRAY CONTENTS:\n"); if (!arrayReads.isEmpty()) { result.append(" reads:\n"); for (MemoryAccess memoryAccess : arrayReads) { result.append(" ").append(memoryAccess).append('\n'); } } if (!arrayWrites.isEmpty()) { result.append(" writes:\n"); for (MemoryAccess memoryAccess : arrayWrites) { result.append(" ").append(memoryAccess).append('\n'); } } return result.toString(); } @Override public Collection<MemoryAccess> getStaticFieldReads(IField field) { return getFieldReads(null, field); } @Override public Collection<MemoryAccess> getStaticFieldWrites(IField field) { return getFieldWrites(null, field); } @Override public HeapModel getHeapModel() { // NOTE: this memory access map actually makes no use of the heap model return heapModel; } public void repOk() { for (MemoryAccess m : Iterator2Iterable.make( new CompoundIterator<>(arrayReads.iterator(), arrayWrites.iterator()))) { CGNode node = m.getNode(); IR ir = node.getIR(); assert ir != null : "null IR for " + node + " but we have a memory access"; SSAInstruction[] instructions = ir.getInstructions(); int instructionIndex = m.getInstructionIndex(); assert instructionIndex >= 0 && instructionIndex < instructions.length : "instruction index " + instructionIndex + " out of range for " + node + ", which has " + instructions.length + " instructions"; SSAInstruction s = instructions[m.getInstructionIndex()]; if (s == null) { // this is possible due to dead bytecodes continue; } assert s instanceof SSAArrayReferenceInstruction || s instanceof SSANewInstruction : "bad type " + s.getClass() + " for array access instruction"; } } }
14,258
31.114865
104
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/escape/FILiveObjectAnalysis.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.escape; import com.ibm.wala.analysis.pointers.HeapGraph; import com.ibm.wala.classLoader.NewSiteReference; import com.ibm.wala.ipa.callgraph.CGNode; import com.ibm.wala.ipa.callgraph.CallGraph; import com.ibm.wala.ipa.callgraph.propagation.AbstractLocalPointerKey; import com.ibm.wala.ipa.callgraph.propagation.InstanceKey; import com.ibm.wala.ipa.callgraph.propagation.LocalPointerKey; import com.ibm.wala.ipa.callgraph.propagation.PropagationCallGraphBuilder.TypedPointerKey; import com.ibm.wala.ipa.callgraph.propagation.StaticFieldKey; import com.ibm.wala.ssa.DefUse; import com.ibm.wala.ssa.IR; import com.ibm.wala.util.WalaException; import com.ibm.wala.util.collections.HashMapFactory; import com.ibm.wala.util.collections.HashSetFactory; import com.ibm.wala.util.collections.Iterator2Iterable; import com.ibm.wala.util.debug.Assertions; import com.ibm.wala.util.graph.impl.GraphInverter; import com.ibm.wala.util.graph.traverse.DFS; import com.ibm.wala.util.intset.IntIterator; import com.ibm.wala.util.intset.IntSet; import java.util.Collections; import java.util.Map; import java.util.Set; /** A simple liveness analysis based on flow-insensitive pointer analysis. */ public class FILiveObjectAnalysis implements ILiveObjectAnalysis { /** governing call graph */ private final CallGraph callGraph; /** Graph view of pointer analysis results */ private final HeapGraph<?> heapGraph; /** Cached map from InstanceKey -&gt; Set&lt;CGNode&gt; */ private final Map<InstanceKey, Set<CGNode>> liveNodes = HashMapFactory.make(); /** Set of instanceKeys which are live everywhere */ private final Set<InstanceKey> liveEverywhere = HashSetFactory.make(); /** A hack for now .. since right now the intraprocedural analysis is expensive */ private final boolean expensiveIntraproceduralAnalysis; /** */ public FILiveObjectAnalysis( CallGraph callGraph, HeapGraph<?> heapGraph, boolean expensiveIntraproceduralAnalysis) { super(); this.callGraph = callGraph; this.heapGraph = heapGraph; this.expensiveIntraproceduralAnalysis = expensiveIntraproceduralAnalysis; } @Override public boolean mayBeLive(CGNode allocMethod, int allocPC, CGNode m, int instructionIndex) throws IllegalArgumentException, WalaException { if (allocMethod == null) { throw new IllegalArgumentException("allocMethod == null"); } NewSiteReference site = TrivialMethodEscape.findAlloc(allocMethod, allocPC); InstanceKey ik = heapGraph.getHeapModel().getInstanceKeyForAllocation(allocMethod, site); return mayBeLive(ik, m, instructionIndex); } /** @param instructionIndex index of an SSA instruction */ @Override public boolean mayBeLive(InstanceKey ik, CGNode m, int instructionIndex) { if (liveEverywhere.contains(ik)) { return true; } else { Set<CGNode> live = liveNodes.get(ik); if (live != null) { if (live.contains(m)) { if (instructionIndex == -1) { return true; } else { if (mayBeLiveInSomeCaller(ik, m)) { // a hack. if it's live in some caller of m, assume it's live // throughout m. this may be imprecise. return true; } else { if (expensiveIntraproceduralAnalysis) { return mayBeLiveIntraprocedural(ik, m, instructionIndex); } else { // be conservative return true; } } } } else { return false; } } else { live = computeLiveNodes(ik); liveNodes.put(ik, live); return mayBeLive(ik, m, instructionIndex); } } } private boolean mayBeLiveInSomeCaller(InstanceKey ik, CGNode m) { for (CGNode n : Iterator2Iterable.make(callGraph.getPredNodes(m))) { if (mayBeLive(ik, n, -1)) { return true; } } return false; } /** * precondition: !mayBeLiveInSomeCaller(ik, m) * * @param instructionIndex index of an SSA instruction */ private boolean mayBeLiveIntraprocedural(InstanceKey ik, CGNode m, int instructionIndex) { IR ir = m.getIR(); DefUse du = m.getDU(); for (Object p : Iterator2Iterable.make(DFS.iterateDiscoverTime(GraphInverter.invert(heapGraph), ik))) { if (p instanceof LocalPointerKey) { LocalPointerKey lpk = (LocalPointerKey) p; if (lpk.getNode().equals(m)) { if (LocalLiveRangeAnalysis.isLive(lpk.getValueNumber(), instructionIndex, ir, du)) { return true; } } } } return false; } /** * Compute the set of nodes in which ik may be live. If it's live everywhere, return an EMPTY_SET, * but also record this fact in the "liveEverywhere" set as a side effect */ private Set<CGNode> computeLiveNodes(InstanceKey ik) { Set<CGNode> localRootNodes = HashSetFactory.make(); for (Object node : Iterator2Iterable.make(DFS.iterateDiscoverTime(GraphInverter.invert(heapGraph), ik))) { if (node instanceof StaticFieldKey) { liveEverywhere.add(ik); return Collections.emptySet(); } else { if (node instanceof AbstractLocalPointerKey) { AbstractLocalPointerKey local = (AbstractLocalPointerKey) node; localRootNodes.add(local.getNode()); } else if (node instanceof TypedPointerKey) { TypedPointerKey t = (TypedPointerKey) node; node = t.getBase(); if (node instanceof AbstractLocalPointerKey) { AbstractLocalPointerKey local = (AbstractLocalPointerKey) node; localRootNodes.add(local.getNode()); } else { Assertions.UNREACHABLE( "unexpected base of TypedPointerKey: " + node.getClass() + ' ' + node); } } } } return DFS.getReachableNodes(callGraph, localRootNodes); } @Override public boolean mayBeLive(InstanceKey ik, CGNode m, IntSet instructionIndices) { if (instructionIndices == null) { throw new IllegalArgumentException("instructionIndices is null"); } // TODO this sucks for (IntIterator it = instructionIndices.intIterator(); it.hasNext(); ) { int i = it.next(); if (mayBeLive(ik, m, i)) { return true; } } return false; } }
6,744
34.5
100
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/escape/ILiveObjectAnalysis.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.escape; import com.ibm.wala.ipa.callgraph.CGNode; import com.ibm.wala.ipa.callgraph.propagation.InstanceKey; import com.ibm.wala.util.WalaException; import com.ibm.wala.util.intset.IntSet; /** Basic interface for liveness analysis of heap-allocated objects. */ public interface ILiveObjectAnalysis { /** * @param allocMethod a method which holds an allocation site * @param allocPC bytecode index of allocation site * @param m method in question * @param instructionIndex index of an instruction in SSA IR. in m. if -1, it is interpreted as a * wildcard meaning "any statement" * @return true if an object allocated at the allocation site &lt;allocMethod,allocPC&gt; may be * live immediately after the statement &lt;m,instructionIndex&gt; */ boolean mayBeLive(CGNode allocMethod, int allocPC, CGNode m, int instructionIndex) throws WalaException; /** * @param ik an instance key * @param m method in question * @param instructionIndex index of an instruction in SSA IR. in m. if -1, it is interpreted as a * wildcard meaning "any statement" * @return true if an object allocated at the allocation site &lt;allocMethod,allocPC&gt; may be * live immediately after the statement &lt;m,instructionIndex&gt; */ boolean mayBeLive(InstanceKey ik, CGNode m, int instructionIndex) throws WalaException; /** * @param ik an instance key * @param m method in question * @param instructionIndices indices of instructions in SSA IR. * @return true if an object allocated at the allocation site &lt;allocMethod,allocPC&gt; may be * live immediately after the statement &lt;m,instructionIndex&gt; for any instructionIndex in * the set */ boolean mayBeLive(InstanceKey ik, CGNode m, IntSet instructionIndices); }
2,206
40.641509
100
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/escape/IMethodEscapeAnalysis.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.escape; import com.ibm.wala.types.MethodReference; import com.ibm.wala.util.WalaException; /** Basic interface from which to execute and get the results of escape analysis. */ public interface IMethodEscapeAnalysis { /** * @param allocMethod a method which holds an allocation site * @param allocPC bytecode index of allocation site * @param m method in question * @return true if an object allocated at the allocation site &lt;allocMethod,allocPC&gt; may * escape from an activation of method m, false otherwise */ boolean mayEscape(MethodReference allocMethod, int allocPC, MethodReference m) throws WalaException; }
1,050
35.241379
95
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/escape/INodeEscapeAnalysis.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.escape; import com.ibm.wala.ipa.callgraph.CGNode; import com.ibm.wala.util.WalaException; /** Basic interface from which to execute and get the results of escape analysis. */ public interface INodeEscapeAnalysis extends IMethodEscapeAnalysis { /** * @param allocNode a CGNode which holds an allocation site * @param allocPC bytecode index of allocation site * @param node method in question * @return true if an object allocated at the allocation site &lt;allocMethod,allocPC&gt; may * escape from an activation of node m, false otherwise */ boolean mayEscape(CGNode allocNode, int allocPC, CGNode node) throws WalaException; }
1,053
36.642857
95
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/escape/LocalLiveRangeAnalysis.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.escape; import com.ibm.wala.ssa.DefUse; 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.SSAInstruction; import com.ibm.wala.ssa.SSAReturnInstruction; import com.ibm.wala.util.collections.HashSetFactory; import com.ibm.wala.util.collections.Iterator2Collection; import com.ibm.wala.util.debug.Assertions; import com.ibm.wala.util.graph.traverse.DFS; import java.util.Collection; import java.util.Collections; import java.util.Iterator; import java.util.function.Predicate; /** Intraprocedural SSA-based live range analysis. This is horribly inefficient. */ public class LocalLiveRangeAnalysis { /** * Is the variable with value number v live immediately after a particular instruction index? * * <p>Algorithm: returns true if there is a path from pc to some use of v that does not traverse * the def of v * * @param instructionIndex index of an instruction in the IR * @throws IllegalArgumentException if du is null */ public static boolean isLive(int v, int instructionIndex, IR ir, DefUse du) { if (du == null) { throw new IllegalArgumentException("du is null"); } if (du.isUnused(v)) { return false; } if (instructionIndex < 0) { Assertions.UNREACHABLE(); } ISSABasicBlock queryBlock = findBlock(ir, instructionIndex); SSAInstruction def = du.getDef(v); final SSACFG.BasicBlock defBlock = def == null ? null : findBlock(ir, def); final Collection<BasicBlock> uses = findBlocks(ir, du.getUses(v)); // a filter which accepts everything but the block which defs v Predicate<Object> notDef = o -> (defBlock == null || !defBlock.equals(o)); if (defBlock != null && defBlock.equals(queryBlock)) { // for now, conservatively say it's live. fix this later if necessary. return true; } else { Collection<ISSABasicBlock> reached = DFS.getReachableNodes( ir.getControlFlowGraph(), Collections.singleton(queryBlock), notDef); uses.retainAll(reached); if (uses.isEmpty()) { return false; } else if (uses.size() == 1 && uses.iterator().next().equals(queryBlock)) { if (instructionIndex == queryBlock.getLastInstructionIndex()) { // the query is for the last instruction. There can be no more uses // following the block, so: // not quite true for return instructions. if (ir.getInstructions()[instructionIndex] instanceof SSAReturnInstruction) { return true; } else { return false; } } else { // todo: be more aggressive. // there may be more uses after the query, so conservatively assume it // may be live return true; } } else { return true; } } } /** @param statements {@code Iterator<SSAInstruction>} */ private static Collection<BasicBlock> findBlocks(IR ir, Iterator<SSAInstruction> statements) { Collection<SSAInstruction> s = Iterator2Collection.toSet(statements); Collection<BasicBlock> result = HashSetFactory.make(); outer: for (ISSABasicBlock issaBasicBlock : ir.getControlFlowGraph()) { SSACFG.BasicBlock b = (SSACFG.BasicBlock) issaBasicBlock; for (SSAInstruction x : b) { if (s.contains(x)) { result.add(b); continue outer; } } } if (result.isEmpty()) { Assertions.UNREACHABLE(); } return result; } /** * This is horribly inefficient. * * @return the basic block which contains the instruction */ private static SSACFG.BasicBlock findBlock(IR ir, SSAInstruction s) { if (s == null) { Assertions.UNREACHABLE(); } for (ISSABasicBlock issaBasicBlock : ir.getControlFlowGraph()) { SSACFG.BasicBlock b = (SSACFG.BasicBlock) issaBasicBlock; for (SSAInstruction x : b) { if (s.equals(x)) { return b; } } } Assertions.UNREACHABLE("no block for " + s + " in IR " + ir); return null; } /** * This is horribly inefficient. * * @return the basic block which contains the ith instruction */ private static ISSABasicBlock findBlock(IR ir, int i) { for (ISSABasicBlock issaBasicBlock : ir.getControlFlowGraph()) { SSACFG.BasicBlock b = (SSACFG.BasicBlock) issaBasicBlock; if (i >= b.getFirstInstructionIndex() && i <= b.getLastInstructionIndex()) { return b; } } Assertions.UNREACHABLE("no block for " + i + " in IR " + ir); return null; } }
5,048
33.114865
98
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/escape/TrivialMethodEscape.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.escape; import com.ibm.wala.analysis.pointers.HeapGraph; import com.ibm.wala.classLoader.NewSiteReference; import com.ibm.wala.ipa.callgraph.CGNode; import com.ibm.wala.ipa.callgraph.CallGraph; import com.ibm.wala.ipa.callgraph.propagation.AbstractLocalPointerKey; import com.ibm.wala.ipa.callgraph.propagation.InstanceKey; import com.ibm.wala.ipa.callgraph.propagation.PointerKey; import com.ibm.wala.ipa.callgraph.propagation.ReturnValueKey; import com.ibm.wala.types.MethodReference; import com.ibm.wala.util.WalaException; import com.ibm.wala.util.collections.HashSetFactory; import com.ibm.wala.util.collections.Iterator2Iterable; import java.util.Collections; import java.util.Set; /** * Trivial method-level escape analysis. * * <p>An instance does not escape from method m if the following hold: * * <ol> * <li>the instance is only ever pointed to by locals (it is never stored in the heap) * <li>the method m does NOT return (either normally or exceptionally) a pointer to the instance * </ol> */ public class TrivialMethodEscape implements IMethodEscapeAnalysis, INodeEscapeAnalysis { /** Heap graph representation of pointer analysis */ private final HeapGraph<InstanceKey> hg; /** Governing call graph */ private final CallGraph cg; /** * @param hg Heap graph representation of pointer analysis * @param cg governing call graph */ public TrivialMethodEscape(CallGraph cg, HeapGraph<InstanceKey> hg) { this.hg = hg; this.cg = cg; } @Override public boolean mayEscape(MethodReference allocMethod, int allocPC, MethodReference m) throws WalaException { if (allocMethod == null) { throw new IllegalArgumentException("null allocMethod"); } // nodes:= set of call graph nodes representing method m Set<CGNode> nodes = cg.getNodes(m); if (nodes.size() == 0) { throw new WalaException("could not find call graph node for method " + m); } // allocN := set of call graph nodes representing method allocMethod Set<CGNode> allocN = cg.getNodes(allocMethod); if (allocN.size() == 0) { throw new WalaException( "could not find call graph node for allocation method " + allocMethod); } return mayEscape(allocN, allocPC, nodes); } @Override public boolean mayEscape(CGNode allocNode, int allocPC, CGNode node) throws WalaException { return mayEscape(Collections.singleton(allocNode), allocPC, Collections.singleton(node)); } /** * @param allocN {@code Set<CGNode>} representing the allocation site. * @param nodes {@code Set<CGNode>}, the nodes of interest * @return true iff some instance allocated at a site N \in &lt;allocN, allocPC> might escape from * some activation of a node m \in { nodes } */ private boolean mayEscape(Set<CGNode> allocN, int allocPC, Set<CGNode> nodes) throws WalaException { Set<InstanceKey> instances = HashSetFactory.make(); // instances := set of instance key allocated at &lt;allocMethod, allocPC> for (CGNode n : allocN) { NewSiteReference site = findAlloc(n, allocPC); InstanceKey ik = hg.getHeapModel().getInstanceKeyForAllocation(n, site); if (ik == null) { throw new WalaException("could not get instance key at site " + site + " in " + n); } instances.add(ik); } for (InstanceKey ik : instances) { for (Object o : Iterator2Iterable.make(hg.getPredNodes(ik))) { PointerKey p = (PointerKey) o; if (!(p instanceof AbstractLocalPointerKey)) { // a pointer from the heap. give up. return true; } else { if (p instanceof ReturnValueKey) { ReturnValueKey rk = (ReturnValueKey) p; if (nodes.contains(rk.getNode())) { // some node representing method m returns the instance to its // caller return true; } } } } } // if we get here, it may not escape return false; } /** * @param n a call graph node * @param allocPC a bytecode index corresponding to an allocation * @return the NewSiteReference for the allocation */ static NewSiteReference findAlloc(CGNode n, int allocPC) throws WalaException { if (n == null) { throw new IllegalArgumentException("null n"); } for (NewSiteReference site : Iterator2Iterable.make(n.iterateNewSites())) { if (site.getProgramCounter() == allocPC) { return site; } } throw new WalaException("Failed to find an allocation at pc " + allocPC + " in node " + n); } }
4,994
34.425532
100
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/examples/analysis/dataflow/ContextInsensitiveReachingDefs.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.examples.analysis.dataflow; import com.ibm.wala.classLoader.IField; import com.ibm.wala.dataflow.graph.AbstractMeetOperator; import com.ibm.wala.dataflow.graph.BitVectorFramework; import com.ibm.wala.dataflow.graph.BitVectorIdentity; import com.ibm.wala.dataflow.graph.BitVectorKillAll; import com.ibm.wala.dataflow.graph.BitVectorKillGen; import com.ibm.wala.dataflow.graph.BitVectorSolver; import com.ibm.wala.dataflow.graph.BitVectorUnion; import com.ibm.wala.dataflow.graph.ITransferFunctionProvider; import com.ibm.wala.fixpoint.BitVectorVariable; import com.ibm.wala.fixpoint.UnaryOperator; import com.ibm.wala.ipa.callgraph.CGNode; import com.ibm.wala.ipa.cfg.BasicBlockInContext; import com.ibm.wala.ipa.cfg.ExplodedInterproceduralCFG; import com.ibm.wala.ipa.cha.IClassHierarchy; import com.ibm.wala.ssa.IR; import com.ibm.wala.ssa.SSAAbstractInvokeInstruction; import com.ibm.wala.ssa.SSAInstruction; import com.ibm.wala.ssa.SSAPutInstruction; import com.ibm.wala.ssa.analysis.IExplodedBasicBlock; import com.ibm.wala.util.CancelException; import com.ibm.wala.util.collections.HashMapFactory; import com.ibm.wala.util.collections.ObjectArrayMapping; import com.ibm.wala.util.collections.Pair; import com.ibm.wala.util.intset.BitVector; import com.ibm.wala.util.intset.OrdinalSetMapping; import java.util.ArrayList; import java.util.Map; /** * Computes interprocedural reaching definitions for static fields in a context-insensitive manner. */ public class ContextInsensitiveReachingDefs { /** the exploded interprocedural control-flow graph on which to compute the analysis */ private final ExplodedInterproceduralCFG icfg; /** * maps call graph node and instruction index of putstatic instructions to more compact numbering * for bitvectors */ private final OrdinalSetMapping<Pair<CGNode, Integer>> putInstrNumbering; /** for resolving field references in putstatic instructions */ private final IClassHierarchy cha; /** * maps each static field to the numbers of the statements (in {@link #putInstrNumbering}) that * define it; used for kills in flow functions */ private final Map<IField, BitVector> staticField2DefStatements = HashMapFactory.make(); private static final boolean VERBOSE = true; public ContextInsensitiveReachingDefs(ExplodedInterproceduralCFG icfg, IClassHierarchy cha) { this.icfg = icfg; this.cha = cha; this.putInstrNumbering = numberPutStatics(); } /** generate a numbering of the putstatic instructions */ private OrdinalSetMapping<Pair<CGNode, Integer>> numberPutStatics() { ArrayList<Pair<CGNode, Integer>> putInstrs = new ArrayList<>(); for (CGNode node : icfg.getCallGraph()) { IR ir = node.getIR(); if (ir == null) { continue; } SSAInstruction[] instructions = ir.getInstructions(); for (int i = 0; i < instructions.length; i++) { SSAInstruction instruction = instructions[i]; if (instruction instanceof SSAPutInstruction && ((SSAPutInstruction) instruction).isStatic()) { SSAPutInstruction putInstr = (SSAPutInstruction) instruction; // instrNum is the number that will be assigned to this putstatic int instrNum = putInstrs.size(); putInstrs.add(Pair.make(node, i)); // also update the mapping of static fields to def'ing statements IField field = cha.resolveField(putInstr.getDeclaredField()); assert field != null; BitVector bv = staticField2DefStatements.get(field); if (bv == null) { bv = new BitVector(); staticField2DefStatements.put(field, bv); } bv.set(instrNum); } } } // IntelliJ IDEA 2019.3 misdiagnoses "new ObjectArrayMapping<>(...)" below as a raw use of // generic type ObjectArrayMapping. It's actually a perfectly good use of Java generic type // inference. ECJ, on the other hand, apparently needs the "unchecked" suppression for some // reason. @SuppressWarnings({"rawtypes", "unchecked"}) ObjectArrayMapping<Pair<CGNode, Integer>> result = new ObjectArrayMapping<>(putInstrs.toArray(new Pair[0])); return result; } private class TransferFunctions implements ITransferFunctionProvider< BasicBlockInContext<IExplodedBasicBlock>, BitVectorVariable> { /** our meet operator is set union */ @Override public AbstractMeetOperator<BitVectorVariable> getMeetOperator() { return BitVectorUnion.instance(); } @Override public UnaryOperator<BitVectorVariable> getNodeTransferFunction( BasicBlockInContext<IExplodedBasicBlock> node) { IExplodedBasicBlock ebb = node.getDelegate(); SSAInstruction instruction = ebb.getInstruction(); int instructionIndex = ebb.getFirstInstructionIndex(); CGNode cgNode = node.getNode(); if (instruction instanceof SSAPutInstruction && ((SSAPutInstruction) instruction).isStatic()) { // kill all defs of the same static field, and gen this instruction final SSAPutInstruction putInstr = (SSAPutInstruction) instruction; final IField field = cha.resolveField(putInstr.getDeclaredField()); assert field != null; BitVector kill = staticField2DefStatements.get(field); BitVector gen = new BitVector(); gen.set(putInstrNumbering.getMappedIndex(Pair.make(cgNode, instructionIndex))); return new BitVectorKillGen(kill, gen); } else { // identity function for non-putstatic instructions return BitVectorIdentity.instance(); } } /** * here we need an edge transfer function for call-to-return edges (see {@link * #getEdgeTransferFunction(BasicBlockInContext, BasicBlockInContext)}) */ @Override public boolean hasEdgeTransferFunctions() { return true; } @Override public boolean hasNodeTransferFunctions() { return true; } /** * for direct call-to-return edges at a call site, the edge transfer function will kill all * facts, since we only want to consider facts that arise from going through the callee */ @Override public UnaryOperator<BitVectorVariable> getEdgeTransferFunction( BasicBlockInContext<IExplodedBasicBlock> src, BasicBlockInContext<IExplodedBasicBlock> dst) { if (isCallToReturnEdge(src, dst)) { return BitVectorKillAll.instance(); } else { return BitVectorIdentity.instance(); } } private boolean isCallToReturnEdge( BasicBlockInContext<IExplodedBasicBlock> src, BasicBlockInContext<IExplodedBasicBlock> dst) { SSAInstruction srcInst = src.getDelegate().getInstruction(); return srcInst instanceof SSAAbstractInvokeInstruction && src.getNode().equals(dst.getNode()); } } /** * run the analysis * * @return the solver used for the analysis, which contains the analysis result */ public BitVectorSolver<BasicBlockInContext<IExplodedBasicBlock>> analyze() { // the framework describes the dataflow problem, in particular the underlying graph and the // transfer functions BitVectorFramework<BasicBlockInContext<IExplodedBasicBlock>, Pair<CGNode, Integer>> framework = new BitVectorFramework<>(icfg, new TransferFunctions(), putInstrNumbering); BitVectorSolver<BasicBlockInContext<IExplodedBasicBlock>> solver = new BitVectorSolver<>(framework); try { solver.solve(null); } catch (CancelException e) { // this shouldn't happen assert false; } if (VERBOSE) { for (BasicBlockInContext<IExplodedBasicBlock> ebb : icfg) { System.out.println(ebb); System.out.println(ebb.getDelegate().getInstruction()); System.out.println(solver.getIn(ebb)); System.out.println(solver.getOut(ebb)); } } return solver; } /** * gets putstatic instruction corresponding to some fact number from a bitvector in the analysis * result */ public Pair<CGNode, Integer> getNodeAndInstrForNumber(int num) { return putInstrNumbering.getMappedObject(num); } }
8,566
38.118721
100
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/examples/analysis/dataflow/ContextSensitiveReachingDefs.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.examples.analysis.dataflow; import com.ibm.wala.classLoader.IField; import com.ibm.wala.dataflow.IFDS.ICFGSupergraph; import com.ibm.wala.dataflow.IFDS.IFlowFunction; import com.ibm.wala.dataflow.IFDS.IMergeFunction; import com.ibm.wala.dataflow.IFDS.IPartiallyBalancedFlowFunctions; import com.ibm.wala.dataflow.IFDS.ISupergraph; import com.ibm.wala.dataflow.IFDS.IUnaryFlowFunction; import com.ibm.wala.dataflow.IFDS.IdentityFlowFunction; import com.ibm.wala.dataflow.IFDS.KillEverything; import com.ibm.wala.dataflow.IFDS.PartiallyBalancedTabulationProblem; import com.ibm.wala.dataflow.IFDS.PartiallyBalancedTabulationSolver; import com.ibm.wala.dataflow.IFDS.PathEdge; import com.ibm.wala.dataflow.IFDS.TabulationDomain; import com.ibm.wala.dataflow.IFDS.TabulationResult; import com.ibm.wala.dataflow.IFDS.TabulationSolver; 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.cha.IClassHierarchy; import com.ibm.wala.ssa.SSAInstruction; import com.ibm.wala.ssa.SSAPutInstruction; import com.ibm.wala.ssa.analysis.IExplodedBasicBlock; import com.ibm.wala.util.CancelException; import com.ibm.wala.util.collections.HashSetFactory; import com.ibm.wala.util.collections.Pair; import com.ibm.wala.util.intset.IntSet; import com.ibm.wala.util.intset.MutableMapping; import com.ibm.wala.util.intset.MutableSparseIntSet; import java.util.Collection; /** * Computes interprocedural reaching definitions for static fields in a context-sensitive manner via * {@link TabulationSolver tabulation}. */ public class ContextSensitiveReachingDefs { /** used for resolving field references in putstatic instructions */ private final IClassHierarchy cha; /** the supergraph over which tabulation is performed */ private final ISupergraph<BasicBlockInContext<IExplodedBasicBlock>, CGNode> supergraph; /** the tabulation domain */ private final ReachingDefsDomain domain = new ReachingDefsDomain(); public ContextSensitiveReachingDefs(CallGraph cg) { this.cha = cg.getClassHierarchy(); // we use an ICFGSupergraph, which basically adapts ExplodedInterproceduralCFG to the // ISupergraph interface this.supergraph = ICFGSupergraph.make(cg); } /** controls numbering of putstatic instructions for use in tabulation */ private static class ReachingDefsDomain extends MutableMapping<Pair<CGNode, Integer>> implements TabulationDomain<Pair<CGNode, Integer>, BasicBlockInContext<IExplodedBasicBlock>> { private static final long serialVersionUID = 4014252274660361965L; @Override public boolean hasPriorityOver( PathEdge<BasicBlockInContext<IExplodedBasicBlock>> p1, PathEdge<BasicBlockInContext<IExplodedBasicBlock>> p2) { // don't worry about worklist priorities return false; } } private class ReachingDefsFlowFunctions implements IPartiallyBalancedFlowFunctions<BasicBlockInContext<IExplodedBasicBlock>> { private final ReachingDefsDomain domain; protected ReachingDefsFlowFunctions(ReachingDefsDomain domain) { this.domain = domain; } /** * the flow function for flow from a callee to caller where there was no flow from caller to * callee; just the identity function * * @see ReachingDefsProblem */ @Override public IFlowFunction getUnbalancedReturnFlowFunction( BasicBlockInContext<IExplodedBasicBlock> src, BasicBlockInContext<IExplodedBasicBlock> dest) { return IdentityFlowFunction.identity(); } /** flow function from caller to callee; just the identity function */ @Override public IUnaryFlowFunction getCallFlowFunction( BasicBlockInContext<IExplodedBasicBlock> src, BasicBlockInContext<IExplodedBasicBlock> dest, BasicBlockInContext<IExplodedBasicBlock> ret) { return IdentityFlowFunction.identity(); } /** * flow function from call node to return node when there are no targets for the call site; not * a case we are expecting */ @Override public IUnaryFlowFunction getCallNoneToReturnFlowFunction( BasicBlockInContext<IExplodedBasicBlock> src, BasicBlockInContext<IExplodedBasicBlock> dest) { // if we're missing callees, just keep what information we have return IdentityFlowFunction.identity(); } /** * flow function from call node to return node at a call site when callees exist. We kill * everything; surviving facts should flow out of the callee */ @Override public IUnaryFlowFunction getCallToReturnFlowFunction( BasicBlockInContext<IExplodedBasicBlock> src, BasicBlockInContext<IExplodedBasicBlock> dest) { return KillEverything.singleton(); } /** flow function for normal intraprocedural edges */ @Override public IUnaryFlowFunction getNormalFlowFunction( final BasicBlockInContext<IExplodedBasicBlock> src, BasicBlockInContext<IExplodedBasicBlock> dest) { final IExplodedBasicBlock ebb = src.getDelegate(); SSAInstruction instruction = ebb.getInstruction(); if (instruction instanceof SSAPutInstruction) { final SSAPutInstruction putInstr = (SSAPutInstruction) instruction; if (putInstr.isStatic()) { return new IUnaryFlowFunction() { @Override public IntSet getTargets(int d1) { // first, gen this statement int factNum = domain.getMappedIndex(Pair.make(src.getNode(), ebb.getFirstInstructionIndex())); assert factNum != -1; MutableSparseIntSet result = MutableSparseIntSet.makeEmpty(); result.add(factNum); // if incoming statement is some different statement that defs the same static field, // kill it; otherwise, keep it if (d1 != factNum) { IField staticField = cha.resolveField(putInstr.getDeclaredField()); assert staticField != null; Pair<CGNode, Integer> otherPutInstrAndNode = domain.getMappedObject(d1); SSAPutInstruction otherPutInstr = (SSAPutInstruction) otherPutInstrAndNode.fst.getIR() .getInstructions()[otherPutInstrAndNode.snd]; IField otherStaticField = cha.resolveField(otherPutInstr.getDeclaredField()); if (!staticField.equals(otherStaticField)) { result.add(d1); } } return result; } @Override public String toString() { return "Reaching Defs Normal Flow"; } }; } } // identity function when src block isn't for a putstatic return IdentityFlowFunction.identity(); } /** standard flow function from callee to caller; just identity */ @Override public IFlowFunction getReturnFlowFunction( BasicBlockInContext<IExplodedBasicBlock> call, BasicBlockInContext<IExplodedBasicBlock> src, BasicBlockInContext<IExplodedBasicBlock> dest) { return IdentityFlowFunction.identity(); } } /** * Definition of the reaching definitions tabulation problem. Note that we choose to make the * problem a <em>partially</em> balanced tabulation problem, where the solver is seeded with the * putstatic instructions themselves. The problem is partially balanced since a definition in a * callee used as a seed for the analysis may then reach a caller, yielding a "return" without a * corresponding "call." An alternative to this approach, used in the Reps-Horwitz-Sagiv POPL95 * paper, would be to "lift" the domain of putstatic instructions with a 0 (bottom) element, have * a 0->0 transition in all transfer functions, and then seed the analysis with the path edge * (main_entry, 0) -&gt; (main_entry, 0). We choose the partially-balanced approach to avoid * pollution of the flow functions. */ private class ReachingDefsProblem implements PartiallyBalancedTabulationProblem< BasicBlockInContext<IExplodedBasicBlock>, CGNode, Pair<CGNode, Integer>> { private final ReachingDefsFlowFunctions flowFunctions = new ReachingDefsFlowFunctions(domain); /** path edges corresponding to all putstatic instructions, used as seeds for the analysis */ private final Collection<PathEdge<BasicBlockInContext<IExplodedBasicBlock>>> initialSeeds = collectInitialSeeds(); /** * we use the entry block of the CGNode as the fake entry when propagating from callee to caller * with unbalanced parens */ @Override public BasicBlockInContext<IExplodedBasicBlock> getFakeEntry( BasicBlockInContext<IExplodedBasicBlock> node) { final CGNode cgNode = node.getNode(); return getFakeEntry(cgNode); } /** * we use the entry block of the CGNode as the "fake" entry when propagating from callee to * caller with unbalanced parens */ private BasicBlockInContext<IExplodedBasicBlock> getFakeEntry(final CGNode cgNode) { BasicBlockInContext<IExplodedBasicBlock>[] entriesForProcedure = supergraph.getEntriesForProcedure(cgNode); assert entriesForProcedure.length == 1; return entriesForProcedure[0]; } /** * collect the putstatic instructions in the call graph as {@link PathEdge} seeds for the * analysis */ private Collection<PathEdge<BasicBlockInContext<IExplodedBasicBlock>>> collectInitialSeeds() { Collection<PathEdge<BasicBlockInContext<IExplodedBasicBlock>>> result = HashSetFactory.make(); for (BasicBlockInContext<IExplodedBasicBlock> bb : supergraph) { IExplodedBasicBlock ebb = bb.getDelegate(); SSAInstruction instruction = ebb.getInstruction(); if (instruction instanceof SSAPutInstruction) { SSAPutInstruction putInstr = (SSAPutInstruction) instruction; if (putInstr.isStatic()) { final CGNode cgNode = bb.getNode(); Pair<CGNode, Integer> fact = Pair.make(cgNode, ebb.getFirstInstructionIndex()); int factNum = domain.add(fact); BasicBlockInContext<IExplodedBasicBlock> fakeEntry = getFakeEntry(cgNode); // note that the fact number used for the source of this path edge doesn't really matter result.add(PathEdge.createPathEdge(fakeEntry, factNum, bb, factNum)); } } } return result; } @Override public IPartiallyBalancedFlowFunctions<BasicBlockInContext<IExplodedBasicBlock>> getFunctionMap() { return flowFunctions; } @Override public TabulationDomain<Pair<CGNode, Integer>, BasicBlockInContext<IExplodedBasicBlock>> getDomain() { return domain; } /** we don't need a merge function; the default unioning of tabulation works fine */ @Override public IMergeFunction getMergeFunction() { return null; } @Override public ISupergraph<BasicBlockInContext<IExplodedBasicBlock>, CGNode> getSupergraph() { return supergraph; } @Override public Collection<PathEdge<BasicBlockInContext<IExplodedBasicBlock>>> initialSeeds() { return initialSeeds; } } /** perform the tabulation analysis and return the {@link TabulationResult} */ public TabulationResult<BasicBlockInContext<IExplodedBasicBlock>, CGNode, Pair<CGNode, Integer>> analyze() { PartiallyBalancedTabulationSolver< BasicBlockInContext<IExplodedBasicBlock>, CGNode, Pair<CGNode, Integer>> solver = PartiallyBalancedTabulationSolver.createPartiallyBalancedTabulationSolver( new ReachingDefsProblem(), null); TabulationResult<BasicBlockInContext<IExplodedBasicBlock>, CGNode, Pair<CGNode, Integer>> result = null; try { result = solver.solve(); } catch (CancelException e) { // this shouldn't happen assert false; } return result; } public ISupergraph<BasicBlockInContext<IExplodedBasicBlock>, CGNode> getSupergraph() { return supergraph; } public TabulationDomain<Pair<CGNode, Integer>, BasicBlockInContext<IExplodedBasicBlock>> getDomain() { return domain; } }
12,780
39.318612
100
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/examples/analysis/dataflow/IntraprocReachingDefs.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.examples.analysis.dataflow; import com.ibm.wala.classLoader.IField; import com.ibm.wala.dataflow.graph.AbstractMeetOperator; import com.ibm.wala.dataflow.graph.BitVectorFramework; import com.ibm.wala.dataflow.graph.BitVectorIdentity; import com.ibm.wala.dataflow.graph.BitVectorKillGen; import com.ibm.wala.dataflow.graph.BitVectorSolver; import com.ibm.wala.dataflow.graph.BitVectorUnion; import com.ibm.wala.dataflow.graph.ITransferFunctionProvider; import com.ibm.wala.fixpoint.BitVectorVariable; import com.ibm.wala.fixpoint.UnaryOperator; import com.ibm.wala.ipa.cha.IClassHierarchy; import com.ibm.wala.ssa.IR; import com.ibm.wala.ssa.SSAInstruction; import com.ibm.wala.ssa.SSAPutInstruction; import com.ibm.wala.ssa.analysis.ExplodedControlFlowGraph; import com.ibm.wala.ssa.analysis.IExplodedBasicBlock; import com.ibm.wala.util.CancelException; import com.ibm.wala.util.collections.HashMapFactory; import com.ibm.wala.util.collections.ObjectArrayMapping; import com.ibm.wala.util.intset.BitVector; import com.ibm.wala.util.intset.OrdinalSetMapping; import java.util.ArrayList; import java.util.Map; /** * Compute intraprocedural reaching defs of global variables, i.e., the defs are {@link * SSAPutInstruction}s on static state. * * @author manu */ public class IntraprocReachingDefs { /** the exploded control-flow graph on which to compute the analysis */ private final ExplodedControlFlowGraph ecfg; /** * maps the index of a putstatic IR instruction to a more compact numbering for use in bitvectors */ private final OrdinalSetMapping<Integer> putInstrNumbering; /** used to resolve references to fields in putstatic instructions */ private final IClassHierarchy cha; /** * maps each static field to the numbers of the statements (in {@link #putInstrNumbering}) that * define it; used for kills in flow functions */ private final Map<IField, BitVector> staticField2DefStatements = HashMapFactory.make(); private static final boolean VERBOSE = true; public IntraprocReachingDefs(ExplodedControlFlowGraph ecfg, IClassHierarchy cha) { this.ecfg = ecfg; this.cha = cha; this.putInstrNumbering = numberPutStatics(); } /** generate a numbering of the putstatic instructions */ private OrdinalSetMapping<Integer> numberPutStatics() { ArrayList<Integer> putInstrs = new ArrayList<>(); IR ir = ecfg.getIR(); SSAInstruction[] instructions = ir.getInstructions(); for (int i = 0; i < instructions.length; i++) { SSAInstruction instruction = instructions[i]; if (instruction instanceof SSAPutInstruction && ((SSAPutInstruction) instruction).isStatic()) { SSAPutInstruction putInstr = (SSAPutInstruction) instruction; // instrNum is the number that will be assigned to this putstatic int instrNum = putInstrs.size(); putInstrs.add(i); // also update the mapping of static fields to def'ing statements IField field = cha.resolveField(putInstr.getDeclaredField()); assert field != null; BitVector bv = staticField2DefStatements.get(field); if (bv == null) { bv = new BitVector(); staticField2DefStatements.put(field, bv); } bv.set(instrNum); } } return new ObjectArrayMapping<>(putInstrs.toArray(new Integer[0])); } private class TransferFunctions implements ITransferFunctionProvider<IExplodedBasicBlock, BitVectorVariable> { @Override public UnaryOperator<BitVectorVariable> getEdgeTransferFunction( IExplodedBasicBlock src, IExplodedBasicBlock dst) { throw new UnsupportedOperationException(); } /** our meet operator is set union */ @Override public AbstractMeetOperator<BitVectorVariable> getMeetOperator() { return BitVectorUnion.instance(); } @Override public UnaryOperator<BitVectorVariable> getNodeTransferFunction(IExplodedBasicBlock node) { SSAInstruction instruction = node.getInstruction(); int instructionIndex = node.getFirstInstructionIndex(); if (instruction instanceof SSAPutInstruction && ((SSAPutInstruction) instruction).isStatic()) { // kill all defs of the same static field, and gen this instruction final SSAPutInstruction putInstr = (SSAPutInstruction) instruction; final IField field = cha.resolveField(putInstr.getDeclaredField()); assert field != null; BitVector kill = staticField2DefStatements.get(field); BitVector gen = new BitVector(); gen.set(putInstrNumbering.getMappedIndex(instructionIndex)); return new BitVectorKillGen(kill, gen); } else { // identity function for non-putstatic instructions return BitVectorIdentity.instance(); } } @Override public boolean hasEdgeTransferFunctions() { // we only need transfer functions on nodes return false; } @Override public boolean hasNodeTransferFunctions() { return true; } } /** * run the analysis * * @return the solver used for the analysis, which contains the analysis result */ public BitVectorSolver<IExplodedBasicBlock> analyze() { // the framework describes the dataflow problem, in particular the underlying graph and the // transfer functions BitVectorFramework<IExplodedBasicBlock, Integer> framework = new BitVectorFramework<>(ecfg, new TransferFunctions(), putInstrNumbering); BitVectorSolver<IExplodedBasicBlock> solver = new BitVectorSolver<>(framework); try { solver.solve(null); } catch (CancelException e) { // this shouldn't happen assert false; } if (VERBOSE) { for (IExplodedBasicBlock ebb : ecfg) { System.out.println(ebb); System.out.println(ebb.getInstruction()); System.out.println(solver.getIn(ebb)); System.out.println(solver.getOut(ebb)); } } return solver; } }
6,356
35.959302
99
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/examples/analysis/dataflow/StaticInitializer.java
/* * Copyright (c) 2002 - 2014 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package com.ibm.wala.examples.analysis.dataflow; import com.ibm.wala.classLoader.IClass; import com.ibm.wala.dataflow.IFDS.ICFGSupergraph; import com.ibm.wala.dataflow.IFDS.IFlowFunction; import com.ibm.wala.dataflow.IFDS.IMergeFunction; import com.ibm.wala.dataflow.IFDS.IPartiallyBalancedFlowFunctions; import com.ibm.wala.dataflow.IFDS.ISupergraph; import com.ibm.wala.dataflow.IFDS.IUnaryFlowFunction; import com.ibm.wala.dataflow.IFDS.IdentityFlowFunction; import com.ibm.wala.dataflow.IFDS.KillEverything; import com.ibm.wala.dataflow.IFDS.PartiallyBalancedTabulationProblem; import com.ibm.wala.dataflow.IFDS.PartiallyBalancedTabulationSolver; import com.ibm.wala.dataflow.IFDS.PathEdge; import com.ibm.wala.dataflow.IFDS.TabulationDomain; import com.ibm.wala.dataflow.IFDS.TabulationResult; import com.ibm.wala.ipa.callgraph.CGNode; import com.ibm.wala.ipa.callgraph.CallGraph; import com.ibm.wala.ipa.cfg.BasicBlockInContext; import com.ibm.wala.ipa.cha.IClassHierarchy; 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.analysis.IExplodedBasicBlock; import com.ibm.wala.util.CancelException; import com.ibm.wala.util.collections.HashSetFactory; import com.ibm.wala.util.intset.IntSet; import com.ibm.wala.util.intset.MutableMapping; import com.ibm.wala.util.intset.MutableSparseIntSet; import java.util.Collection; import java.util.List; import java.util.Map; public class StaticInitializer { /** used for resolving field references in putstatic instructions */ private final IClassHierarchy cha; /** the supergraph over which tabulation is performed */ private final ISupergraph<BasicBlockInContext<IExplodedBasicBlock>, CGNode> supergraph; private final InitializerDomain domain = new InitializerDomain(); private Map<BasicBlockInContext<IExplodedBasicBlock>, List<IClass>> initialized; public final Map<BasicBlockInContext<IExplodedBasicBlock>, List<IClass>> getInitialized() { return initialized; } public StaticInitializer(CallGraph cg) { cha = cg.getClassHierarchy(); supergraph = ICFGSupergraph.make(cg); } /** controls numbering of putstatic instructions for use in tabulation */ private static class InitializerDomain extends MutableMapping<IClass> implements TabulationDomain<IClass, BasicBlockInContext<IExplodedBasicBlock>> { private static final long serialVersionUID = -1897766113586243833L; @Override public boolean hasPriorityOver( PathEdge<BasicBlockInContext<IExplodedBasicBlock>> p1, PathEdge<BasicBlockInContext<IExplodedBasicBlock>> p2) { // don't worry about worklist priorities return false; } } private class InitializerFlowFunctions implements IPartiallyBalancedFlowFunctions<BasicBlockInContext<IExplodedBasicBlock>> { private final InitializerDomain domain; protected InitializerFlowFunctions(InitializerDomain domain) { this.domain = domain; } /** * the flow function for flow from a callee to caller where there was no flow from caller to * callee; just the identity function * * @see ReachingDefsProblem */ @Override public IFlowFunction getUnbalancedReturnFlowFunction( BasicBlockInContext<IExplodedBasicBlock> src, BasicBlockInContext<IExplodedBasicBlock> dest) { return IdentityFlowFunction.identity(); } /** flow function from caller to callee; just the identity function */ @Override public IUnaryFlowFunction getCallFlowFunction( BasicBlockInContext<IExplodedBasicBlock> src, BasicBlockInContext<IExplodedBasicBlock> dest, BasicBlockInContext<IExplodedBasicBlock> ret) { return IdentityFlowFunction.identity(); } /** * flow function from call node to return node when there are no targets for the call site; not * a case we are expecting */ @Override public IUnaryFlowFunction getCallNoneToReturnFlowFunction( BasicBlockInContext<IExplodedBasicBlock> src, BasicBlockInContext<IExplodedBasicBlock> dest) { // if we're missing callees, just keep what information we have return IdentityFlowFunction.identity(); } /** * flow function from call node to return node at a call site when callees exist. We kill * everything; surviving facts should flow out of the callee */ @Override public IUnaryFlowFunction getCallToReturnFlowFunction( BasicBlockInContext<IExplodedBasicBlock> src, BasicBlockInContext<IExplodedBasicBlock> dest) { return KillEverything.singleton(); } /** flow function for normal intraprocedural edges */ @Override public IUnaryFlowFunction getNormalFlowFunction( final BasicBlockInContext<IExplodedBasicBlock> src, BasicBlockInContext<IExplodedBasicBlock> dest) { final IExplodedBasicBlock ebb = src.getDelegate(); SSAInstruction instruction = ebb.getInstruction(); if (instruction instanceof SSAPutInstruction) { final SSAPutInstruction putInstr = (SSAPutInstruction) instruction; if (putInstr.isStatic()) { return new IUnaryFlowFunction() { @Override public IntSet getTargets(int d1) { System.out.println(ebb); System.out.println(d1); // first, gen this statement int factNum = domain.getMappedIndex( cha.lookupClass(putInstr.getDeclaredField().getDeclaringClass())); System.out.println(factNum); assert factNum != -1; MutableSparseIntSet result = MutableSparseIntSet.makeEmpty(); result.add(factNum); // if incoming statement is some different statement that defs the same static field, // kill it; otherwise, keep it if (d1 != factNum) { result.add(d1); } return result; } @Override public String toString() { return "Initializer Normal Flow"; } }; } } else if (instruction instanceof SSAGetInstruction) { final SSAGetInstruction getInstr = (SSAGetInstruction) instruction; if (getInstr.isStatic()) { // Auf konstante �berpr�fen return new IUnaryFlowFunction() { @Override public IntSet getTargets(int d1) { // first, gen this statement int factNum = domain.getMappedIndex( cha.lookupClass(getInstr.getDeclaredField().getDeclaringClass())); assert factNum != -1; MutableSparseIntSet result = MutableSparseIntSet.makeEmpty(); result.add(factNum); // if incoming statement is some different statement that defs the same static field, // kill it; otherwise, keep it if (d1 != factNum) { result.add(d1); } return result; } @Override public String toString() { return "Initializer Normal Flow"; } }; } } else if (instruction instanceof SSANewInstruction) { final SSANewInstruction newInstr = (SSANewInstruction) instruction; return new IUnaryFlowFunction() { @Override public IntSet getTargets(int d1) { // first, gen this statement int factNum = domain.getMappedIndex(cha.lookupClass(newInstr.getConcreteType())); assert factNum != -1; MutableSparseIntSet result = MutableSparseIntSet.makeEmpty(); result.add(factNum); // if incoming statement is some different statement that defs the same static field, // kill it; otherwise, keep it if (d1 != factNum) { result.add(d1); } return result; } @Override public String toString() { return "Initializer Normal Flow"; } }; } else if (instruction instanceof SSAInvokeInstruction) { final SSAInvokeInstruction invInstr = (SSAInvokeInstruction) instruction; if (invInstr.isStatic()) { return new IUnaryFlowFunction() { @Override public IntSet getTargets(int d1) { System.out.println("Invoke!"); // first, gen this statement int factNum = domain.getMappedIndex( cha.lookupClass(invInstr.getDeclaredTarget().getDeclaringClass())); assert factNum != -1; MutableSparseIntSet result = MutableSparseIntSet.makeEmpty(); result.add(factNum); // if incoming statement is some different statement that defs the same static field, // kill it; otherwise, keep it if (d1 != factNum) { result.add(d1); } return result; } @Override public String toString() { return "Initializer Normal Flow"; } }; } } // identity function when src block isn't for a putstatic return IdentityFlowFunction.identity(); } /** standard flow function from callee to caller; just identity */ @Override public IFlowFunction getReturnFlowFunction( BasicBlockInContext<IExplodedBasicBlock> call, BasicBlockInContext<IExplodedBasicBlock> src, BasicBlockInContext<IExplodedBasicBlock> dest) { return IdentityFlowFunction.identity(); } } private class ReachingDefsProblem implements PartiallyBalancedTabulationProblem< BasicBlockInContext<IExplodedBasicBlock>, CGNode, IClass> { private final InitializerFlowFunctions flowFunctions = new InitializerFlowFunctions(domain); /** path edges corresponding to all putstatic instructions, used as seeds for the analysis */ private final Collection<PathEdge<BasicBlockInContext<IExplodedBasicBlock>>> initialSeeds = collectInitialSeeds(); /** * we use the entry block of the CGNode as the fake entry when propagating from callee to caller * with unbalanced parens */ @Override public BasicBlockInContext<IExplodedBasicBlock> getFakeEntry( BasicBlockInContext<IExplodedBasicBlock> node) { final CGNode cgNode = node.getNode(); return getFakeEntry(cgNode); } /** * we use the entry block of the CGNode as the "fake" entry when propagating from callee to * caller with unbalanced parens */ private BasicBlockInContext<IExplodedBasicBlock> getFakeEntry(final CGNode cgNode) { BasicBlockInContext<IExplodedBasicBlock>[] entriesForProcedure = supergraph.getEntriesForProcedure(cgNode); assert entriesForProcedure.length == 1; return entriesForProcedure[0]; } /** * collect the putstatic instructions in the call graph as {@link PathEdge} seeds for the * analysis */ private Collection<PathEdge<BasicBlockInContext<IExplodedBasicBlock>>> collectInitialSeeds() { Collection<PathEdge<BasicBlockInContext<IExplodedBasicBlock>>> result = HashSetFactory.make(); for (BasicBlockInContext<IExplodedBasicBlock> bb : supergraph) { IExplodedBasicBlock ebb = bb.getDelegate(); SSAInstruction instruction = ebb.getInstruction(); if (instruction instanceof SSAPutInstruction) { SSAPutInstruction putInstr = (SSAPutInstruction) instruction; if (putInstr.isStatic()) { final CGNode cgNode = bb.getNode(); IClass fact = cha.lookupClass(putInstr.getDeclaredField().getDeclaringClass()); int factNum = domain.add(fact); BasicBlockInContext<IExplodedBasicBlock> fakeEntry = getFakeEntry(cgNode); // note that the fact number used for the source of this path edge doesn't really matter result.add(PathEdge.createPathEdge(fakeEntry, factNum, bb, factNum)); } } else if (instruction instanceof SSAGetInstruction) { SSAGetInstruction getInstr = (SSAGetInstruction) instruction; if (getInstr.isStatic()) { final CGNode cgNode = bb.getNode(); IClass fact = cha.lookupClass(getInstr.getDeclaredField().getDeclaringClass()); int factNum = domain.add(fact); BasicBlockInContext<IExplodedBasicBlock> fakeEntry = getFakeEntry(cgNode); // note that the fact number used for the source of this path edge doesn't really matter result.add(PathEdge.createPathEdge(fakeEntry, factNum, bb, factNum)); } } else if (instruction instanceof SSANewInstruction) { SSANewInstruction newInstr = (SSANewInstruction) instruction; final CGNode cgNode = bb.getNode(); IClass fact = cha.lookupClass(newInstr.getConcreteType()); int factNum = domain.add(fact); BasicBlockInContext<IExplodedBasicBlock> fakeEntry = getFakeEntry(cgNode); // note that the fact number used for the source of this path edge doesn't really matter result.add(PathEdge.createPathEdge(fakeEntry, factNum, bb, factNum)); } else if (instruction instanceof SSAInvokeInstruction) { SSAInvokeInstruction invInstr = (SSAInvokeInstruction) instruction; if (invInstr.isStatic()) { final CGNode cgNode = bb.getNode(); IClass fact = cha.lookupClass(invInstr.getDeclaredTarget().getDeclaringClass()); int factNum = domain.add(fact); BasicBlockInContext<IExplodedBasicBlock> fakeEntry = getFakeEntry(cgNode); // note that the fact number used for the source of this path edge doesn't really matter result.add(PathEdge.createPathEdge(fakeEntry, factNum, bb, factNum)); } } } return result; } @Override public IPartiallyBalancedFlowFunctions<BasicBlockInContext<IExplodedBasicBlock>> getFunctionMap() { return flowFunctions; } @Override public TabulationDomain<IClass, BasicBlockInContext<IExplodedBasicBlock>> getDomain() { return domain; } /** we don't need a merge function; the default unioning of tabulation works fine */ @Override public IMergeFunction getMergeFunction() { return null; } @Override public ISupergraph<BasicBlockInContext<IExplodedBasicBlock>, CGNode> getSupergraph() { return supergraph; } @Override public Collection<PathEdge<BasicBlockInContext<IExplodedBasicBlock>>> initialSeeds() { return initialSeeds; } } /** perform the tabulation analysis and return the {@link TabulationResult} */ public TabulationResult<BasicBlockInContext<IExplodedBasicBlock>, CGNode, IClass> analyze() { PartiallyBalancedTabulationSolver<BasicBlockInContext<IExplodedBasicBlock>, CGNode, IClass> solver = PartiallyBalancedTabulationSolver.createPartiallyBalancedTabulationSolver( new ReachingDefsProblem(), null); TabulationResult<BasicBlockInContext<IExplodedBasicBlock>, CGNode, IClass> result = null; try { result = solver.solve(); } catch (CancelException e) { // this shouldn't happen assert false; } return result; } public ISupergraph<BasicBlockInContext<IExplodedBasicBlock>, CGNode> getSupergraph() { return supergraph; } public TabulationDomain<IClass, BasicBlockInContext<IExplodedBasicBlock>> getDomain() { return domain; } }
16,218
38.655257
100
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/examples/drivers/JavaViewerDriver.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.examples.drivers; import com.ibm.wala.classLoader.Language; import com.ibm.wala.core.tests.callGraph.CallGraphTestUtil; import com.ibm.wala.core.util.config.AnalysisScopeReader; import com.ibm.wala.core.util.io.FileProvider; import com.ibm.wala.core.viz.viewer.WalaViewer; import com.ibm.wala.ipa.callgraph.AnalysisCacheImpl; import com.ibm.wala.ipa.callgraph.AnalysisOptions; import com.ibm.wala.ipa.callgraph.AnalysisScope; import com.ibm.wala.ipa.callgraph.CallGraph; import com.ibm.wala.ipa.callgraph.CallGraphBuilderCancelException; import com.ibm.wala.ipa.callgraph.Entrypoint; import com.ibm.wala.ipa.callgraph.impl.Util; import com.ibm.wala.ipa.callgraph.propagation.InstanceKey; import com.ibm.wala.ipa.callgraph.propagation.PointerAnalysis; import com.ibm.wala.ipa.cha.ClassHierarchy; import com.ibm.wala.ipa.cha.ClassHierarchyException; import com.ibm.wala.ipa.cha.ClassHierarchyFactory; import com.ibm.wala.util.io.CommandLine; import java.io.File; import java.io.IOException; import java.util.Properties; /** * Allows viewing the ClassHeirarcy, CallGraph and Pointer Analysis built from a given classpath. * * @author yinnonh */ public class JavaViewerDriver { public static void main(String[] args) throws ClassHierarchyException, IOException, CallGraphBuilderCancelException { Properties p = CommandLine.parse(args); validateCommandLine(p); run( p.getProperty("appClassPath"), p.getProperty("exclusionFile", CallGraphTestUtil.REGRESSION_EXCLUSIONS)); } public static void validateCommandLine(Properties p) { if (p.get("appClassPath") == null) { throw new UnsupportedOperationException("expected command-line to include -appClassPath"); } } private static void run(String classPath, String exclusionFilePath) throws IOException, ClassHierarchyException, CallGraphBuilderCancelException { File exclusionFile = new FileProvider().getFile(exclusionFilePath); AnalysisScope scope = AnalysisScopeReader.instance.makeJavaBinaryAnalysisScope( classPath, exclusionFile != null ? exclusionFile : new File(CallGraphTestUtil.REGRESSION_EXCLUSIONS)); ClassHierarchy cha = ClassHierarchyFactory.make(scope); Iterable<Entrypoint> entrypoints = com.ibm.wala.ipa.callgraph.impl.Util.makeMainEntrypoints(cha); AnalysisOptions options = new AnalysisOptions(scope, entrypoints); // // // build the call graph // // com.ibm.wala.ipa.callgraph.CallGraphBuilder<InstanceKey> builder = Util.makeZeroCFABuilder(Language.JAVA, options, new AnalysisCacheImpl(), cha); CallGraph cg = builder.makeCallGraph(options, null); PointerAnalysis<InstanceKey> pa = builder.getPointerAnalysis(); @SuppressWarnings("unused") WalaViewer walaViewer = new WalaViewer(cg, pa); } }
3,253
37.282353
97
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/examples/drivers/PDFCallGraph.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.examples.drivers; import com.ibm.wala.classLoader.Language; import com.ibm.wala.core.tests.callGraph.CallGraphTestUtil; import com.ibm.wala.core.util.config.AnalysisScopeReader; import com.ibm.wala.core.util.io.FileProvider; import com.ibm.wala.core.viz.PDFViewUtil; import com.ibm.wala.examples.properties.WalaExamplesProperties; import com.ibm.wala.ipa.callgraph.AnalysisCacheImpl; import com.ibm.wala.ipa.callgraph.AnalysisOptions; import com.ibm.wala.ipa.callgraph.AnalysisScope; import com.ibm.wala.ipa.callgraph.CGNode; import com.ibm.wala.ipa.callgraph.CallGraph; import com.ibm.wala.ipa.callgraph.CallGraphStats; import com.ibm.wala.ipa.callgraph.Entrypoint; import com.ibm.wala.ipa.callgraph.impl.Util; import com.ibm.wala.ipa.callgraph.propagation.InstanceKey; import com.ibm.wala.ipa.callgraph.propagation.LocalPointerKey; import com.ibm.wala.ipa.cha.ClassHierarchy; import com.ibm.wala.ipa.cha.ClassHierarchyFactory; import com.ibm.wala.properties.WalaProperties; import com.ibm.wala.types.ClassLoaderReference; import com.ibm.wala.util.CancelException; import com.ibm.wala.util.WalaException; import com.ibm.wala.util.collections.HashSetFactory; import com.ibm.wala.util.debug.Assertions; import com.ibm.wala.util.graph.Graph; import com.ibm.wala.util.io.CommandLine; import com.ibm.wala.util.io.FileUtil; import com.ibm.wala.util.viz.DotUtil; import java.io.File; import java.io.IOException; import java.util.Collection; import java.util.Iterator; import java.util.Properties; import java.util.function.Predicate; /** * This simple example WALA application builds a call graph and fires off ghostview to visualize a * DOT representation. */ public class PDFCallGraph { public static boolean isDirectory(String appJar) { return new File(appJar).isDirectory(); } public static String findJarFiles(String[] directories) { Collection<String> result = HashSetFactory.make(); for (String directorie : directories) { for (File f : FileUtil.listFiles(directorie, ".*\\.jar", true)) { result.add(f.getAbsolutePath()); } } return composeString(result); } private static String composeString(Collection<String> s) { StringBuilder result = new StringBuilder(); Iterator<String> it = s.iterator(); for (int i = 0; i < s.size() - 1; i++) { result.append(it.next()); result.append(File.pathSeparator); } if (it.hasNext()) { result.append(it.next()); } return result.toString(); } private static final String PDF_FILE = "cg.pdf"; /** * Usage: args = "-appJar [jar file name] {-exclusionFile [exclusionFileName]}" The "jar file * name" should be something like "c:/temp/testdata/java_cup.jar" */ public static void main(String[] args) throws IllegalArgumentException, CancelException { run(args); } /** * Usage: args = "-appJar [jar file name] {-exclusionFile [exclusionFileName]}" The "jar file * name" should be something like "c:/temp/testdata/java_cup.jar" */ public static Process run(String[] args) throws IllegalArgumentException, CancelException { Properties p = CommandLine.parse(args); validateCommandLine(p); return run( p.getProperty("appJar"), p.getProperty("exclusionFile", CallGraphTestUtil.REGRESSION_EXCLUSIONS)); } /** @param appJar something like "c:/temp/testdata/java_cup.jar" */ public static Process run(String appJar, String exclusionFile) throws IllegalArgumentException, CancelException { try { Graph<CGNode> g = buildPrunedCallGraph(appJar, new FileProvider().getFile(exclusionFile)); Properties p = null; try { p = WalaExamplesProperties.loadProperties(); p.putAll(WalaProperties.loadProperties()); } catch (WalaException e) { e.printStackTrace(); Assertions.UNREACHABLE(); } String pdfFile = p.getProperty(WalaProperties.OUTPUT_DIR) + File.separatorChar + PDF_FILE; String dotExe = p.getProperty(WalaExamplesProperties.DOT_EXE); DotUtil.dotify(g, null, PDFTypeHierarchy.DOT_FILE, pdfFile, dotExe); String gvExe = p.getProperty(WalaExamplesProperties.PDFVIEW_EXE); return PDFViewUtil.launchPDFView(pdfFile, gvExe); } catch (WalaException | IOException e) { e.printStackTrace(); return null; } } /** * @param appJar something like "c:/temp/testdata/java_cup.jar" * @return a call graph */ public static Graph<CGNode> buildPrunedCallGraph(String appJar, File exclusionFile) throws WalaException, IllegalArgumentException, CancelException, IOException { AnalysisScope scope = AnalysisScopeReader.instance.makeJavaBinaryAnalysisScope( appJar, exclusionFile != null ? exclusionFile : new File(CallGraphTestUtil.REGRESSION_EXCLUSIONS)); ClassHierarchy cha = ClassHierarchyFactory.make(scope); Iterable<Entrypoint> entrypoints = com.ibm.wala.ipa.callgraph.impl.Util.makeMainEntrypoints(cha); AnalysisOptions options = new AnalysisOptions(scope, entrypoints); // // // build the call graph // // com.ibm.wala.ipa.callgraph.CallGraphBuilder<InstanceKey> builder = Util.makeZeroCFABuilder(Language.JAVA, options, new AnalysisCacheImpl(), cha); CallGraph cg = builder.makeCallGraph(options, null); System.err.println(CallGraphStats.getStats(cg)); Graph<CGNode> g = pruneForAppLoader(cg); return g; } public static Graph<CGNode> pruneForAppLoader(CallGraph g) { return PDFTypeHierarchy.pruneGraph(g, new ApplicationLoaderFilter()); } /** * Validate that the command-line arguments obey the expected usage. * * <p>Usage: * * <ul> * <li>args[0] : "-appJar" * <li>args[1] : something like "c:/temp/testdata/java_cup.jar" * </ul> * * @throws UnsupportedOperationException if command-line is malformed. */ public static void validateCommandLine(Properties p) { if (p.get("appJar") == null) { throw new UnsupportedOperationException("expected command-line to include -appJar"); } } /** * A filter that accepts WALA objects that "belong" to the application loader. * * <p>Currently supported WALA types include * * <ul> * <li>{@link CGNode} * <li>{@link LocalPointerKey} * </ul> */ private static class ApplicationLoaderFilter implements Predicate<CGNode> { @Override public boolean test(CGNode o) { if (o == null) return false; return o.getMethod() .getDeclaringClass() .getClassLoader() .getReference() .equals(ClassLoaderReference.Application); } } }
7,087
33.076923
98
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/examples/drivers/PDFControlDependenceGraph.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.examples.drivers; import com.ibm.wala.cfg.cdg.ControlDependenceGraph; import com.ibm.wala.classLoader.IMethod; import com.ibm.wala.core.tests.callGraph.CallGraphTestUtil; import com.ibm.wala.core.util.config.AnalysisScopeReader; import com.ibm.wala.core.util.io.FileProvider; import com.ibm.wala.core.util.strings.StringStuff; import com.ibm.wala.core.viz.PDFViewUtil; import com.ibm.wala.examples.properties.WalaExamplesProperties; import com.ibm.wala.ipa.callgraph.AnalysisCacheImpl; import com.ibm.wala.ipa.callgraph.AnalysisOptions; import com.ibm.wala.ipa.callgraph.AnalysisScope; import com.ibm.wala.ipa.callgraph.IAnalysisCacheView; import com.ibm.wala.ipa.callgraph.impl.Everywhere; import com.ibm.wala.ipa.cha.ClassHierarchy; import com.ibm.wala.ipa.cha.ClassHierarchyFactory; import com.ibm.wala.properties.WalaProperties; import com.ibm.wala.ssa.IR; import com.ibm.wala.ssa.ISSABasicBlock; import com.ibm.wala.ssa.SSAOptions; import com.ibm.wala.types.MethodReference; import com.ibm.wala.util.WalaException; import com.ibm.wala.util.debug.Assertions; import com.ibm.wala.util.viz.DotUtil; import java.io.File; import java.io.IOException; import java.util.Properties; /** * This simple example application builds a WALA CDG and fires off ghostview to viz a DOT * representation. * * @author sfink */ public class PDFControlDependenceGraph { public static final boolean SANITIZE_CFG = false; public static final String PDF_FILE = "cdg.pdf"; /** * Usage: GVControlDependenceGraph -appJar [jar file name] -sig [method signature] The "jar file * name" should be something like "c:/temp/testdata/java_cup.jar" The signature should be * something like "java_cup.lexer.advance()V" */ public static void main(String[] args) throws IOException { run(args); } /** * @param args -appJar [jar file name] -sig [method signature] The "jar file name" should be * something like "c:/temp/testdata/java_cup.jar" The signature should be something like * "java_cup.lexer.advance()V" */ public static Process run(String[] args) throws IOException { validateCommandLine(args); return run(args[1], args[3]); } /** * @param appJar should be something like "c:/temp/testdata/java_cup.jar" * @param methodSig should be something like "java_cup.lexer.advance()V" */ public static Process run(String appJar, String methodSig) throws IOException { try { if (PDFCallGraph.isDirectory(appJar)) { appJar = PDFCallGraph.findJarFiles(new String[] {appJar}); } AnalysisScope scope = AnalysisScopeReader.instance.makeJavaBinaryAnalysisScope( appJar, new FileProvider().getFile(CallGraphTestUtil.REGRESSION_EXCLUSIONS)); ClassHierarchy cha = ClassHierarchyFactory.make(scope); MethodReference mr = StringStuff.makeMethodReference(methodSig); IMethod m = cha.resolveMethod(mr); if (m == null) { System.err.println("could not resolve " + mr); throw new RuntimeException(); } AnalysisOptions options = new AnalysisOptions(); options.getSSAOptions().setPiNodePolicy(SSAOptions.getAllBuiltInPiNodes()); IAnalysisCacheView cache = new AnalysisCacheImpl(options.getSSAOptions()); IR ir = cache.getIR(m, Everywhere.EVERYWHERE); if (ir == null) { Assertions.UNREACHABLE("Null IR for " + m); } System.err.println(ir); ControlDependenceGraph<ISSABasicBlock> cdg = new ControlDependenceGraph<>(ir.getControlFlowGraph()); Properties wp = null; try { wp = WalaProperties.loadProperties(); wp.putAll(WalaExamplesProperties.loadProperties()); } catch (WalaException e) { e.printStackTrace(); Assertions.UNREACHABLE(); } String psFile = wp.getProperty(WalaProperties.OUTPUT_DIR) + File.separatorChar + PDFControlDependenceGraph.PDF_FILE; String dotFile = wp.getProperty(WalaProperties.OUTPUT_DIR) + File.separatorChar + PDFTypeHierarchy.DOT_FILE; String dotExe = wp.getProperty(WalaExamplesProperties.DOT_EXE); String gvExe = wp.getProperty(WalaExamplesProperties.PDFVIEW_EXE); DotUtil.<ISSABasicBlock>dotify(cdg, PDFViewUtil.makeIRDecorator(ir), dotFile, psFile, dotExe); return PDFViewUtil.launchPDFView(psFile, gvExe); } catch (WalaException e) { // TODO Auto-generated catch block e.printStackTrace(); return null; } } /** * Validate that the command-line arguments obey the expected usage. * * <p>Usage: * * <ul> * <li>args[0] : "-appJar" * <li>args[1] : something like "c:/temp/testdata/java_cup.jar" * <li>args[2] : "-sig" * <li>args[3] : a method signature like "java_cup.lexer.advance()V" * </ul> * * @throws UnsupportedOperationException if command-line is malformed. */ static void validateCommandLine(String[] args) { if (args.length != 4) { throw new UnsupportedOperationException("must have at exactly 4 command-line arguments"); } if (!args[0].equals("-appJar")) { throw new UnsupportedOperationException( "invalid command-line, args[0] should be -appJar, but is " + args[0]); } if (!args[2].equals("-sig")) { throw new UnsupportedOperationException( "invalid command-line, args[2] should be -sig, but is " + args[0]); } } }
5,867
34.563636
100
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/examples/drivers/PDFSDG.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.examples.drivers; import com.ibm.wala.classLoader.Language; import com.ibm.wala.core.tests.callGraph.CallGraphTestUtil; import com.ibm.wala.core.util.config.AnalysisScopeReader; import com.ibm.wala.core.util.io.FileProvider; import com.ibm.wala.core.viz.PDFViewUtil; import com.ibm.wala.examples.properties.WalaExamplesProperties; import com.ibm.wala.ipa.callgraph.AnalysisCacheImpl; import com.ibm.wala.ipa.callgraph.AnalysisOptions; import com.ibm.wala.ipa.callgraph.AnalysisScope; import com.ibm.wala.ipa.callgraph.CallGraph; import com.ibm.wala.ipa.callgraph.CallGraphBuilder; import com.ibm.wala.ipa.callgraph.Entrypoint; import com.ibm.wala.ipa.callgraph.impl.Util; import com.ibm.wala.ipa.callgraph.propagation.InstanceKey; import com.ibm.wala.ipa.callgraph.propagation.PointerAnalysis; import com.ibm.wala.ipa.cha.ClassHierarchy; import com.ibm.wala.ipa.cha.ClassHierarchyFactory; import com.ibm.wala.ipa.slicer.HeapStatement; import com.ibm.wala.ipa.slicer.MethodEntryStatement; import com.ibm.wala.ipa.slicer.MethodExitStatement; import com.ibm.wala.ipa.slicer.SDG; import com.ibm.wala.ipa.slicer.Slicer.ControlDependenceOptions; import com.ibm.wala.ipa.slicer.Slicer.DataDependenceOptions; import com.ibm.wala.ipa.slicer.Statement; import com.ibm.wala.properties.WalaProperties; import com.ibm.wala.util.CancelException; import com.ibm.wala.util.WalaException; import com.ibm.wala.util.debug.Assertions; import com.ibm.wala.util.graph.Graph; import com.ibm.wala.util.graph.GraphIntegrity; import com.ibm.wala.util.graph.GraphIntegrity.UnsoundGraphException; import com.ibm.wala.util.graph.GraphSlicer; import com.ibm.wala.util.io.CommandLine; import com.ibm.wala.util.viz.DotUtil; import com.ibm.wala.util.viz.NodeDecorator; import java.io.File; import java.io.IOException; import java.util.Properties; import java.util.function.Predicate; /** * This simple example WALA application builds an SDG and fires off ghostview to viz a DOT * representation. * * @author sfink */ public class PDFSDG { private static final String PDF_FILE = "sdg.pdf"; /** * Usage: GVSDG -appJar [jar file name] -mainclass [main class] * * <p>The "jar file name" should be something like "c:/temp/testdata/java_cup.jar" */ public static void main(String[] args) throws IllegalArgumentException, CancelException, IOException { run(args); } public static Process run(String[] args) throws IllegalArgumentException, CancelException, IOException { Properties p = CommandLine.parse(args); validateCommandLine(p); return run( p.getProperty("appJar"), p.getProperty("mainClass"), getDataDependenceOptions(p), getControlDependenceOptions(p)); } public static DataDependenceOptions getDataDependenceOptions(Properties p) { String d = p.getProperty("dd", "full"); for (DataDependenceOptions result : DataDependenceOptions.values()) { if (d.equals(result.getName())) { return result; } } Assertions.UNREACHABLE("unknown data datapendence option: " + d); return null; } public static ControlDependenceOptions getControlDependenceOptions(Properties p) { String d = p.getProperty("cd", "full"); for (ControlDependenceOptions result : ControlDependenceOptions.values()) { if (d.equals(result.getName())) { return result; } } Assertions.UNREACHABLE("unknown control datapendence option: " + d); return null; } /** @param appJar something like "c:/temp/testdata/java_cup.jar" */ public static Process run( String appJar, String mainClass, DataDependenceOptions dOptions, ControlDependenceOptions cOptions) throws IllegalArgumentException, CancelException, IOException { try { AnalysisScope scope = AnalysisScopeReader.instance.makeJavaBinaryAnalysisScope( appJar, new FileProvider().getFile(CallGraphTestUtil.REGRESSION_EXCLUSIONS)); // generate a WALA-consumable wrapper around the incoming scope object ClassHierarchy cha = ClassHierarchyFactory.make(scope); Iterable<Entrypoint> entrypoints = com.ibm.wala.ipa.callgraph.impl.Util.makeMainEntrypoints(cha, mainClass); AnalysisOptions options = CallGraphTestUtil.makeAnalysisOptions(scope, entrypoints); CallGraphBuilder<InstanceKey> builder = Util.makeZeroOneCFABuilder(Language.JAVA, options, new AnalysisCacheImpl(), cha); CallGraph cg = builder.makeCallGraph(options, null); final PointerAnalysis<InstanceKey> pointerAnalysis = builder.getPointerAnalysis(); SDG<?> sdg = new SDG<>(cg, pointerAnalysis, dOptions, cOptions); try { GraphIntegrity.check(sdg); } catch (UnsoundGraphException e1) { e1.printStackTrace(); Assertions.UNREACHABLE(); } System.err.println(sdg); Properties p = null; try { p = WalaExamplesProperties.loadProperties(); p.putAll(WalaProperties.loadProperties()); } catch (WalaException e) { e.printStackTrace(); Assertions.UNREACHABLE(); } String psFile = p.getProperty(WalaProperties.OUTPUT_DIR) + File.separatorChar + PDF_FILE; String dotExe = p.getProperty(WalaExamplesProperties.DOT_EXE); Graph<Statement> g = pruneSDG(sdg); DotUtil.dotify(g, makeNodeDecorator(), PDFTypeHierarchy.DOT_FILE, psFile, dotExe); String gvExe = p.getProperty(WalaExamplesProperties.PDFVIEW_EXE); return PDFViewUtil.launchPDFView(psFile, gvExe); } catch (WalaException e) { // TODO Auto-generated catch block e.printStackTrace(); return null; } } private static Graph<Statement> pruneSDG(final SDG<?> sdg) { Predicate<Statement> f = s -> { if (s.getNode().equals(sdg.getCallGraph().getFakeRootNode())) { return false; } else if (s instanceof MethodExitStatement || s instanceof MethodEntryStatement) { return false; } else { return true; } }; return GraphSlicer.prune(sdg, f); } private static NodeDecorator<Statement> makeNodeDecorator() { return s -> { switch (s.getKind()) { case HEAP_PARAM_CALLEE: case HEAP_PARAM_CALLER: case HEAP_RET_CALLEE: case HEAP_RET_CALLER: HeapStatement h = (HeapStatement) s; return s.getKind() + "\\n" + h.getNode() + "\\n" + h.getLocation(); case EXC_RET_CALLEE: case EXC_RET_CALLER: case NORMAL: case NORMAL_RET_CALLEE: case NORMAL_RET_CALLER: case PARAM_CALLEE: case PARAM_CALLER: case PHI: default: return s.toString(); } }; } /** * Validate that the command-line arguments obey the expected usage. * * <p>Usage: * * <ul> * <li>args[0] : "-appJar" * <li>args[1] : something like "c:/temp/testdata/java_cup.jar" * <li>args[2] : "-mainClass" * <li>args[3] : something like "Lslice/TestRecursion" * </ul> * * @throws UnsupportedOperationException if command-line is malformed. */ static void validateCommandLine(Properties p) { if (p.get("appJar") == null) { throw new UnsupportedOperationException("expected command-line to include -appJar"); } if (p.get("mainClass") == null) { throw new UnsupportedOperationException("expected command-line to include -mainClass"); } } }
7,871
34.459459
95
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/examples/drivers/PDFSlice.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.examples.drivers; import com.ibm.wala.classLoader.Language; import com.ibm.wala.core.tests.callGraph.CallGraphTestUtil; import com.ibm.wala.core.util.config.AnalysisScopeReader; import com.ibm.wala.core.util.io.FileProvider; import com.ibm.wala.core.viz.PDFViewUtil; import com.ibm.wala.examples.properties.WalaExamplesProperties; import com.ibm.wala.ipa.callgraph.AnalysisCacheImpl; import com.ibm.wala.ipa.callgraph.AnalysisOptions; import com.ibm.wala.ipa.callgraph.AnalysisScope; import com.ibm.wala.ipa.callgraph.CGNode; import com.ibm.wala.ipa.callgraph.CallGraph; import com.ibm.wala.ipa.callgraph.CallGraphBuilder; import com.ibm.wala.ipa.callgraph.Entrypoint; import com.ibm.wala.ipa.callgraph.impl.Util; import com.ibm.wala.ipa.callgraph.propagation.InstanceKey; import com.ibm.wala.ipa.callgraph.propagation.PointerAnalysis; import com.ibm.wala.ipa.callgraph.util.CallGraphSearchUtil; import com.ibm.wala.ipa.cha.ClassHierarchy; import com.ibm.wala.ipa.cha.ClassHierarchyFactory; import com.ibm.wala.ipa.slicer.HeapStatement; import com.ibm.wala.ipa.slicer.NormalReturnCaller; import com.ibm.wala.ipa.slicer.NormalStatement; import com.ibm.wala.ipa.slicer.ParamCallee; import com.ibm.wala.ipa.slicer.ParamCaller; import com.ibm.wala.ipa.slicer.SDG; import com.ibm.wala.ipa.slicer.Slicer; import com.ibm.wala.ipa.slicer.Slicer.ControlDependenceOptions; import com.ibm.wala.ipa.slicer.Slicer.DataDependenceOptions; import com.ibm.wala.ipa.slicer.SlicerUtil; import com.ibm.wala.ipa.slicer.Statement; import com.ibm.wala.ipa.slicer.Statement.Kind; import com.ibm.wala.properties.WalaProperties; import com.ibm.wala.ssa.SSAAbstractInvokeInstruction; import com.ibm.wala.ssa.SSAInstruction; import com.ibm.wala.ssa.SSAInvokeInstruction; import com.ibm.wala.types.TypeReference; import com.ibm.wala.util.CancelException; import com.ibm.wala.util.WalaException; import com.ibm.wala.util.debug.Assertions; import com.ibm.wala.util.graph.Graph; import com.ibm.wala.util.graph.GraphIntegrity; import com.ibm.wala.util.graph.GraphIntegrity.UnsoundGraphException; import com.ibm.wala.util.graph.GraphSlicer; import com.ibm.wala.util.io.CommandLine; import com.ibm.wala.util.viz.DotUtil; import com.ibm.wala.util.viz.NodeDecorator; import java.io.File; import java.io.IOException; import java.util.Collection; import java.util.Properties; /** * This simple example WALA application computes a slice (see {@link Slicer}) and fires off the PDF * viewer to view a dot-ted representation of the slice. * * <p>This is an example program on how to use the slicer. * * <p>See the 'PDFSlice' launcher included in the 'launchers' directory. * * @see Slicer * @author sfink */ public class PDFSlice { /** Name of the postscript file generated by dot */ private static final String PDF_FILE = "slice.pdf"; /** * Usage: PDFSlice -appJar [jar file name] -mainClass [main class] -srcCaller [method name] * -srcCallee [method name] -dd [data dependence options] -cd [control dependence options] -dir * [forward|backward] * * <ul> * <li>"jar file name" should be something like "c:/temp/testdata/java_cup.jar" * <li>"main class" should beshould be something like "c:/temp/testdata/java_cup.jar" * <li>"method name" should be the name of a method. This takes a slice from the statement that * calls "srcCallee" from "srcCaller" * <li>"data dependence options" can be one of "-full", "-no_base_ptrs", "-no_base_no_heap", * "-no_heap", "-no_base_no_heap_no_cast", or "-none". * <li>"control dependence options" can be "-full" or "-none" * <li>the -dir argument tells whether to compute a forwards or backwards slice. * </ul> * * @see com.ibm.wala.ipa.slicer.Slicer.DataDependenceOptions */ public static void main(String[] args) throws IllegalArgumentException, CancelException, IOException { run(args); } /** see {@link #main(String[])} for command-line arguments */ public static Process run(String[] args) throws IllegalArgumentException, CancelException, IOException { // parse the command-line into a Properties object Properties p = CommandLine.parse(args); // validate that the command-line has the expected format validateCommandLine(p); // run the applications return run( p.getProperty("appJar"), p.getProperty("mainClass"), p.getProperty("srcCaller"), p.getProperty("srcCallee"), goBackward(p), PDFSDG.getDataDependenceOptions(p), PDFSDG.getControlDependenceOptions(p)); } /** Should the slice be a backwards slice? */ private static boolean goBackward(Properties p) { return !p.getProperty("dir", "backward").equals("forward"); } /** * Compute a slice from a call statements, dot it, and fire off the PDF viewer to visualize the * result * * @param appJar should be something like "c:/temp/testdata/java_cup.jar" * @param mainClass should be something like "c:/temp/testdata/java_cup.jar" * @param srcCaller name of the method containing the statement of interest * @param srcCallee name of the method called by the statement of interest * @param goBackward do a backward slice? * @param dOptions options controlling data dependence * @param cOptions options controlling control dependence * @return a Process running the PDF viewer to visualize the dot'ted representation of the slice */ public static Process run( String appJar, String mainClass, String srcCaller, String srcCallee, boolean goBackward, DataDependenceOptions dOptions, ControlDependenceOptions cOptions) throws IllegalArgumentException, CancelException, IOException { try { // create an analysis scope representing the appJar as a J2SE application AnalysisScope scope = AnalysisScopeReader.instance.makeJavaBinaryAnalysisScope( appJar, new FileProvider().getFile(CallGraphTestUtil.REGRESSION_EXCLUSIONS)); // build a class hierarchy, call graph, and system dependence graph ClassHierarchy cha = ClassHierarchyFactory.make(scope); Iterable<Entrypoint> entrypoints = com.ibm.wala.ipa.callgraph.impl.Util.makeMainEntrypoints(cha, mainClass); AnalysisOptions options = CallGraphTestUtil.makeAnalysisOptions(scope, entrypoints); CallGraphBuilder<InstanceKey> builder = Util.makeVanillaZeroOneCFABuilder(Language.JAVA, options, new AnalysisCacheImpl(), cha); // CallGraphBuilder builder = Util.makeZeroOneCFABuilder(options, new // AnalysisCache(), cha, scope); CallGraph cg = builder.makeCallGraph(options, null); SDG<InstanceKey> sdg = new SDG<>(cg, builder.getPointerAnalysis(), dOptions, cOptions); // find the call statement of interest CGNode callerNode = CallGraphSearchUtil.findMethod(cg, srcCaller); Statement s = SlicerUtil.findCallTo(callerNode, srcCallee); System.err.println("Statement: " + s); // compute the slice as a collection of statements Collection<Statement> slice = null; if (goBackward) { final PointerAnalysis<InstanceKey> pointerAnalysis = builder.getPointerAnalysis(); slice = Slicer.computeBackwardSlice(s, cg, pointerAnalysis, dOptions, cOptions); } else { // for forward slices ... we actually slice from the return value of // calls. s = getReturnStatementForCall(s); final PointerAnalysis<InstanceKey> pointerAnalysis = builder.getPointerAnalysis(); slice = Slicer.computeForwardSlice(s, cg, pointerAnalysis, dOptions, cOptions); } SlicerUtil.dumpSlice(slice); // create a view of the SDG restricted to nodes in the slice Graph<Statement> g = pruneSDG(sdg, slice); sanityCheck(slice, g); // load Properties from standard WALA and the WALA examples project Properties p = null; try { p = WalaExamplesProperties.loadProperties(); p.putAll(WalaProperties.loadProperties()); } catch (WalaException e) { e.printStackTrace(); Assertions.UNREACHABLE(); } // create a dot representation. String psFile = p.getProperty(WalaProperties.OUTPUT_DIR) + File.separatorChar + PDF_FILE; String dotExe = p.getProperty(WalaExamplesProperties.DOT_EXE); DotUtil.dotify(g, makeNodeDecorator(), PDFTypeHierarchy.DOT_FILE, psFile, dotExe); // fire off the PDF viewer String gvExe = p.getProperty(WalaExamplesProperties.PDFVIEW_EXE); return PDFViewUtil.launchPDFView(psFile, gvExe); } catch (WalaException e) { // something bad happened. e.printStackTrace(); return null; } } /** * check that g is a well-formed graph, and that it contains exactly the number of nodes in the * slice */ private static void sanityCheck(Collection<Statement> slice, Graph<Statement> g) { try { GraphIntegrity.check(g); } catch (UnsoundGraphException e1) { e1.printStackTrace(); Assertions.UNREACHABLE(); } Assertions.productionAssertion( g.getNumberOfNodes() == slice.size(), "panic " + g.getNumberOfNodes() + " " + slice.size()); } /** If s is a call statement, return the statement representing the normal return from s */ public static Statement getReturnStatementForCall(Statement s) { if (s.getKind() == Kind.NORMAL) { NormalStatement n = (NormalStatement) s; SSAInstruction st = n.getInstruction(); if (st instanceof SSAInvokeInstruction) { SSAAbstractInvokeInstruction call = (SSAAbstractInvokeInstruction) st; if (call.getCallSite().getDeclaredTarget().getReturnType().equals(TypeReference.Void)) { throw new IllegalArgumentException( "this driver computes forward slices from the return value of calls.\n" + "Method " + call.getCallSite().getDeclaredTarget().getSignature() + " returns void."); } return new NormalReturnCaller(s.getNode(), n.getInstructionIndex()); } else { return s; } } else { return s; } } /** return a view of the sdg restricted to the statements in the slice */ public static Graph<Statement> pruneSDG(SDG<InstanceKey> sdg, final Collection<Statement> slice) { return GraphSlicer.prune(sdg, slice::contains); } /** @return a NodeDecorator that decorates statements in a slice for a dot-ted representation */ public static NodeDecorator<Statement> makeNodeDecorator() { return s -> { switch (s.getKind()) { case HEAP_PARAM_CALLEE: case HEAP_PARAM_CALLER: case HEAP_RET_CALLEE: case HEAP_RET_CALLER: HeapStatement h = (HeapStatement) s; return s.getKind() + "\\n" + h.getNode() + "\\n" + h.getLocation(); case NORMAL: NormalStatement n = (NormalStatement) s; return n.getInstruction() + "\\n" + n.getNode().getMethod().getSignature(); case PARAM_CALLEE: ParamCallee paramCallee = (ParamCallee) s; return s.getKind() + " " + paramCallee.getValueNumber() + "\\n" + s.getNode().getMethod().getName(); case PARAM_CALLER: ParamCaller paramCaller = (ParamCaller) s; return s.getKind() + " " + paramCaller.getValueNumber() + "\\n" + s.getNode().getMethod().getName() + "\\n" + paramCaller.getInstruction().getCallSite().getDeclaredTarget().getName(); case EXC_RET_CALLEE: case EXC_RET_CALLER: case NORMAL_RET_CALLEE: case NORMAL_RET_CALLER: case PHI: default: return s.toString(); } }; } /** * Validate that the command-line arguments obey the expected usage. * * <p>Usage: * * <ul> * <li>args[0] : "-appJar" * <li>args[1] : something like "c:/temp/testdata/java_cup.jar" * <li>args[2] : "-mainClass" * <li>args[3] : something like "Lslice/TestRecursion" * * <li>args[4] : "-srcCallee" * <li>args[5] : something like "print" * * <li>args[4] : "-srcCaller" * <li>args[5] : something like "main" * </ul> * * @throws UnsupportedOperationException if command-line is malformed. */ static void validateCommandLine(Properties p) { if (p.get("appJar") == null) { throw new UnsupportedOperationException("expected command-line to include -appJar"); } if (p.get("mainClass") == null) { throw new UnsupportedOperationException("expected command-line to include -mainClass"); } if (p.get("srcCallee") == null) { throw new UnsupportedOperationException("expected command-line to include -srcCallee"); } if (p.get("srcCaller") == null) { throw new UnsupportedOperationException("expected command-line to include -srcCaller"); } } }
13,402
39.370482
100
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/examples/drivers/PDFTypeHierarchy.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.examples.drivers; import com.ibm.wala.classLoader.IClass; import com.ibm.wala.core.tests.callGraph.CallGraphTestUtil; import com.ibm.wala.core.util.config.AnalysisScopeReader; import com.ibm.wala.core.util.io.FileProvider; import com.ibm.wala.core.viz.PDFViewUtil; import com.ibm.wala.examples.properties.WalaExamplesProperties; import com.ibm.wala.ipa.callgraph.AnalysisScope; import com.ibm.wala.ipa.cha.ClassHierarchy; import com.ibm.wala.ipa.cha.ClassHierarchyFactory; import com.ibm.wala.ipa.cha.IClassHierarchy; import com.ibm.wala.properties.WalaProperties; import com.ibm.wala.types.ClassLoaderReference; import com.ibm.wala.util.WalaException; import com.ibm.wala.util.collections.CollectionFilter; import com.ibm.wala.util.debug.Assertions; import com.ibm.wala.util.graph.Graph; import com.ibm.wala.util.graph.GraphSlicer; import com.ibm.wala.util.graph.impl.SlowSparseNumberedGraph; import com.ibm.wala.util.viz.DotUtil; import java.io.File; import java.io.IOException; import java.util.Collection; import java.util.Properties; import java.util.function.Predicate; /** * This simple example WALA application builds a TypeHierarchy and fires off ghostview to viz a DOT * representation. * * @author sfink */ public class PDFTypeHierarchy { // This example takes one command-line argument, so args[1] should be the "-classpath" parameter static final int CLASSPATH_INDEX = 1; public static final String DOT_FILE = "temp.dt"; private static final String PDF_FILE = "th.pdf"; public static Properties p; static { try { p = WalaProperties.loadProperties(); p.putAll(WalaExamplesProperties.loadProperties()); } catch (WalaException e) { e.printStackTrace(); Assertions.UNREACHABLE(); } } public static void main(String[] args) throws IOException { run(args); } public static Process run(String[] args) throws IOException { try { validateCommandLine(args); String classpath = args[CLASSPATH_INDEX]; AnalysisScope scope = AnalysisScopeReader.instance.makeJavaBinaryAnalysisScope( classpath, new FileProvider().getFile(CallGraphTestUtil.REGRESSION_EXCLUSIONS)); // invoke WALA to build a class hierarchy ClassHierarchy cha = ClassHierarchyFactory.make(scope); Graph<IClass> g = typeHierarchy2Graph(cha); g = pruneForAppLoader(g); String dotFile = p.getProperty(WalaProperties.OUTPUT_DIR) + File.separatorChar + DOT_FILE; String pdfFile = p.getProperty(WalaProperties.OUTPUT_DIR) + File.separatorChar + PDF_FILE; String dotExe = p.getProperty(WalaExamplesProperties.DOT_EXE); String gvExe = p.getProperty(WalaExamplesProperties.PDFVIEW_EXE); DotUtil.dotify(g, null, dotFile, pdfFile, dotExe); return PDFViewUtil.launchPDFView(pdfFile, gvExe); } catch (WalaException e) { // TODO Auto-generated catch block e.printStackTrace(); return null; } } public static <T> Graph<T> pruneGraph(Graph<T> g, Predicate<T> f) { Collection<T> slice = GraphSlicer.slice(g, f); return GraphSlicer.prune(g, new CollectionFilter<>(slice)); } /** Restrict g to nodes from the Application loader */ public static Graph<IClass> pruneForAppLoader(Graph<IClass> g) { Predicate<IClass> f = c -> c.getClassLoader().getReference().equals(ClassLoaderReference.Application); return pruneGraph(g, f); } /** * Validate that the command-line arguments obey the expected usage. * * <p>Usage: args[0] : "-classpath" args[1] : String, a ";"-delimited class path * * @throws UnsupportedOperationException if command-line is malformed. */ public static void validateCommandLine(String[] args) { if (args.length < 2) { throw new UnsupportedOperationException("must have at least 2 command-line arguments"); } if (!args[0].equals("-classpath")) { throw new UnsupportedOperationException( "invalid command-line, args[0] should be -classpath, but is " + args[0]); } } /** * Return a view of an {@link IClassHierarchy} as a {@link Graph}, with edges from classes to * immediate subtypes */ public static Graph<IClass> typeHierarchy2Graph(IClassHierarchy cha) { Graph<IClass> result = SlowSparseNumberedGraph.make(); for (IClass c : cha) { result.addNode(c); } for (IClass c : cha) { for (IClass x : cha.getImmediateSubclasses(c)) { result.addEdge(c, x); } if (c.isInterface()) { for (IClass x : cha.getImplementors(c.getReference())) { result.addEdge(c, x); } } } return result; } }
5,050
33.360544
99
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/examples/drivers/PDFWalaIR.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.examples.drivers; import com.ibm.wala.classLoader.IMethod; import com.ibm.wala.core.tests.callGraph.CallGraphTestUtil; import com.ibm.wala.core.util.config.AnalysisScopeReader; import com.ibm.wala.core.util.io.FileProvider; import com.ibm.wala.core.util.strings.StringStuff; import com.ibm.wala.core.viz.PDFViewUtil; import com.ibm.wala.examples.properties.WalaExamplesProperties; import com.ibm.wala.ipa.callgraph.AnalysisCacheImpl; import com.ibm.wala.ipa.callgraph.AnalysisOptions; import com.ibm.wala.ipa.callgraph.AnalysisScope; import com.ibm.wala.ipa.callgraph.IAnalysisCacheView; import com.ibm.wala.ipa.callgraph.impl.Everywhere; import com.ibm.wala.ipa.cha.ClassHierarchy; import com.ibm.wala.ipa.cha.ClassHierarchyFactory; import com.ibm.wala.properties.WalaProperties; import com.ibm.wala.ssa.IR; import com.ibm.wala.ssa.SSAOptions; import com.ibm.wala.types.MethodReference; import com.ibm.wala.util.WalaException; import com.ibm.wala.util.debug.Assertions; import java.io.File; import java.io.IOException; import java.util.Properties; /** * This simple example application builds a WALA IR and fires off a PDF viewer to visualize a DOT * representation. */ public class PDFWalaIR { public static final String PDF_FILE = "ir.pdf"; /** * Usage: PDFWalaIR -appJar [jar file name] -sig [method signature] The "jar file name" should be * something like "c:/temp/testdata/java_cup.jar" The signature should be something like * "java_cup.lexer.advance()V" */ public static void main(String[] args) throws IOException { run(args); } /** * @param args -appJar [jar file name] -sig [method signature] The "jar file name" should be * something like "c:/temp/testdata/java_cup.jar" The signature should be something like * "java_cup.lexer.advance()V" */ public static Process run(String[] args) throws IOException { validateCommandLine(args); return run(args[1], args[3]); } /** * @param appJar should be something like "c:/temp/testdata/java_cup.jar" * @param methodSig should be something like "java_cup.lexer.advance()V" */ public static Process run(String appJar, String methodSig) throws IOException { try { if (PDFCallGraph.isDirectory(appJar)) { appJar = PDFCallGraph.findJarFiles(new String[] {appJar}); } // Build an AnalysisScope which represents the set of classes to analyze. In particular, // we will analyze the contents of the appJar jar file and the Java standard libraries. AnalysisScope scope = AnalysisScopeReader.instance.makeJavaBinaryAnalysisScope( appJar, new FileProvider().getFile(CallGraphTestUtil.REGRESSION_EXCLUSIONS)); // Build a class hierarchy representing all classes to analyze. This step will read the class // files and organize them into a tree. ClassHierarchy cha = ClassHierarchyFactory.make(scope); // Create a name representing the method whose IR we will visualize MethodReference mr = StringStuff.makeMethodReference(methodSig); // Resolve the method name into the IMethod, the canonical representation of the method // information. IMethod m = cha.resolveMethod(mr); if (m == null) { Assertions.UNREACHABLE("could not resolve " + mr); } // Set up options which govern analysis choices. In particular, we will use all Pi nodes when // building the IR. AnalysisOptions options = new AnalysisOptions(); options.getSSAOptions().setPiNodePolicy(SSAOptions.getAllBuiltInPiNodes()); // Create an object which caches IRs and related information, reconstructing them lazily on // demand. IAnalysisCacheView cache = new AnalysisCacheImpl(options.getSSAOptions()); // Build the IR and cache it. IR ir = cache.getIR(m, Everywhere.EVERYWHERE); if (ir == null) { Assertions.UNREACHABLE("Null IR for " + m); } System.err.println(ir); Properties wp = null; try { wp = WalaProperties.loadProperties(); wp.putAll(WalaExamplesProperties.loadProperties()); } catch (WalaException e) { e.printStackTrace(); Assertions.UNREACHABLE(); } String psFile = wp.getProperty(WalaProperties.OUTPUT_DIR) + File.separatorChar + PDFWalaIR.PDF_FILE; String dotFile = wp.getProperty(WalaProperties.OUTPUT_DIR) + File.separatorChar + PDFTypeHierarchy.DOT_FILE; String dotExe = wp.getProperty(WalaExamplesProperties.DOT_EXE); String gvExe = wp.getProperty(WalaExamplesProperties.PDFVIEW_EXE); return PDFViewUtil.ghostviewIR(cha, ir, psFile, dotFile, dotExe, gvExe); } catch (WalaException e) { // TODO Auto-generated catch block e.printStackTrace(); return null; } } /** * Validate that the command-line arguments obey the expected usage. * * <p>Usage: * * <ul> * <li>args[0] : "-appJar" * <li>args[1] : something like "c:/temp/testdata/java_cup.jar" * <li>args[2] : "-sig" * <li>args[3] : a method signature like "java_cup.lexer.advance()V" * </ul> * * @throws UnsupportedOperationException if command-line is malformed. */ public static void validateCommandLine(String[] args) { if (args.length != 4) { throw new UnsupportedOperationException("must have at exactly 4 command-line arguments"); } if (!args[0].equals("-appJar")) { throw new UnsupportedOperationException( "invalid command-line, args[0] should be -appJar, but is " + args[0]); } if (!args[2].equals("-sig")) { throw new UnsupportedOperationException( "invalid command-line, args[2] should be -sig, but is " + args[0]); } } }
6,182
36.246988
100
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/examples/drivers/ScopeFileCallGraph.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.examples.drivers; import com.ibm.wala.classLoader.IClass; import com.ibm.wala.classLoader.IMethod; import com.ibm.wala.core.util.config.AnalysisScopeReader; import com.ibm.wala.core.util.strings.StringStuff; import com.ibm.wala.core.util.warnings.Warnings; import com.ibm.wala.ipa.callgraph.AnalysisCacheImpl; import com.ibm.wala.ipa.callgraph.AnalysisOptions; import com.ibm.wala.ipa.callgraph.AnalysisOptions.ReflectionOptions; import com.ibm.wala.ipa.callgraph.AnalysisScope; import com.ibm.wala.ipa.callgraph.CallGraph; import com.ibm.wala.ipa.callgraph.CallGraphBuilder; import com.ibm.wala.ipa.callgraph.CallGraphBuilderCancelException; import com.ibm.wala.ipa.callgraph.CallGraphStats; import com.ibm.wala.ipa.callgraph.Entrypoint; import com.ibm.wala.ipa.callgraph.IAnalysisCacheView; import com.ibm.wala.ipa.callgraph.impl.DefaultEntrypoint; import com.ibm.wala.ipa.callgraph.impl.Util; import com.ibm.wala.ipa.callgraph.propagation.InstanceKey; import com.ibm.wala.ipa.cha.ClassHierarchyException; import com.ibm.wala.ipa.cha.ClassHierarchyFactory; import com.ibm.wala.ipa.cha.IClassHierarchy; import com.ibm.wala.types.ClassLoaderReference; import com.ibm.wala.types.TypeReference; import com.ibm.wala.util.io.CommandLine; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Collection; import java.util.Properties; /** * Driver that constructs a call graph for an application specified via a scope file. Useful for * getting some code to copy-paste. */ public class ScopeFileCallGraph { /** * Usage: ScopeFileCallGraph -scopeFile file_path [-entryClass class_name | -mainClass class_name] * * <p>If given -mainClass, uses main() method of class_name as entrypoint. If given -entryClass, * uses all public methods of class_name. */ public static void main(String[] args) throws IOException, ClassHierarchyException, IllegalArgumentException, CallGraphBuilderCancelException { long start = System.currentTimeMillis(); Properties p = CommandLine.parse(args); String scopeFile = p.getProperty("scopeFile"); String entryClass = p.getProperty("entryClass"); String mainClass = p.getProperty("mainClass"); String dump = p.getProperty("dump"); if (mainClass != null && entryClass != null) { throw new IllegalArgumentException("only specify one of mainClass or entryClass"); } // use exclusions to eliminate certain library packages File exclusionsFile = null; AnalysisScope scope = AnalysisScopeReader.instance.readJavaScope( scopeFile, exclusionsFile, ScopeFileCallGraph.class.getClassLoader()); IClassHierarchy cha = ClassHierarchyFactory.make(scope); System.out.println(cha.getNumberOfClasses() + " classes"); System.out.println(Warnings.asString()); Warnings.clear(); AnalysisOptions options = new AnalysisOptions(); Iterable<Entrypoint> entrypoints = entryClass != null ? makePublicEntrypoints(cha, entryClass) : Util.makeMainEntrypoints(cha, mainClass); options.setEntrypoints(entrypoints); // you can dial down reflection handling if you like options.setReflectionOptions(ReflectionOptions.NONE); IAnalysisCacheView cache = new AnalysisCacheImpl(); // other builders can be constructed with different Util methods CallGraphBuilder<InstanceKey> builder = Util.makeZeroOneContainerCFABuilder(options, cache, cha); // CallGraphBuilder builder = Util.makeNCFABuilder(2, options, cache, cha, scope); // CallGraphBuilder builder = Util.makeVanillaNCFABuilder(2, options, cache, cha, scope); System.out.println("building call graph..."); CallGraph cg = builder.makeCallGraph(options, null); long end = System.currentTimeMillis(); System.out.println("done"); if (dump != null) { System.err.println(cg); } System.out.println("took " + (end - start) + "ms"); System.out.println(CallGraphStats.getStats(cg)); } private static Iterable<Entrypoint> makePublicEntrypoints( IClassHierarchy cha, String entryClass) { Collection<Entrypoint> result = new ArrayList<>(); IClass klass = cha.lookupClass( TypeReference.findOrCreate( ClassLoaderReference.Application, StringStuff.deployment2CanonicalTypeString(entryClass))); for (IMethod m : klass.getDeclaredMethods()) { if (m.isPublic()) { result.add(new DefaultEntrypoint(m, cha)); } } return result; } }
4,935
41.188034
100
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/examples/properties/WalaExamplesProperties.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.examples.properties; import com.ibm.wala.core.util.io.FileProvider; import com.ibm.wala.properties.WalaProperties; import java.io.File; import java.net.URL; import java.util.Properties; public final class WalaExamplesProperties { public static final String PDFVIEW_EXE = "pdfview_exe"; // $NON-NLS-1$ public static final String DOT_EXE = "dot_exe"; // $NON-NLS-1$ public static final String PROPERTY_FILENAME = "wala.examples.properties"; // $NON-NLS-1$ public static Properties loadProperties() { try { Properties result = WalaProperties.loadPropertiesFromFile( WalaExamplesProperties.class.getClassLoader(), PROPERTY_FILENAME); return result; } catch (Exception e) { e.printStackTrace(); throw new IllegalStateException("Unable to set up wala examples properties ", e); } } public static String getWalaCoreTestsHomeDirectory() { final URL url = WalaExamplesProperties.class.getClassLoader().getResource(PROPERTY_FILENAME); if (url == null) { throw new IllegalStateException("failed to find URL for wala.examples.properties"); } return new File(new FileProvider().filePathFromURL(url)) .getParentFile() .getParentFile() .getAbsolutePath(); } }
1,671
30.54717
97
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/ipa/callgraph/AnalysisCache.java
/* * Copyright (c) 2007 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package com.ibm.wala.ipa.callgraph; import com.ibm.wala.classLoader.IMethod; import com.ibm.wala.core.util.ref.ReferenceCleanser; import com.ibm.wala.ipa.callgraph.impl.Everywhere; import com.ibm.wala.ssa.DefUse; import com.ibm.wala.ssa.IR; import com.ibm.wala.ssa.IRFactory; import com.ibm.wala.ssa.SSACache; import com.ibm.wala.ssa.SSAOptions; /** * A place to hold onto caches of various analysis artifacts. * * <p>Someday this should maybe go away? */ public class AnalysisCache implements IAnalysisCacheView { private final IRFactory<IMethod> irFactory; private final SSACache ssaCache; private final SSAOptions ssaOptions; public AnalysisCache(IRFactory<IMethod> irFactory, SSAOptions ssaOptions, SSACache cache) { super(); this.ssaOptions = ssaOptions; this.irFactory = irFactory; this.ssaCache = cache; ReferenceCleanser.registerCache(this); } @Override public void invalidate(IMethod method, Context C) { ssaCache.invalidate(method, C); } public SSACache getSSACache() { return ssaCache; } public SSAOptions getSSAOptions() { return ssaOptions; } @Override public IRFactory<IMethod> getIRFactory() { return irFactory; } /** @see com.ibm.wala.ipa.callgraph.IAnalysisCacheView#getIR(com.ibm.wala.classLoader.IMethod) */ @Override public IR getIR(IMethod method, Context context) { if (method == null) { throw new IllegalArgumentException("method is null"); } return ssaCache.findOrCreateIR(method, context, ssaOptions); } @Override public IR getIR(IMethod m) { return getIR(m, Everywhere.EVERYWHERE); } @Override public DefUse getDefUse(IR ir) { if (ir == null) { throw new IllegalArgumentException("ir is null"); } return ssaCache.findOrCreateDU(ir, Everywhere.EVERYWHERE); } @Override public void clear() { ssaCache.wipe(); } }
2,258
24.965517
99
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/ipa/callgraph/AnalysisCacheImpl.java
/* * Copyright (c) 2007 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package com.ibm.wala.ipa.callgraph; import com.ibm.wala.classLoader.IMethod; import com.ibm.wala.ssa.AuxiliaryCache; import com.ibm.wala.ssa.DefaultIRFactory; import com.ibm.wala.ssa.IRFactory; import com.ibm.wala.ssa.SSACache; import com.ibm.wala.ssa.SSAOptions; public class AnalysisCacheImpl extends AnalysisCache { public AnalysisCacheImpl(IRFactory<IMethod> irFactory, SSAOptions ssaOptions) { super( irFactory, ssaOptions, new SSACache(irFactory, new AuxiliaryCache(), new AuxiliaryCache())); } public AnalysisCacheImpl(SSAOptions ssaOptions) { this(new DefaultIRFactory(), ssaOptions); } public AnalysisCacheImpl(IRFactory<IMethod> irFactory) { this(irFactory, new AnalysisOptions().getSSAOptions()); } public AnalysisCacheImpl() { this(new DefaultIRFactory()); } }
1,187
29.461538
100
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/ipa/callgraph/AnalysisOptions.java
/* * Copyright (c) 2002 - 2006 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package com.ibm.wala.ipa.callgraph; import com.ibm.wala.analysis.reflection.ReflectionContextInterpreter; import com.ibm.wala.analysis.reflection.ReflectionContextSelector; import com.ibm.wala.ipa.callgraph.impl.ExplicitCallGraph; import com.ibm.wala.ipa.callgraph.propagation.ReflectionHandler; import com.ibm.wala.ssa.SSAOptions; /** * Basic interface for options that control call graph generation. * * <p>TODO: This class should be refactored into an abstract base class and language-specific * subclasses. */ public class AnalysisOptions { /** An object that represents the analysis scope */ private AnalysisScope analysisScope; /** An object that identifies the entrypoints for the call graph */ private Iterable<? extends Entrypoint> entrypoints; /** Policy that determines types allocated at new statements. */ private ClassTargetSelector classTargetSelector; /** Policy that determines methods called at call sites. */ private MethodTargetSelector methodTargetSelector; /** * A tuning parameter; how may new equations must be added before doing a new topological sort? */ private int minEquationsForTopSort = 100; /** * A tuning parameter; by what percentage must the number of equations grow before we perform a * topological sort? */ private double topologicalGrowthFactor = 0.5; /** * A tuning parameter: how many evaluations are allowed to take place between topological * re-orderings. The idea is that many evaluations may be a sign of a bad ordering, even when few * new equations are being added. */ private int maxEvalBetweenTopo = 1000000000; /** options for handling reflection during call graph construction */ public enum ReflectionOptions { FULL("full", Integer.MAX_VALUE, false, false, false), APPLICATION_GET_METHOD("application_get_method", Integer.MAX_VALUE, false, false, true), NO_FLOW_TO_CASTS("no_flow_to_casts", 0, false, false, false), NO_FLOW_TO_CASTS_APPLICATION_GET_METHOD( "no_flow_to_casts_application_get_method", 0, false, false, true), NO_METHOD_INVOKE("no_method_invoke", Integer.MAX_VALUE, true, false, false), NO_FLOW_TO_CASTS_NO_METHOD_INVOKE("no_flow_to_casts_no_method_invoke", 0, true, false, false), ONE_FLOW_TO_CASTS_NO_METHOD_INVOKE("one_flow_to_casts_no_method_invoke", 1, true, false, false), ONE_FLOW_TO_CASTS_APPLICATION_GET_METHOD( "one_flow_to_casts_application_get_method", 1, false, false, true), MULTI_FLOW_TO_CASTS_APPLICATION_GET_METHOD( "multi_flow_to_casts_application_get_method", 100, false, false, true), NO_STRING_CONSTANTS("no_string_constants", Integer.MAX_VALUE, false, true, false), STRING_ONLY("string_constants", 0, true, false, true), NONE("none", 0, true, true, true); private final String name; /** how many times should flows from newInstance() calls to casts be analyzed? */ private final int numFlowToCastIterations; /** should calls to Method.invoke() be ignored? */ private final boolean ignoreMethodInvoke; /** should calls to Class.getMethod() be modeled only for application classes? */ private final boolean applicationClassesOnly; /** should calls to reflective methods with String constant arguments be ignored? */ private final boolean ignoreStringConstants; ReflectionOptions( String name, int numFlowToCastIterations, boolean ignoreMethodInvoke, boolean ignoreInterpretCalls, boolean applicationClassesOnly) { this.name = name; this.numFlowToCastIterations = numFlowToCastIterations; this.ignoreMethodInvoke = ignoreMethodInvoke; this.ignoreStringConstants = ignoreInterpretCalls; this.applicationClassesOnly = applicationClassesOnly; } public String getName() { return name; } public int getNumFlowToCastIterations() { return numFlowToCastIterations; } public boolean isIgnoreMethodInvoke() { return ignoreMethodInvoke; } public boolean isIgnoreStringConstants() { return ignoreStringConstants; } public boolean isApplicationClassesOnly() { return applicationClassesOnly; } } /** * Should call graph construction attempt to handle reflection via detection of flows to casts, * analysis of string constant parameters to reflective methods, etc.? * * @see ReflectionHandler * @see ReflectionContextInterpreter * @see ReflectionContextSelector */ private ReflectionOptions reflectionOptions = ReflectionOptions.FULL; /** Should call graph construction handle possible invocations of static initializer methods? */ private boolean handleStaticInit = true; /** Options governing SSA construction */ private SSAOptions ssaOptions = new SSAOptions(); /** * Use distinct instance keys for distinct string constants? * * <p>TODO: Probably, this option should moved somewhere into the creation of instance keys. * However, those factories are created within the various builders right now, and this is the * most convenient place for an engine user to set an option which the creation of instance keys * later picks up. */ private boolean useConstantSpecificKeys = false; /** * Should analysis of lexical scoping consider call stacks? * * <p>TODO: this option does not apply to all languages. We could have a separation into core * engine options and language-specific options. * * <p>(be careful with multithreaded languages, as threading can break the stack discipline this * option may assume) */ private boolean useStacksForLexicalScoping = false; /** * Should global variables be considered lexically-scoped from the root node? * * <p>TODO: this option does not apply to all languages. We could have a separation into core * engine options and language-specific options. * * <p>(be careful with multithreaded languages, as threading can break the stack discipline this * option may assume) */ private boolean useLexicalScopingForGlobals = false; /** * Should analysis try to understand the results of string constants flowing to a + operator? Note * that this option does not apply to Java bytecode analysis, since the + operators have been * compiled away for that. It is used for the Java CAst front end. */ private boolean traceStringConstants = false; /** * This numerical value indicates the maximum number of nodes that any {@link CallGraph} build * with this {@link AnalysisOptions} object is allowed to have. During {@link CallGraph} * construction, once {@code maxNumberOfNodes} {@link CGNode} objects have been added to the * {@link CallGraph}, no more {@link CGNode} objects will be added. By default, {@code * maxNumberOfNodes} is set to {@code -1}, which indicates that no restrictions are in place. See * also {@link ExplicitCallGraph}. */ private long maxNumberOfNodes = -1; /** Should call graph construction handle arrays of zero-length differently? */ private boolean handleZeroLengthArray = true; // SJF: I'm not sure these factories and caches belong here. // TODO: figure out how to clean this up. public AnalysisOptions() {} public AnalysisOptions(AnalysisScope scope, Iterable<? extends Entrypoint> e) { this.analysisScope = scope; this.entrypoints = e; } public AnalysisScope getAnalysisScope() { return analysisScope; } public void setAnalysisScope(AnalysisScope analysisScope) { this.analysisScope = analysisScope; } /** TODO: this really should go away. The entrypoints don't belong here. */ public Iterable<? extends Entrypoint> getEntrypoints() { return entrypoints; } public void setEntrypoints(Iterable<? extends Entrypoint> entrypoints) { this.entrypoints = entrypoints; } public long getMaxNumberOfNodes() { return maxNumberOfNodes; } public void setMaxNumberOfNodes(long maxNumberOfNodes) { this.maxNumberOfNodes = maxNumberOfNodes; } /** @return Policy that determines methods called at call sites. */ public MethodTargetSelector getMethodTargetSelector() { return methodTargetSelector; } /** @return Policy that determines types allocated at new statements. */ public ClassTargetSelector getClassTargetSelector() { return classTargetSelector; } /** * install a method target selector * * @param x an object which controls the policy for selecting the target at a call site */ public void setSelector(MethodTargetSelector x) { methodTargetSelector = x; } /** * install a class target selector * * @param x an object which controls the policy for selecting the allocated object at a new site */ public void setSelector(ClassTargetSelector x) { classTargetSelector = x; } /** * @return the mininum number of equations that the pointer analysis system must contain before * the solver will try to topologically sore */ public int getMinEquationsForTopSort() { return minEquationsForTopSort; } /** * @param i the mininum number of equations that the pointer analysis system must contain before * the solver will try to topologically sore */ public void setMinEquationsForTopSort(int i) { minEquationsForTopSort = i; } /** * @return the maximum number of evaluations that the pointer analysis solver will perform before * topologically resorting the system */ public int getMaxEvalBetweenTopo() { return maxEvalBetweenTopo; } /** @return a fraction x s.t. the solver will resort the system when it grows by a factor of x */ public double getTopologicalGrowthFactor() { return topologicalGrowthFactor; } /** * @param i the maximum number of evaluations that the pointer analysis solver will perform before * topologically resorting the system */ public void setMaxEvalBetweenTopo(int i) { maxEvalBetweenTopo = i; } /** @param d a fraction x s.t. the solver will resort the system when it grows by a factor of x */ public void setTopologicalGrowthFactor(double d) { topologicalGrowthFactor = d; } /** @return options governing SSA construction */ public SSAOptions getSSAOptions() { return ssaOptions; } /** @param ssaOptions options governing SSA construction */ public void setSSAOptions(SSAOptions ssaOptions) { this.ssaOptions = ssaOptions; } /** Use distinct instance keys for distinct string constants? */ public boolean getUseConstantSpecificKeys() { return useConstantSpecificKeys; } /** Use distinct instance keys for distinct string constants? */ public void setUseConstantSpecificKeys(boolean useConstantSpecificKeys) { this.useConstantSpecificKeys = useConstantSpecificKeys; } /** Should analysis of lexical scoping consider call stacks? */ public boolean getUseStacksForLexicalScoping() { return useStacksForLexicalScoping; } /** Should analysis of lexical scoping consider call stacks? */ public void setUseStacksForLexicalScoping(boolean v) { useStacksForLexicalScoping = v; } /** Should global variables be considered lexically-scoped from the root node? */ public boolean getUseLexicalScopingForGlobals() { return useLexicalScopingForGlobals; } /** Should global variables be considered lexically-scoped from the root node? */ public void setUseLexicalScopingForGlobals(boolean v) { useLexicalScopingForGlobals = v; } /** * Should analysis try to understand the results of string constants flowing to a + operator? Note * that this option does not apply to Java bytecode analysis, since the + operators have been * compiled away for that. It is used for the Java CAst front end. */ public void setTraceStringConstants(boolean v) { traceStringConstants = v; } /** * Should analysis try to understand the results of string constants flowing to a + operator? Note * that this option does not apply to Java bytecode analysis, since the + operators have been * compiled away for that. It is used for the Java CAst front end. */ public boolean getTraceStringConstants() { return traceStringConstants; } /** * Should call graph construction attempt to handle reflection via detection of flows to casts, * analysis of string constant parameters to reflective methods, etc.? * * @see ReflectionHandler * @see ReflectionContextInterpreter * @see ReflectionContextSelector */ public ReflectionOptions getReflectionOptions() { return reflectionOptions; } /** * Should call graph construction attempt to handle reflection via detection of flows to casts, * analysis of string constant parameters to reflective methods, etc.? * * @see ReflectionHandler * @see ReflectionContextInterpreter * @see ReflectionContextSelector */ public void setReflectionOptions(ReflectionOptions reflectionOptions) { this.reflectionOptions = reflectionOptions; } /** Should call graph construction handle possible invocations of static initializer methods? */ public boolean getHandleStaticInit() { return handleStaticInit; } /** Should call graph construction handle possible invocations of static initializer methods? */ public void setHandleStaticInit(boolean handleStaticInit) { this.handleStaticInit = handleStaticInit; } /** Should call graph construction handle arrays of zero-length differently? */ public boolean getHandleZeroLengthArray() { return handleZeroLengthArray; } /** Should call graph construction handle arrays of zero-length differently? */ public void setHandleZeroLengthArray(boolean handleZeroLengthArray) { this.handleZeroLengthArray = handleZeroLengthArray; } }
14,178
34.625628
100
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/ipa/callgraph/AnalysisScope.java
/* * Copyright (c) 2002 - 2006 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package com.ibm.wala.ipa.callgraph; import com.ibm.wala.classLoader.ArrayClassLoader; import com.ibm.wala.classLoader.BinaryDirectoryTreeModule; import com.ibm.wala.classLoader.ClassFileModule; import com.ibm.wala.classLoader.IClassLoader; import com.ibm.wala.classLoader.JarFileModule; import com.ibm.wala.classLoader.JarStreamModule; import com.ibm.wala.classLoader.Language; import com.ibm.wala.classLoader.Module; import com.ibm.wala.classLoader.SourceDirectoryTreeModule; import com.ibm.wala.classLoader.SourceFileModule; import com.ibm.wala.core.util.strings.Atom; import com.ibm.wala.core.util.strings.ImmutableByteArray; import com.ibm.wala.shrike.shrikeCT.InvalidClassFileException; import com.ibm.wala.types.ClassLoaderReference; import com.ibm.wala.types.Descriptor; import com.ibm.wala.types.MethodReference; import com.ibm.wala.types.TypeName; import com.ibm.wala.types.TypeReference; import com.ibm.wala.util.PlatformUtil; import com.ibm.wala.util.collections.FilterIterator; import com.ibm.wala.util.collections.HashMapFactory; import com.ibm.wala.util.collections.HashSetFactory; import com.ibm.wala.util.collections.MapIterator; import com.ibm.wala.util.collections.MapUtil; import com.ibm.wala.util.config.SetOfClasses; import com.ibm.wala.util.debug.Assertions; import com.ibm.wala.util.io.RtJar; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.NotSerializableException; import java.nio.file.Files; import java.nio.file.Path; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.jar.Attributes; import java.util.jar.JarFile; import java.util.jar.Manifest; /** * Base class that represents a set of files to analyze. * * <p>The analysis scope is partitioned by class loader. There are three pre-defined class loader * scopes: * * <ul> * <li>Primordial (for {@code rt.jar}, the core classes) * <li>Extension (for extension libraries in $JRE/lib/ext) * <li>Application (for the classes of the application) * </ul> * * Each class loader will load a set of classes described by a {@link Module}. */ public class AnalysisScope { private static final int DEBUG_LEVEL = 0; public static final Atom PRIMORDIAL = Atom.findOrCreateUnicodeAtom("Primordial"); public static final Atom EXTENSION = Atom.findOrCreateUnicodeAtom("Extension"); public static final Atom APPLICATION = Atom.findOrCreateUnicodeAtom("Application"); public static final Atom SYNTHETIC = Atom.findOrCreateUnicodeAtom("Synthetic"); /** Create an analysis scope initialized for analysis of Java */ public static AnalysisScope createJavaAnalysisScope() { AnalysisScope scope = new AnalysisScope(Collections.singleton(Language.JAVA)); scope.initForJava(); return scope; } /** Initialize a scope for java analysis */ protected void initForJava() { initCoreForJava(); initSynthetic(loadersByName.get(APPLICATION)); } /** Initialize the standard 3 class loaders for java analysis */ protected void initCoreForJava() { ClassLoaderReference primordial = new ClassLoaderReference(PRIMORDIAL, ClassLoaderReference.Java, null); ClassLoaderReference extension = new ClassLoaderReference(EXTENSION, ClassLoaderReference.Java, primordial); ClassLoaderReference application = new ClassLoaderReference(APPLICATION, ClassLoaderReference.Java, extension); loadersByName.put(PRIMORDIAL, primordial); loadersByName.put(EXTENSION, extension); loadersByName.put(APPLICATION, application); } /** Create the class loader for synthetic classes. */ protected void initSynthetic(ClassLoaderReference parent) { ClassLoaderReference synthetic = new ClassLoaderReference(SYNTHETIC, ClassLoaderReference.Java, parent); setLoaderImpl(synthetic, "com.ibm.wala.ipa.summaries.BypassSyntheticClassLoader"); loadersByName.put(SYNTHETIC, synthetic); } /** A set of classes to exclude from the analysis entirely. */ private SetOfClasses exclusions; public final LinkedHashMap<Atom, ClassLoaderReference> loadersByName = new LinkedHashMap<>(); /** Special class loader for array instances */ private final ArrayClassLoader arrayClassLoader = new ArrayClassLoader(); private final Map<ClassLoaderReference, List<Module>> moduleMap = HashMapFactory.make(3); private final Map<Atom, Language> languages; protected AnalysisScope(Collection<? extends Language> languages) { super(); this.languages = new HashMap<>(); for (Language l : languages) { this.languages.put(l.getName(), l); } } public Language getLanguage(Atom name) { return languages.get(name); } public boolean isApplicationLoader(IClassLoader loader) { return loader.getReference().equals(getLoader(APPLICATION)); } /** Return the information regarding the primordial loader. */ public ClassLoaderReference getPrimordialLoader() { return getLoader(PRIMORDIAL); } /** Return the information regarding the extension loader. */ public ClassLoaderReference getExtensionLoader() { return getLoader(EXTENSION); } /** Return the information regarding the application loader. */ public ClassLoaderReference getApplicationLoader() { return getLoader(APPLICATION); } /** Return the information regarding the application loader. */ public ClassLoaderReference getSyntheticLoader() { return getLoader(SYNTHETIC); } /** @return the set of languages to be processed during this analysis session. */ public Collection<Language> getLanguages() { return languages.values(); } /** * @return the set of "base languages," each of which defines a family of compatible languages, * and therefore induces a distinct ClassHierarchy */ public Set<Language> getBaseLanguages() { Set<Language> result = HashSetFactory.make(); for (Language language : getLanguages()) { if (language.getBaseLanguage() == null) { result.add(language); } } return result; } /** Add a class file to the scope for a loader */ public void addSourceFileToScope(ClassLoaderReference loader, File file, String fileName) throws IllegalArgumentException { List<Module> s = MapUtil.findOrCreateList(moduleMap, loader); s.add(new SourceFileModule(file, fileName, null)); } /** Add a class file to the scope for a loader */ public void addClassFileToScope(ClassLoaderReference loader, File file) throws IllegalArgumentException, InvalidClassFileException { List<Module> s = MapUtil.findOrCreateList(moduleMap, loader); s.add(new ClassFileModule(file, null)); } /** * Adds a module from the Java standard library to the analysis scope. * * @param moduleName the name of the module, e.g., {@code "java.sql"} * @throws IOException if a module by that name cannot successfully be loaded */ public void addJDKModuleToScope(String moduleName) throws IOException { Path path = PlatformUtil.getPathForJDKModule(moduleName); if (!Files.exists(path)) { throw new IOException("cannot find jmod file for module " + moduleName + ", tried " + path); } addToScope(ClassLoaderReference.Primordial, new JarFile(path.toString(), false)); } /** * Add a jar file to the scope via an {@link InputStream}. NOTE: The InputStream should *not* be a * {@link java.util.jar.JarInputStream}; it should be a regular {@link InputStream} for the raw * bytes of the jar file. */ public void addInputStreamForJarToScope(ClassLoaderReference loader, InputStream stream) throws IOException { MapUtil.findOrCreateList(moduleMap, loader).add(new JarStreamModule(stream)); } /** Add a jar file to the scope for a loader */ @SuppressWarnings("unused") public void addToScope(ClassLoaderReference loader, JarFile file) { List<Module> s = MapUtil.findOrCreateList(moduleMap, loader); if (DEBUG_LEVEL > 0) { System.err.println(("AnalysisScope: add JarFileModule " + file.getName())); } s.add(new JarFileModule(file)); } /** Add a module to the scope for a loader */ @SuppressWarnings("unused") public void addToScope(ClassLoaderReference loader, Module m) { if (m == null) { throw new IllegalArgumentException("null m"); } List<Module> s = MapUtil.findOrCreateList(moduleMap, loader); if (DEBUG_LEVEL > 0) { System.err.println(("AnalysisScope: add module " + m)); } s.add(m); } /** Add all modules from another scope */ public void addToScope(AnalysisScope other) { if (other == null) { throw new IllegalArgumentException("null other"); } for (ClassLoaderReference loader : other.getLoaders()) { for (Module m : other.getModules(loader)) { addToScope(loader, m); } } } /** * Add a module file to the scope for a loader. The classes in the added jar file will override * classes added to the scope so far. */ @SuppressWarnings("unused") public void addToScopeHead(ClassLoaderReference loader, Module m) { if (m == null) { throw new IllegalArgumentException("null m"); } List<Module> s = MapUtil.findOrCreateList(moduleMap, loader); if (DEBUG_LEVEL > 0) { System.err.println(("AnalysisScope: add overriding module " + m)); } s.add(0, m); } /** * @return the ClassLoaderReference specified by {@code name}. * @throws IllegalArgumentException if name is null */ public ClassLoaderReference getLoader(Atom name) throws IllegalArgumentException { if (name == null) { throw new IllegalArgumentException("name is null"); } if (name.length() == 0) { throw new IllegalArgumentException("empty atom is not a legal class loader name"); } /* * if (Assertions.verifyAssertions) { if (name.getVal(0) > 'Z') { Assertions._assert(name.getVal(0) <= 'Z', * "Classloader name improperly capitalised? (" + name + ")"); } } */ return loadersByName.get(name); } protected ClassLoaderReference classLoaderName2Ref(String clName) { return getLoader(Atom.findOrCreateUnicodeAtom(clName)); } private final HashMap<ClassLoaderReference, String> loaderImplByRef = HashMapFactory.make(); public String getLoaderImpl(ClassLoaderReference ref) { return loaderImplByRef.get(ref); } public void setLoaderImpl(ClassLoaderReference ref, String implClass) { if (ref == null) { throw new IllegalArgumentException("null ref"); } if (implClass == null) { throw new IllegalArgumentException("null implClass"); } loaderImplByRef.put(ref, implClass); } public Collection<ClassLoaderReference> getLoaders() { return Collections.unmodifiableCollection(loadersByName.values()); } public int getNumberOfLoaders() { return loadersByName.values().size(); } public SetOfClasses getExclusions() { return exclusions; } public void setExclusions(SetOfClasses classes) { exclusions = classes; } @Override public String toString() { StringBuilder result = new StringBuilder(); for (ClassLoaderReference loader : loadersByName.values()) { result.append(loader.getName()); result.append('\n'); for (Module m : getModules(loader)) { result.append(' '); result.append(m); result.append('\n'); } } result.append(getExclusionString()); result.append('\n'); return result.toString(); } /** @return a String that describes exclusions from the analysis scope. */ protected Object getExclusionString() { return "Exclusions: " + exclusions; } /** Utility function. Useful when parsing input. */ public MethodReference findMethod(Atom loader, String klass, Atom name, ImmutableByteArray desc) { if (desc == null) { throw new IllegalArgumentException("null desc"); } ClassLoaderReference clr = getLoader(loader); Descriptor ddesc = Descriptor.findOrCreate(languages.get(clr.getLanguage()), desc); TypeReference type = TypeReference.findOrCreate(clr, TypeName.string2TypeName(klass)); return MethodReference.findOrCreate(type, name, ddesc); } public List<Module> getModules(ClassLoaderReference loader) { List<Module> result = moduleMap.get(loader); return result == null ? Collections.emptyList() : result; } /** @return Returns the arrayClassLoader. */ public ArrayClassLoader getArrayClassLoader() { return arrayClassLoader; } /** @return the rt.jar (1.4), core.jar (1.5), java.core.jmod (13) file, or null if not found. */ private JarFile getRtJar() { return RtJar.getRtJar( new MapIterator<>( new FilterIterator<>( getModules(getPrimordialLoader()).iterator(), JarFileModule.class::isInstance), M -> ((JarFileModule) M).getJarFile())); } public String getJavaLibraryVersion() throws IllegalStateException { try (final JarFile rtJar = getRtJar()) { if (rtJar == null) { throw new IllegalStateException("cannot find runtime libraries"); } assert !rtJar.getName().endsWith(".jmod") : String.format( "main runtime library is \"%s\", but WALA does not yet know how to get the library version of a Java module", rtJar.getName()); Manifest man = rtJar.getManifest(); assert man != null : "runtime library has no manifest!"; String result = man.getMainAttributes().getValue("Specification-Version"); if (result == null) { Attributes att = man.getMainAttributes(); System.err.println("main attributes:" + att); Assertions.UNREACHABLE( "Manifest for " + rtJar.getName() + " has no value for Specification-Version"); } return result; } catch (java.io.IOException e) { Assertions.UNREACHABLE("error getting rt.jar manifest!"); return null; } } public boolean isJava18Libraries() throws IllegalStateException { return getJavaLibraryVersion().startsWith("1.8"); } public boolean isJava17Libraries() throws IllegalStateException { return getJavaLibraryVersion().startsWith("1.7"); } public boolean isJava16Libraries() throws IllegalStateException { return getJavaLibraryVersion().startsWith("1.6"); } public boolean isJava15Libraries() throws IllegalStateException { return getJavaLibraryVersion().startsWith("1.5"); } public boolean isJava14Libraries() throws IllegalStateException { return getJavaLibraryVersion().startsWith("1.4"); } /** * Creates a "serializable" version of the analysis scope. * * @return a "serializable" version of the analysis scope. */ public ShallowAnalysisScope toShallowAnalysisScope() throws NotSerializableException { if (getArrayClassLoader().getNumberOfClasses() != 0) { throw new NotSerializableException("Scope was already used for building array classes"); } // Note: 'arrayClassLoader' object will be built from scratch in remote process // represent modules map as a set of strings (corresponding to analysis scope file lines. List<String> moduleLines = new ArrayList<>(); for (Map.Entry<ClassLoaderReference, List<Module>> e : moduleMap.entrySet()) { ClassLoaderReference lrReference = e.getKey(); String moduleLdr = lrReference.getName().toString(); String moduleLang = lrReference.getLanguage().toString(); assert Language.JAVA.getName().equals(lrReference.getLanguage()) : "Java language only is currently supported"; for (Module m : e.getValue()) { String moduleType; String modulePath; if (m instanceof JarFileModule) { moduleType = "jarFile"; modulePath = ((JarFileModule) m).getAbsolutePath(); } else if (m instanceof BinaryDirectoryTreeModule) { moduleType = "binaryDir"; modulePath = ((BinaryDirectoryTreeModule) m).getPath(); } else if (m instanceof SourceDirectoryTreeModule) { moduleType = "sourceDir"; modulePath = ((SourceDirectoryTreeModule) m).getPath(); } else if (m instanceof SourceFileModule) { moduleType = "sourceFile"; modulePath = ((SourceFileModule) m).getAbsolutePath(); } else { Assertions.UNREACHABLE("Module type isn't supported - " + m); continue; } modulePath = modulePath.replace("\\", "/"); String moduleDescrLine = String.format("%s,%s,%s,%s", moduleLdr, moduleLang, moduleType, modulePath); moduleLines.add(moduleDescrLine); } } // represent loaderImplByRef map as set of strings List<String> ldrImplLines = new ArrayList<>(); for (Map.Entry<ClassLoaderReference, String> e : loaderImplByRef.entrySet()) { ClassLoaderReference lrReference = e.getKey(); String ldrName = lrReference.getName().toString(); String ldrLang = lrReference.getLanguage().toString(); assert Language.JAVA.getName().equals(lrReference.getLanguage()) : "Java language only is currently supported"; String ldrImplName = e.getValue(); String ldrImplDescrLine = String.format("%s,%s,%s,%s", ldrName, ldrLang, "loaderImpl", ldrImplName); ldrImplLines.add(ldrImplDescrLine); } ShallowAnalysisScope shallowScope = new ShallowAnalysisScope(getExclusions(), moduleLines, ldrImplLines); return shallowScope; } }
17,964
35.588595
123
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/ipa/callgraph/CGNode.java
/* * Copyright (c) 2002 - 2006 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package com.ibm.wala.ipa.callgraph; import com.ibm.wala.classLoader.CallSiteReference; import com.ibm.wala.classLoader.IMethod; import com.ibm.wala.classLoader.NewSiteReference; import com.ibm.wala.ipa.cha.IClassHierarchyDweller; import com.ibm.wala.ssa.DefUse; import com.ibm.wala.ssa.IR; import com.ibm.wala.util.graph.INodeWithNumber; import java.util.Iterator; /** Basic interface for a node in a call graph. */ public interface CGNode extends INodeWithNumber, ContextItem, IClassHierarchyDweller { /** * Return the {@link IMethod method} this CGNode represents. This value will never be {@code * null}. * * @return the target IMethod for this CGNode. */ IMethod getMethod(); /** * Return the {@link Context context} this CGNode represents. This value will never be {@code * null}. * * @return the Context for this CGNode. */ Context getContext(); /** * NOTE: This is for use only by call graph builders, not by any other client of this interface. * * <p>Record that a particular call site might resolve to a call to a particular target node. * Returns true if this is a new target */ boolean addTarget(CallSiteReference site, CGNode target); /** @return the "default" IR for this node used by the governing call graph */ IR getIR(); /** @return DefUse for the "default" IR for this node used by the governing call graph */ DefUse getDU(); /** * @return an Iterator of the types that may be allocated by a given method in a given context. */ Iterator<NewSiteReference> iterateNewSites(); /** * @return an Iterator of the call statements that may execute in a given method for a given * context */ Iterator<CallSiteReference> iterateCallSites(); }
2,125
32.21875
98
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/ipa/callgraph/CallGraph.java
/* * Copyright (c) 2002 - 2006 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package com.ibm.wala.ipa.callgraph; import com.ibm.wala.classLoader.CallSiteReference; import com.ibm.wala.classLoader.IMethod; import com.ibm.wala.ipa.cha.IClassHierarchy; import com.ibm.wala.types.MethodReference; import com.ibm.wala.util.graph.NumberedGraph; import java.util.Collection; import java.util.Iterator; import java.util.Set; /** Basic interface for a call graph, which is a graph of {@link CGNode} */ public interface CallGraph extends NumberedGraph<CGNode> { /** * Return the (fake) interprocedural {@link CGNode root node} of the call graph. * * @return the "fake" root node the call graph */ CGNode getFakeRootNode(); CGNode getFakeWorldClinitNode(); /** @return an Iterator of the nodes designated as "root nodes" */ Collection<CGNode> getEntrypointNodes(); /** * If you want to get <em> all </em> the nodes corresponding to a particular method, regardless of * context, then use {@link CGNode getNodes} * * @return the node corresponding a method in a context */ CGNode getNode(IMethod method, Context C); /** * @param m a method reference * @return the set of all nodes in the call graph that represent this method. */ Set<CGNode> getNodes(MethodReference m); /** @return the governing class hierarchy for this call graph */ IClassHierarchy getClassHierarchy(); /** * Return the set of CGNodes that represent possible targets of a particular call site from a * particular node */ Set<CGNode> getPossibleTargets(CGNode node, CallSiteReference site); /** @return the number of nodes that the call site may dispatch to */ int getNumberOfTargets(CGNode node, CallSiteReference site); /** * @return iterator of CallSiteReference, the call sites in a node that might dispatch to the * target node. */ Iterator<CallSiteReference> getPossibleSites(CGNode src, CGNode target); }
2,269
31.898551
100
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/ipa/callgraph/CallGraphBuilder.java
/* * Copyright (c) 2002 - 2006 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package com.ibm.wala.ipa.callgraph; import com.ibm.wala.ipa.callgraph.propagation.InstanceKey; import com.ibm.wala.ipa.callgraph.propagation.PointerAnalysis; import com.ibm.wala.ipa.cha.IClassHierarchy; import com.ibm.wala.util.MonitorUtil.IProgressMonitor; /** Basic interface for an object that can build a call graph. */ public interface CallGraphBuilder<I extends InstanceKey> { /** * Build a call graph. * * @param options an object representing controlling options that the call graph building * algorithm needs to know. * @return the built call graph */ CallGraph makeCallGraph(AnalysisOptions options, IProgressMonitor monitor) throws IllegalArgumentException, CallGraphBuilderCancelException; /** * @return the Pointer Analysis information computed as a side-effect of call graph construction. */ PointerAnalysis<I> getPointerAnalysis(); /** @return A cache of various analysis artifacts used during call graph construction. */ IAnalysisCacheView getAnalysisCache(); IClassHierarchy getClassHierarchy(); }
1,443
35.1
99
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/ipa/callgraph/CallGraphBuilderCancelException.java
/* * Copyright (c) 2007 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package com.ibm.wala.ipa.callgraph; import com.ibm.wala.ipa.callgraph.propagation.InstanceKey; import com.ibm.wala.ipa.callgraph.propagation.PointerAnalysis; import com.ibm.wala.util.CancelException; /** * An exception to throw when call graph construction is canceled. This exception allows clients to * retrieve the partially-built call graph and pointer analysis */ public class CallGraphBuilderCancelException extends CancelException { private static final long serialVersionUID = -3071193971009314659L; private final CallGraph cg; private final PointerAnalysis<InstanceKey> pointerAnalysis; public static CallGraphBuilderCancelException createCallGraphBuilderCancelException( Exception cause, CallGraph cg, PointerAnalysis<InstanceKey> pointerAnalysis) { return new CallGraphBuilderCancelException(cause, cg, pointerAnalysis); } public static CallGraphBuilderCancelException createCallGraphBuilderCancelException( String msg, CallGraph cg, PointerAnalysis<InstanceKey> pointerAnalysis) { return new CallGraphBuilderCancelException(msg, cg, pointerAnalysis); } /** @return the {@link CallGraph} in whatever state it was left when computation was canceled */ public CallGraph getPartialCallGraph() { return cg; } /** * @return the {@link PointerAnalysis} in whatever state it was left when computation was canceled */ public PointerAnalysis<InstanceKey> getPartialPointerAnalysis() { return pointerAnalysis; } private CallGraphBuilderCancelException( String msg, CallGraph cg, PointerAnalysis<InstanceKey> pointerAnalysis) { super(msg); this.cg = cg; this.pointerAnalysis = pointerAnalysis; } private CallGraphBuilderCancelException( Exception cause, CallGraph cg, PointerAnalysis<InstanceKey> pointerAnalysis) { super(cause); this.cg = cg; this.pointerAnalysis = pointerAnalysis; } }
2,274
34
100
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/ipa/callgraph/CallGraphStats.java
/* * Copyright (c) 2002 - 2006 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package com.ibm.wala.ipa.callgraph; import com.ibm.wala.classLoader.IMethod; import com.ibm.wala.classLoader.ShrikeCTMethod; import com.ibm.wala.types.MethodReference; import com.ibm.wala.util.collections.HashSetFactory; import com.ibm.wala.util.graph.traverse.DFS; import java.util.Collections; import java.util.HashSet; import java.util.Set; /** Collect basic call graph statistics */ public class CallGraphStats { public static class CGStats { private final int nNodes; private final int nEdges; private final int nMethods; private final int bytecodeBytes; private CGStats(int nodes, int edges, int methods, int bytecodeBytes) { super(); nNodes = nodes; nEdges = edges; nMethods = methods; this.bytecodeBytes = bytecodeBytes; } public int getNNodes() { return nNodes; } public int getNEdges() { return nEdges; } public int getNMethods() { return nMethods; } public int getBytecodeBytes() { return bytecodeBytes; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + bytecodeBytes; result = prime * result + nEdges; result = prime * result + nMethods; result = prime * result + nNodes; return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; CGStats other = (CGStats) obj; if (bytecodeBytes != other.bytecodeBytes) return false; if (nEdges != other.nEdges) return false; if (nMethods != other.nMethods) return false; if (nNodes != other.nNodes) return false; return true; } @Override public String toString() { return "Call graph stats:\n Nodes: " + nNodes + "\n Edges: " + nEdges + "\n Methods: " + nMethods + "\n Bytecode Bytes: " + bytecodeBytes + '\n'; } } public static CGStats getCGStats(CallGraph cg) { if (cg == null) { throw new IllegalArgumentException("cg is null"); } Set<CGNode> reachableNodes = DFS.getReachableNodes(cg, Collections.singleton(cg.getFakeRootNode())); int nNodes = 0; int nEdges = 0; for (CGNode n : reachableNodes) { nNodes++; nEdges += cg.getSuccNodeCount(n); } return new CGStats(nNodes, nEdges, collectMethods(cg).size(), countBytecodeBytes(cg)); } /** @throws IllegalArgumentException if cg is null */ public static String getStats(CallGraph cg) { return getCGStats(cg).toString(); } /** * @return the number of bytecode bytes * @throws IllegalArgumentException if cg is null */ public static int countBytecodeBytes(CallGraph cg) { if (cg == null) { throw new IllegalArgumentException("cg is null"); } int ret = 0; HashSet<IMethod> counted = HashSetFactory.make(); for (CGNode node : cg) { IMethod method = node.getMethod(); if (counted.add(method)) { if (method instanceof ShrikeCTMethod) { byte[] bytecodes = ((ShrikeCTMethod) method).getBytecodes(); if (bytecodes != null) { ret += bytecodes.length; } } } } return ret; } /** * Walk the call graph and return the set of MethodReferences that appear in the graph. * * @return a set of MethodReferences * @throws IllegalArgumentException if cg is null */ public static Set<MethodReference> collectMethods(CallGraph cg) { if (cg == null) { throw new IllegalArgumentException("cg is null"); } HashSet<MethodReference> result = HashSetFactory.make(); for (CGNode N : cg) { result.add(N.getMethod().getReference()); } return result; } }
4,266
26.006329
90
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/ipa/callgraph/CallGraphTransitiveClosure.java
/* * Copyright (c) 2007 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package com.ibm.wala.ipa.callgraph; import com.ibm.wala.core.util.CancelRuntimeException; import com.ibm.wala.dataflow.graph.BitVectorSolver; import com.ibm.wala.fixpoint.BitVectorVariable; import com.ibm.wala.ipa.modref.GenReach; import com.ibm.wala.util.CancelException; import com.ibm.wala.util.collections.HashMapFactory; import com.ibm.wala.util.graph.impl.GraphInverter; import com.ibm.wala.util.intset.OrdinalSet; import java.util.Collection; import java.util.Map; import java.util.function.Function; /** * Utility class for computing an analysis result for call graph nodes and their transitive callees, * given the results for individual nodes. */ public class CallGraphTransitiveClosure { /** * Compute the transitive closure of an analysis result over all callees. * * @param cg the call graph * @param nodeResults analysis result for each individual node * @return a map from each node to the analysis result for the node and its transitive callees */ public static <T> Map<CGNode, OrdinalSet<T>> transitiveClosure( CallGraph cg, Map<CGNode, Collection<T>> nodeResults) { try { // invert the call graph, to compute the bottom-up result GenReach<CGNode, T> gr = new GenReach<>(GraphInverter.invert(cg), nodeResults); BitVectorSolver<CGNode> solver = new BitVectorSolver<>(gr); solver.solve(null); Map<CGNode, OrdinalSet<T>> result = HashMapFactory.make(); for (CGNode n : cg) { BitVectorVariable bv = solver.getOut(n); result.put(n, new OrdinalSet<>(bv.getValue(), gr.getLatticeValues())); } return result; } catch (CancelException e) { throw new CancelRuntimeException(e); } } /** Collect analysis result for each {@link CGNode} in a {@link Map}. */ public static <T> Map<CGNode, Collection<T>> collectNodeResults( CallGraph cg, Function<CGNode, Collection<T>> nodeResultComputer) { Map<CGNode, Collection<T>> result = HashMapFactory.make(); for (CGNode n : cg) { result.put(n, nodeResultComputer.apply(n)); } return result; } }
2,462
36.318182
100
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/ipa/callgraph/ClassTargetSelector.java
/* * Copyright (c) 2002 - 2006 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package com.ibm.wala.ipa.callgraph; import com.ibm.wala.classLoader.IClass; import com.ibm.wala.classLoader.NewSiteReference; /** * This interface represents policies for selecting a class to allocate at a given new site. The * most obvious such policy would be to look at the relevant class hierarchy and lookup the * appropriate class based on the type reference at the new site. However, other policies are * possible for purposes such as providing an abstraction of unanalyzed libraries or specialized * J2EE functionality. * * <p>Such policies are consulted by the different analysis mechanisms, both the flow-based and * non-flow algorithms. The current mechanism is that the policy object are registered with the * AnalysisOptions object, and all analyses that need to analyze allocations ask that object for the * class selector to use. * * <p>In general, for specialized selectors, it is good practice to build selectors that handle the * special case of interest, and otherwise delegate to a child selector. When registering with the * AnalysisOptions object, make the child selector be whatever the options object had before. */ public interface ClassTargetSelector { /** * Given a calling node and a new site, return the type to be allocated. * * @param caller the GCNode in the call graph containing the new site. * @param site the new site reference of the new site. * @return the class to be allocated. */ IClass getAllocatedTarget(CGNode caller, NewSiteReference site); }
1,903
43.27907
100
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/ipa/callgraph/Context.java
/* * Copyright (c) 2002 - 2006 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package com.ibm.wala.ipa.callgraph; /** * A Context is a mapping from a name (ContextKey) to a value (ContextItem) * * <p>For example, for CFA-1, there is only one name ("caller"); and the context maps "caller" to an * IMethod * * <p>As another example, for CPA, there would be name for each parameter slot ("zero","one","two"), * and the Context provides a mapping from this name to a set of types. eg. "one" -&gt; * {java.lang.String, java.lang.Date} */ public interface Context extends ContextItem { /** @return the objects corresponding to a given name */ ContextItem get(ContextKey name); /** @return whether this context has a specific type */ default boolean isA(Class<? extends Context> type) { return type.isInstance(this); } }
1,137
34.5625
100
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/ipa/callgraph/ContextItem.java
/* * Copyright (c) 2002 - 2006 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package com.ibm.wala.ipa.callgraph; /** A placeholder for strong typing. */ public interface ContextItem { class Value<T> implements ContextItem { private final T v; public Value(T v) { this.v = v; } public T getValue() { return v; } public static <T> Value<T> make(T v) { return new Value<>(v); } @Override public int hashCode() { return 31 + ((v == null) ? 0 : v.hashCode()); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Value<?> other = (Value<?>) obj; if (v == null) { if (other.v != null) return false; } else if (!v.equals(other.v)) return false; return true; } } }
1,197
22.96
72
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/ipa/callgraph/ContextKey.java
/* * Copyright (c) 2002 - 2006 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package com.ibm.wala.ipa.callgraph; /** This just exists to enforce strong typing. */ public interface ContextKey { /** * A property of contexts that might be generally useful: the "caller" method ... used for * call-string context schemes. */ ContextKey CALLER = new ContextKey() {}; /** A property of contexts that might be generally useful: the "target" method. */ ContextKey TARGET = new ContextKey() {}; /** A property of contexts that might be generally useful: the "name". */ ContextKey NAME = new ContextKey() {}; /** * A property of contexts that might be generally useful: the "call site" method ... used for * call-string context schemes. */ ContextKey CALLSITE = new ContextKey() {}; /** * A property of contexts that might be generally useful: an identifier for the receiver object * ... used for object-sensitivity context policies. * * <p>Known implementations (ContextItems) for RECEIVER include TypeAbstraction and InstanceKey */ ContextKey RECEIVER = new ContextKey() {}; /** * context key representing some parameter index, useful, e.g. for CPA-style context-sensitivity * policies. */ class ParameterKey implements ContextKey { public final int index; private ParameterKey(int index) { this.index = index; } @Override public String toString() { return "P" + index; } } /** Generally useful constants for possible parameter indices */ ContextKey PARAMETERS[] = new ContextKey[] { new ParameterKey(0), new ParameterKey(1), new ParameterKey(2), new ParameterKey(3), new ParameterKey(4), new ParameterKey(5), new ParameterKey(6), new ParameterKey(7), new ParameterKey(8), new ParameterKey(9), new ParameterKey(10), new ParameterKey(11), new ParameterKey(12), new ParameterKey(13), new ParameterKey(14), new ParameterKey(15), new ParameterKey(16), new ParameterKey(17), new ParameterKey(18), new ParameterKey(19), new ParameterKey(20), new ParameterKey(21), new ParameterKey(22), new ParameterKey(23), new ParameterKey(24), new ParameterKey(25), new ParameterKey(26), new ParameterKey(27), new ParameterKey(28), new ParameterKey(29), new ParameterKey(30), new ParameterKey(31), new ParameterKey(32), new ParameterKey(33), new ParameterKey(34), new ParameterKey(35), new ParameterKey(36), new ParameterKey(37), new ParameterKey(38), new ParameterKey(39), new ParameterKey(40), new ParameterKey(41), new ParameterKey(42), new ParameterKey(43), new ParameterKey(44), new ParameterKey(45), new ParameterKey(46), new ParameterKey(47), new ParameterKey(48), new ParameterKey(49), // added based on functions seen in the wild... // --------- new ParameterKey(50), new ParameterKey(51), new ParameterKey(52), new ParameterKey(53), new ParameterKey(54), new ParameterKey(55), new ParameterKey(56), new ParameterKey(57), new ParameterKey(58), new ParameterKey(59), new ParameterKey(60), new ParameterKey(61), new ParameterKey(62), new ParameterKey(63), new ParameterKey(64), new ParameterKey(65), new ParameterKey(66), new ParameterKey(67), new ParameterKey(68), new ParameterKey(69), new ParameterKey(70), new ParameterKey(71), new ParameterKey(72), new ParameterKey(73), new ParameterKey(74), new ParameterKey(75), new ParameterKey(76), new ParameterKey(77), new ParameterKey(78), new ParameterKey(79), new ParameterKey(80), new ParameterKey(81), new ParameterKey(82), new ParameterKey(83), new ParameterKey(84), new ParameterKey(85), new ParameterKey(86), new ParameterKey(87), new ParameterKey(88), new ParameterKey(89), new ParameterKey(90), new ParameterKey(91), new ParameterKey(92), new ParameterKey(93), new ParameterKey(94), new ParameterKey(95), new ParameterKey(96), new ParameterKey(97), new ParameterKey(98), new ParameterKey(99), new ParameterKey(100), new ParameterKey(101), new ParameterKey(102), new ParameterKey(103), new ParameterKey(104), new ParameterKey(105), new ParameterKey(106), new ParameterKey(107), new ParameterKey(108), new ParameterKey(109), new ParameterKey(110), new ParameterKey(111), new ParameterKey(112), new ParameterKey(113), new ParameterKey(114), new ParameterKey(115), new ParameterKey(116), new ParameterKey(117), new ParameterKey(118), new ParameterKey(119), new ParameterKey(120), new ParameterKey(121), new ParameterKey(122), new ParameterKey(123), new ParameterKey(124), new ParameterKey(125), new ParameterKey(126), new ParameterKey(127), new ParameterKey(128), new ParameterKey(129), new ParameterKey(130), new ParameterKey(131), new ParameterKey(132), new ParameterKey(133), new ParameterKey(134), new ParameterKey(135), new ParameterKey(136), new ParameterKey(137), new ParameterKey(138), new ParameterKey(139), new ParameterKey(140), new ParameterKey(141), new ParameterKey(142), new ParameterKey(143), new ParameterKey(144), new ParameterKey(145), new ParameterKey(146), new ParameterKey(147), new ParameterKey(148), new ParameterKey(149), new ParameterKey(150), new ParameterKey(151), new ParameterKey(152), new ParameterKey(153), new ParameterKey(154), new ParameterKey(155), new ParameterKey(156), new ParameterKey(157), new ParameterKey(158), new ParameterKey(159), new ParameterKey(160), new ParameterKey(161), new ParameterKey(162), new ParameterKey(163), new ParameterKey(164), new ParameterKey(165), new ParameterKey(166), new ParameterKey(167), new ParameterKey(168), new ParameterKey(169), new ParameterKey(170), new ParameterKey(171), new ParameterKey(172), new ParameterKey(173), new ParameterKey(174), new ParameterKey(175), new ParameterKey(176), new ParameterKey(177), new ParameterKey(178), new ParameterKey(179), new ParameterKey(180), new ParameterKey(181), new ParameterKey(182), new ParameterKey(183), new ParameterKey(184), new ParameterKey(185), new ParameterKey(186), new ParameterKey(187), new ParameterKey(188), new ParameterKey(189), new ParameterKey(190), new ParameterKey(191), new ParameterKey(192), new ParameterKey(193), new ParameterKey(194), new ParameterKey(195), new ParameterKey(196), new ParameterKey(197), new ParameterKey(198), new ParameterKey(199), new ParameterKey(200), new ParameterKey(201), new ParameterKey(202), new ParameterKey(203), new ParameterKey(204), new ParameterKey(205), new ParameterKey(206), new ParameterKey(207), new ParameterKey(208), new ParameterKey(209), new ParameterKey(210), new ParameterKey(211), new ParameterKey(212), new ParameterKey(213), new ParameterKey(214), new ParameterKey(215), new ParameterKey(216), new ParameterKey(217), new ParameterKey(218), new ParameterKey(219), new ParameterKey(220), new ParameterKey(221), new ParameterKey(222), new ParameterKey(223), new ParameterKey(224), new ParameterKey(225), new ParameterKey(226), new ParameterKey(227), new ParameterKey(228), new ParameterKey(229), new ParameterKey(230), new ParameterKey(231), new ParameterKey(232), new ParameterKey(233), new ParameterKey(234), new ParameterKey(235), new ParameterKey(236), new ParameterKey(237), new ParameterKey(238), new ParameterKey(239), new ParameterKey(240), new ParameterKey(241), new ParameterKey(242), new ParameterKey(243), new ParameterKey(244), new ParameterKey(245), new ParameterKey(246), new ParameterKey(247), new ParameterKey(248), new ParameterKey(249), new ParameterKey(250), new ParameterKey(251), new ParameterKey(252), new ParameterKey(253), new ParameterKey(254), new ParameterKey(255), new ParameterKey(256), new ParameterKey(257), new ParameterKey(258), new ParameterKey(259), new ParameterKey(260), new ParameterKey(261), new ParameterKey(262), new ParameterKey(263), new ParameterKey(264), new ParameterKey(265), new ParameterKey(266), new ParameterKey(267), new ParameterKey(268), new ParameterKey(269), new ParameterKey(270), new ParameterKey(271), new ParameterKey(272), new ParameterKey(273), new ParameterKey(274), new ParameterKey(275), new ParameterKey(276), new ParameterKey(277), new ParameterKey(278), new ParameterKey(279), new ParameterKey(280), new ParameterKey(281), new ParameterKey(282), new ParameterKey(283), new ParameterKey(284), new ParameterKey(285), new ParameterKey(286), new ParameterKey(287), new ParameterKey(288), new ParameterKey(289), new ParameterKey(290), new ParameterKey(291), new ParameterKey(292), new ParameterKey(293), new ParameterKey(294), new ParameterKey(295), new ParameterKey(296), new ParameterKey(297), new ParameterKey(298), new ParameterKey(299), new ParameterKey(300), new ParameterKey(301), new ParameterKey(302), new ParameterKey(303), new ParameterKey(304), new ParameterKey(305), new ParameterKey(306), new ParameterKey(307), new ParameterKey(308), new ParameterKey(309), new ParameterKey(310), new ParameterKey(311), new ParameterKey(312), new ParameterKey(313), new ParameterKey(314), new ParameterKey(315), new ParameterKey(316), new ParameterKey(317), new ParameterKey(318), new ParameterKey(319), new ParameterKey(320), new ParameterKey(321), new ParameterKey(322), new ParameterKey(323), new ParameterKey(324), new ParameterKey(325), new ParameterKey(326), new ParameterKey(327), new ParameterKey(328), new ParameterKey(329), new ParameterKey(330), new ParameterKey(331), new ParameterKey(332), new ParameterKey(333), new ParameterKey(334), new ParameterKey(335), new ParameterKey(336), new ParameterKey(337), new ParameterKey(338), new ParameterKey(339), new ParameterKey(340), new ParameterKey(341), new ParameterKey(342), new ParameterKey(343), new ParameterKey(344), new ParameterKey(345), new ParameterKey(346), new ParameterKey(347), new ParameterKey(348), new ParameterKey(349), new ParameterKey(350), new ParameterKey(351), new ParameterKey(352), new ParameterKey(353), new ParameterKey(354), new ParameterKey(355), new ParameterKey(356), new ParameterKey(357), new ParameterKey(358), new ParameterKey(359), new ParameterKey(360), new ParameterKey(361), new ParameterKey(362), new ParameterKey(363), new ParameterKey(364), new ParameterKey(365), new ParameterKey(366), new ParameterKey(367), new ParameterKey(368), new ParameterKey(369), new ParameterKey(370), new ParameterKey(371), new ParameterKey(372), new ParameterKey(373), new ParameterKey(374), new ParameterKey(375), new ParameterKey(376), new ParameterKey(377), new ParameterKey(378), new ParameterKey(379), new ParameterKey(380), new ParameterKey(381), new ParameterKey(382), new ParameterKey(383), new ParameterKey(384), new ParameterKey(385), new ParameterKey(386), new ParameterKey(387), new ParameterKey(388), new ParameterKey(389), new ParameterKey(390), new ParameterKey(391), new ParameterKey(392), new ParameterKey(393), new ParameterKey(394), new ParameterKey(395), new ParameterKey(396), new ParameterKey(397), new ParameterKey(398), new ParameterKey(399), new ParameterKey(400), new ParameterKey(401), new ParameterKey(402), new ParameterKey(403), new ParameterKey(404), new ParameterKey(405), new ParameterKey(406), new ParameterKey(407), new ParameterKey(408), new ParameterKey(409), new ParameterKey(410), new ParameterKey(411), new ParameterKey(412), new ParameterKey(413), new ParameterKey(414), new ParameterKey(415), new ParameterKey(416), new ParameterKey(417), new ParameterKey(418), new ParameterKey(419), new ParameterKey(420), new ParameterKey(421), new ParameterKey(422), new ParameterKey(423), new ParameterKey(424), new ParameterKey(425), new ParameterKey(426), new ParameterKey(427), new ParameterKey(428), new ParameterKey(429), new ParameterKey(430), new ParameterKey(431), new ParameterKey(432), new ParameterKey(433), new ParameterKey(434), new ParameterKey(435), new ParameterKey(436), new ParameterKey(437), new ParameterKey(438), new ParameterKey(439), new ParameterKey(440), new ParameterKey(441), new ParameterKey(442), new ParameterKey(443), new ParameterKey(444), new ParameterKey(445), new ParameterKey(446), new ParameterKey(447), new ParameterKey(448), new ParameterKey(449), new ParameterKey(450), new ParameterKey(451), new ParameterKey(452), new ParameterKey(453), new ParameterKey(454), new ParameterKey(455), new ParameterKey(456), new ParameterKey(457), new ParameterKey(458), new ParameterKey(459), new ParameterKey(460), new ParameterKey(461), new ParameterKey(462), new ParameterKey(463), new ParameterKey(464), new ParameterKey(465), new ParameterKey(466), new ParameterKey(467), new ParameterKey(468), new ParameterKey(469), new ParameterKey(470), new ParameterKey(471), new ParameterKey(472), new ParameterKey(473), new ParameterKey(474), new ParameterKey(475), new ParameterKey(476), new ParameterKey(477), new ParameterKey(478), new ParameterKey(479), new ParameterKey(480), new ParameterKey(481), new ParameterKey(482), new ParameterKey(483), new ParameterKey(484), new ParameterKey(485), new ParameterKey(486), new ParameterKey(487), new ParameterKey(488), new ParameterKey(489), new ParameterKey(490), new ParameterKey(491), new ParameterKey(492), new ParameterKey(493), new ParameterKey(494), new ParameterKey(495), new ParameterKey(496), new ParameterKey(497), new ParameterKey(498), new ParameterKey(499) }; }
17,375
29.699647
98
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/ipa/callgraph/ContextSelector.java
/* * Copyright (c) 2002 - 2006 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package com.ibm.wala.ipa.callgraph; import com.ibm.wala.classLoader.CallSiteReference; import com.ibm.wala.classLoader.IMethod; import com.ibm.wala.ipa.callgraph.propagation.InstanceKey; import com.ibm.wala.util.intset.IntSet; /** An interface to an object which helps control context-sensitivity. */ public interface ContextSelector { /** * Given a calling node and a call site, returns the Context in which the callee should be * evaluated. * * @param caller the node containing the call site * @param site description of the call site * @param actualParameters the abstract objects (InstanceKeys) of parameters of interest to the * selector * @return the Context in which the callee should be evaluated, or null if no information is * available. */ Context getCalleeTarget( CGNode caller, CallSiteReference site, IMethod callee, InstanceKey[] actualParameters); /** * Given a calling node and a call site, return the set of parameters based on which this selector * may choose to specialize contexts. * * @param caller the calling node * @param site the specific call site * @return the set of parameters of interest */ IntSet getRelevantParameters(CGNode caller, CallSiteReference site); }
1,645
36.409091
100
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/ipa/callgraph/ContextUtil.java
/* * Copyright (c) 2002 - 2006 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package com.ibm.wala.ipa.callgraph; import com.ibm.wala.analysis.typeInference.PointType; import com.ibm.wala.classLoader.IClass; import com.ibm.wala.ipa.callgraph.propagation.InstanceKey; import com.ibm.wala.util.debug.Assertions; /** misc utilities for dealing with contexts */ public class ContextUtil { /** * @param c a context * @return If this is an object-sensitive context that identifies a unique class for the receiver * object, then return the unique class. Else, return null. * @throws IllegalArgumentException if c is null */ public static IClass getConcreteClassFromContext(Context c) { if (c == null) { throw new IllegalArgumentException("c is null"); } ContextItem item = c.get(ContextKey.RECEIVER); if (item == null) { return null; } else { if (item instanceof PointType) { return ((PointType) item).getIClass(); } else if (item instanceof InstanceKey) { return ((InstanceKey) item).getConcreteType(); } else { Assertions.UNREACHABLE("Unexpected: " + item.getClass()); return null; } } } }
1,502
31.673913
99
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/ipa/callgraph/DelegatingContext.java
/* * Copyright (c) 2007 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package com.ibm.wala.ipa.callgraph; /** A context that first checks with A, then defaults to B. */ public class DelegatingContext implements Context { private final Context A; private final Context B; public DelegatingContext(Context A, Context B) { this.A = A; this.B = B; if (A == null) { throw new IllegalArgumentException("null A"); } if (B == null) { throw new IllegalArgumentException("null B"); } } @Override public ContextItem get(ContextKey name) { ContextItem result = A.get(name); if (result == null) { result = B.get(name); } return result; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + A.hashCode(); result = prime * result + B.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; DelegatingContext other = (DelegatingContext) obj; if (!A.equals(other.A)) return false; if (!B.equals(other.B)) return false; return true; } @Override public String toString() { return "DelegatingContext [A=" + A + ", B=" + B + ']'; } @Override public boolean isA(Class<? extends Context> type) { return A.isA(type) || B.isA(type); } }
1,745
23.942857
72
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/ipa/callgraph/Entrypoint.java
/* * Copyright (c) 2002 - 2006 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package com.ibm.wala.ipa.callgraph; import com.ibm.wala.analysis.typeInference.ConeType; import com.ibm.wala.analysis.typeInference.PrimitiveType; import com.ibm.wala.analysis.typeInference.TypeAbstraction; import com.ibm.wala.classLoader.CallSiteReference; import com.ibm.wala.classLoader.IClass; import com.ibm.wala.classLoader.IMethod; import com.ibm.wala.ipa.callgraph.impl.AbstractRootMethod; import com.ibm.wala.ipa.cha.IClassHierarchy; import com.ibm.wala.shrike.shrikeBT.BytecodeConstants; import com.ibm.wala.shrike.shrikeBT.IInvokeInstruction; import com.ibm.wala.ssa.SSAAbstractInvokeInstruction; import com.ibm.wala.ssa.SSANewInstruction; import com.ibm.wala.types.MethodReference; import com.ibm.wala.types.TypeReference; import com.ibm.wala.util.debug.Assertions; import java.util.Arrays; /** A representation of an entrypoint in the call graph. */ public abstract class Entrypoint implements BytecodeConstants { /** The method to be called */ protected final IMethod method; /** @param method the method to be called for this entrypoint */ protected Entrypoint(IMethod method) { if (method == null) { throw new IllegalArgumentException("method is null"); } this.method = method; assert method.getDeclaringClass() != null : "null declaring class"; } protected Entrypoint(MethodReference method, IClassHierarchy cha) { if (cha == null) { throw new IllegalArgumentException("cha is null"); } IMethod m = cha.resolveMethod(method); if (m == null) { Assertions.UNREACHABLE("could not resolve " + method); } this.method = m; } /** * Create a call site reference representing a call to this entrypoint * * @param programCounter the bytecode index of the synthesize call * @return the call site reference, or null if failed to find entrypoint */ public CallSiteReference makeSite(int programCounter) { if (method.getSelector().equals(MethodReference.clinitSelector)) { assert method.isStatic(); return CallSiteReference.make( programCounter, method.getReference(), IInvokeInstruction.Dispatch.STATIC); } else if (method.getSelector().equals(MethodReference.initSelector)) { assert !method.isStatic(); return CallSiteReference.make( programCounter, method.getReference(), IInvokeInstruction.Dispatch.SPECIAL); } else { // It is important to check for static methods before interface methods, since if an interface // contains a static method, it should be called via static dispatch, not interface dispatch if (method.isStatic()) { return CallSiteReference.make( programCounter, method.getReference(), IInvokeInstruction.Dispatch.STATIC); } else if (method.getDeclaringClass().isInterface()) { return CallSiteReference.make( programCounter, method.getReference(), IInvokeInstruction.Dispatch.INTERFACE); } else { return CallSiteReference.make( programCounter, method.getReference(), IInvokeInstruction.Dispatch.VIRTUAL); } } } /** * Add allocation statements to the fake root method for each possible value of parameter i. If * necessary, add a phi to combine the values. * * @return value number holding the parameter to the call; -1 if there was some error */ protected int makeArgument(AbstractRootMethod m, int i) { TypeReference[] p = getParameterTypes(i); switch (p.length) { case 0: return -1; case 1: if (p[0].isPrimitiveType()) { return m.addLocal(); } else { SSANewInstruction n = m.addAllocation(p[0]); return (n == null) ? -1 : n.getDef(); } default: int[] values = new int[p.length]; int countErrors = 0; for (int j = 0; j < p.length; j++) { SSANewInstruction n = m.addAllocation(p[j]); int value = (n == null) ? -1 : n.getDef(); if (value == -1) { countErrors++; } else { values[j - countErrors] = value; } } if (countErrors > 0) { int[] oldValues = values; values = new int[oldValues.length - countErrors]; System.arraycopy(oldValues, 0, values, 0, values.length); } TypeAbstraction a; if (p[0].isPrimitiveType()) { a = PrimitiveType.getPrimitive(p[0]); for (i = 1; i < p.length; i++) { a = a.meet(PrimitiveType.getPrimitive(p[i])); } } else { IClassHierarchy cha = m.getClassHierarchy(); IClass p0 = cha.lookupClass(p[0]); a = new ConeType(p0); for (i = 1; i < p.length; i++) { IClass pi = cha.lookupClass(p[i]); a = a.meet(new ConeType(pi)); } } return m.addPhi(values); } } @Override public boolean equals(Object obj) { // assume these are managed canonically return this == obj; } /** * Add a call to this entrypoint from the fake root method * * @param m the Fake Root Method * @return the call instruction added, or null if the operation fails */ public SSAAbstractInvokeInstruction addCall(AbstractRootMethod m) { int paramValues[]; CallSiteReference site = makeSite(0); if (site == null) { return null; } paramValues = new int[getNumberOfParameters()]; for (int j = 0; j < paramValues.length; j++) { paramValues[j] = makeArgument(m, j); if (paramValues[j] == -1) { // there was a problem return null; } } return m.addInvocation(paramValues, site); } /** @return the method this call invokes */ public IMethod getMethod() { return method; } /** @return types to allocate for parameter i; for non-static methods, parameter 0 is "this" */ public abstract TypeReference[] getParameterTypes(int i); /** @return number of parameters to this call, including "this" for non-statics */ public abstract int getNumberOfParameters(); @Override public String toString() { StringBuilder result = new StringBuilder(method.toString()); result.append('('); for (int i = 0; i < getNumberOfParameters() - 1; i++) { result.append(Arrays.toString(getParameterTypes(i))); result.append(','); } if (getNumberOfParameters() > 0) { result.append(Arrays.toString(getParameterTypes(getNumberOfParameters() - 1))); } result.append(')'); return result.toString(); } @Override public int hashCode() { return method.hashCode() * 1009; } }
6,991
33.107317
100
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/ipa/callgraph/IAnalysisCacheView.java
/* * Copyright (c) 2007 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package com.ibm.wala.ipa.callgraph; import com.ibm.wala.classLoader.IMethod; import com.ibm.wala.ipa.callgraph.impl.Everywhere; import com.ibm.wala.ssa.DefUse; import com.ibm.wala.ssa.IR; import com.ibm.wala.ssa.IRFactory; import com.ibm.wala.ssa.SSAOptions; public interface IAnalysisCacheView { void invalidate(IMethod method, Context C); IRFactory<IMethod> getIRFactory(); /** * Find or create an IR for the method using the {@link Everywhere} context and default {@link * SSAOptions} */ IR getIR(IMethod method); /** Find or create a DefUse for the IR using the {@link Everywhere} context */ DefUse getDefUse(IR ir); IR getIR(IMethod method, Context context); void clear(); }
1,081
26.74359
96
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/ipa/callgraph/MethodTargetSelector.java
/* * Copyright (c) 2002 - 2006 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package com.ibm.wala.ipa.callgraph; import com.ibm.wala.classLoader.CallSiteReference; import com.ibm.wala.classLoader.IClass; import com.ibm.wala.classLoader.IMethod; /** * This interface represents policies for selecting a method to call at a given invocation site. The * most obvious such policy would be to look at the relevant class hierarchy and lookup the * appropriate method based on the type reference and name and descriptor at the call site. However, * other policies are possible for purposes such as providing an abstraction of unanalyzed libraries * or specialized J2EE functionality. * * <p>Such policies are consulted by the different analysis mechanisms, both the flow-based and * non-flow algorithms. The current mechanism is that the policy object are registered with the * AnalysisOptions object, and all analyses that need to analyze invocations ask that object for the * method selector to use. * * <p>In general, for specialized selectors, it is good practice to build selectors that handle the * special case of interest, and otherwise delegate to a child selector. When registering with the * AnalysisOptions object, make the child selector be whatever the options object had before. */ public interface MethodTargetSelector { /** * Given a calling node, a call site and (optionally) a dispatch type, return the target method to * be called. * * @param caller the GCNode in the call graph containing the call * @param site the call site reference of the call site * @param receiver the type of the target object or null * @return the method to be called. */ IMethod getCalleeTarget(CGNode caller, CallSiteReference site, IClass receiver); }
2,088
44.413043
100
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/ipa/callgraph/ShallowAnalysisScope.java
/* * Copyright (c) 2007 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package com.ibm.wala.ipa.callgraph; import com.ibm.wala.core.util.config.AnalysisScopeReader; import com.ibm.wala.util.config.SetOfClasses; import java.io.IOException; import java.io.Serializable; import java.util.List; /** * A serializable version of {@link AnalysisScope}. Note: any information about the array class * loader is lost using this representation. */ public class ShallowAnalysisScope implements Serializable { /* Serial version */ private static final long serialVersionUID = -3256390509887654321L; private final SetOfClasses exclusions; // example for a line: "Primordial,Java,jarFile,primordial.jar.model" private final List<String> moduleLinesList; // example for a line: "Synthetic, Java, loaderImpl, // com.ibm.wala.ipa.summaries.BypassSyntheticClassLoader" // may be empty private final List<String> ldrImplLinesList; public ShallowAnalysisScope( SetOfClasses exclusions, List<String> moduleLinesList, List<String> ldrImplLinesList) { if (moduleLinesList == null) { throw new IllegalArgumentException("null moduleLinesList"); } if (ldrImplLinesList == null) { throw new IllegalArgumentException("null ldrImplLinesList"); } this.exclusions = exclusions; this.moduleLinesList = moduleLinesList; this.ldrImplLinesList = ldrImplLinesList; } public AnalysisScope toAnalysisScope() throws IOException { AnalysisScope analysisScope = AnalysisScope.createJavaAnalysisScope(); analysisScope.setExclusions(exclusions); for (String moduleLine : moduleLinesList) { AnalysisScopeReader.instance.processScopeDefLine( analysisScope, this.getClass().getClassLoader(), moduleLine); } for (String ldrLine : ldrImplLinesList) { AnalysisScopeReader.instance.processScopeDefLine( analysisScope, this.getClass().getClassLoader(), ldrLine); } return analysisScope; } @Override public String toString() { StringBuilder result = new StringBuilder(); for (String moduleLine : moduleLinesList) { result.append(moduleLine); result.append('\n'); } return result.toString(); } }
2,520
31.320513
95
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/ipa/callgraph/cha/CHACallGraph.java
/* * Copyright (c) 2007 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package com.ibm.wala.ipa.callgraph.cha; import com.ibm.wala.classLoader.CallSiteReference; import com.ibm.wala.classLoader.IMethod; import com.ibm.wala.classLoader.Language; import com.ibm.wala.classLoader.NewSiteReference; import com.ibm.wala.ipa.callgraph.AnalysisCacheImpl; import com.ibm.wala.ipa.callgraph.AnalysisOptions; import com.ibm.wala.ipa.callgraph.CGNode; import com.ibm.wala.ipa.callgraph.Context; import com.ibm.wala.ipa.callgraph.Entrypoint; import com.ibm.wala.ipa.callgraph.IAnalysisCacheView; import com.ibm.wala.ipa.callgraph.impl.BasicCallGraph; import com.ibm.wala.ipa.callgraph.impl.Everywhere; import com.ibm.wala.ipa.callgraph.impl.ExplicitPredecessorsEdgeManager; import com.ibm.wala.ipa.callgraph.impl.FakeWorldClinitMethod; import com.ibm.wala.ipa.cha.IClassHierarchy; import com.ibm.wala.shrike.shrikeBT.IInvokeInstruction; import com.ibm.wala.ssa.DefUse; import com.ibm.wala.ssa.IR; import com.ibm.wala.util.CancelException; import com.ibm.wala.util.collections.ComposedIterator; import com.ibm.wala.util.collections.FilterIterator; import com.ibm.wala.util.collections.HashMapFactory; import com.ibm.wala.util.collections.HashSetFactory; import com.ibm.wala.util.collections.Iterator2Collection; import com.ibm.wala.util.collections.Iterator2Iterable; import com.ibm.wala.util.collections.IteratorUtil; import com.ibm.wala.util.collections.MapIterator; import com.ibm.wala.util.graph.NumberedEdgeManager; import com.ibm.wala.util.intset.IntSet; import com.ibm.wala.util.intset.IntSetUtil; import com.ibm.wala.util.intset.MutableIntSet; import java.util.ArrayDeque; import java.util.Collections; import java.util.Iterator; import java.util.Map; import java.util.Set; import java.util.function.Predicate; /** Call graph in which call targets are determined entirely based on an {@link IClassHierarchy}. */ public class CHACallGraph extends BasicCallGraph<CHAContextInterpreter> { private final IClassHierarchy cha; private final AnalysisOptions options; private final IAnalysisCacheView cache; /** * if set to true, do not include call graph edges in classes outside the application class * loader. This means callbacks from library to application will be ignored. */ private final boolean applicationOnly; private boolean isInitialized = false; private class CHANode extends NodeImpl { protected CHANode(IMethod method, Context C) { super(method, C); } @Override public IR getIR() { return cache.getIR(method); } @Override public DefUse getDU() { return cache.getDefUse(cache.getIR(method)); } @Override public Iterator<NewSiteReference> iterateNewSites() { return getInterpreter(this).iterateNewSites(this); } @Override public Iterator<CallSiteReference> iterateCallSites() { return getInterpreter(this).iterateCallSites(this); } @Override public boolean equals(Object obj) { return obj.getClass() == getClass() && getMethod().equals(((CHANode) obj).getMethod()); } @Override public int hashCode() { return getMethod().hashCode(); } @Override public boolean addTarget(CallSiteReference reference, CGNode target) { return false; } } /** * NOTE: after calling this contructor, {@link #init(Iterable)} must be invoked to complete * initialization */ public CHACallGraph(IClassHierarchy cha) { this(cha, false); } /** * NOTE: after calling this contructor, {@link #init(Iterable)} must be invoked to complete * initialization */ public CHACallGraph(IClassHierarchy cha, boolean applicationOnly) { this.cha = cha; this.options = new AnalysisOptions(); this.cache = new AnalysisCacheImpl(); this.applicationOnly = applicationOnly; setInterpreter(new ContextInsensitiveCHAContextInterpreter()); } /** * Builds the call graph data structures. The call graph will only include methods reachable from * the provided entrypoints. */ public void init(Iterable<Entrypoint> entrypoints) throws CancelException { super.init(); CGNode root = getFakeRootNode(); int programCounter = 0; for (Entrypoint e : entrypoints) { root.addTarget(e.makeSite(programCounter++), null); } newNodes.push(root); closure(); isInitialized = true; } @Override public IClassHierarchy getClassHierarchy() { return cha; } private final Map<CallSiteReference, Set<IMethod>> targetCache = HashMapFactory.make(); private Iterator<IMethod> getPossibleTargets(CallSiteReference site) { Set<IMethod> result = targetCache.get(site); if (result == null) { if (site.isDispatch()) { result = cha.getPossibleTargets(site.getDeclaredTarget()); } else { IMethod m = cha.resolveMethod(site.getDeclaredTarget()); if (m != null) { result = Collections.singleton(m); } else { result = Collections.emptySet(); } } targetCache.put(site, result); } return result.iterator(); } @Override public Set<CGNode> getPossibleTargets(CGNode node, CallSiteReference site) { return Iterator2Collection.toSet( new MapIterator<>( new FilterIterator<>(getPossibleTargets(site), this::isRelevantMethod), object -> { try { return findOrCreateNode(object, Everywhere.EVERYWHERE); } catch (CancelException e) { assert false : e.toString(); return null; } })); } @Override public int getNumberOfTargets(CGNode node, CallSiteReference site) { return IteratorUtil.count(getPossibleTargets(site)); } @Override public Iterator<CallSiteReference> getPossibleSites(final CGNode src, final CGNode target) { return new FilterIterator<>( getInterpreter(src).iterateCallSites(src), o -> getPossibleTargets(src, o).contains(target)); } private class CHARootNode extends CHANode { private final Set<CallSiteReference> calls = HashSetFactory.make(); protected CHARootNode(IMethod method, Context C) { super(method, C); } @Override public Iterator<CallSiteReference> iterateCallSites() { return calls.iterator(); } @Override public boolean addTarget(CallSiteReference reference, CGNode target) { return calls.add(reference); } } @Override protected CGNode makeFakeRootNode() throws CancelException { return new CHARootNode( Language.JAVA.getFakeRootMethod(cha, options, cache), Everywhere.EVERYWHERE); } @Override protected CGNode makeFakeWorldClinitNode() throws CancelException { return new CHARootNode( new FakeWorldClinitMethod( Language.JAVA.getFakeRootMethod(cha, options, cache).getDeclaringClass(), options, cache), Everywhere.EVERYWHERE); } private int clinitPC = 0; @Override public CGNode findOrCreateNode(IMethod method, Context C) throws CancelException { assert C.equals(Everywhere.EVERYWHERE); assert !method.isAbstract(); CGNode n = getNode(method, C); if (n == null) { assert !isInitialized; n = makeNewNode(method, C); IMethod clinit = method.getDeclaringClass().getClassInitializer(); if (clinit != null && getNode(clinit, Everywhere.EVERYWHERE) == null) { CGNode cln = makeNewNode(clinit, Everywhere.EVERYWHERE); CGNode clinits = getFakeWorldClinitNode(); clinits.addTarget( CallSiteReference.make( clinitPC++, clinit.getReference(), IInvokeInstruction.Dispatch.STATIC), cln); edgeManager.addEdge(clinits, cln); } } return n; } private final ArrayDeque<CGNode> newNodes = new ArrayDeque<>(); private void closure() throws CancelException { while (!newNodes.isEmpty()) { CGNode n = newNodes.pop(); for (CallSiteReference site : Iterator2Iterable.make(n.iterateCallSites())) { Iterator<IMethod> methods = getPossibleTargets(site); while (methods.hasNext()) { IMethod target = methods.next(); if (isRelevantMethod(target)) { CGNode callee = getNode(target, Everywhere.EVERYWHERE); if (callee == null) { callee = findOrCreateNode(target, Everywhere.EVERYWHERE); if (n == getFakeRootNode()) { registerEntrypoint(callee); } } edgeManager.addEdge(n, callee); } } } } } private boolean isRelevantMethod(IMethod target) { return !target.isAbstract() && (!applicationOnly || cha.getScope().isApplicationLoader(target.getDeclaringClass().getClassLoader())); } private CGNode makeNewNode(IMethod method, Context C) { CGNode n; Key k = new Key(method, C); n = new CHANode(method, C); registerNode(k, n); newNodes.push(n); return n; } private class CHACallGraphEdgeManager extends ExplicitPredecessorsEdgeManager { protected CHACallGraphEdgeManager() { super(CHACallGraph.this); } @Override public Iterator<CGNode> getSuccNodes(final CGNode n) { return new FilterIterator<>( new ComposedIterator<>(n.iterateCallSites()) { @Override public Iterator<? extends CGNode> makeInner(CallSiteReference outer) { return getPossibleTargets(n, outer).iterator(); } }, new Predicate<>() { private final MutableIntSet nodes = IntSetUtil.make(); @Override public boolean test(CGNode o) { if (nodes.contains(o.getGraphNodeId())) { return false; } else { nodes.add(o.getGraphNodeId()); return true; } } }); } @Override public int getSuccNodeCount(CGNode N) { return IteratorUtil.count(getSuccNodes(N)); } @Override public void addEdge(CGNode src, CGNode dst) { int x = getNumber(src); int y = getNumber(dst); predecessors.add(y, x); } @Override public void removeEdge(CGNode src, CGNode dst) throws UnsupportedOperationException { assert false; } @Override public void removeAllIncidentEdges(CGNode node) throws UnsupportedOperationException { assert false; } @Override public void removeIncomingEdges(CGNode node) throws UnsupportedOperationException { assert false; } @Override public void removeOutgoingEdges(CGNode node) throws UnsupportedOperationException { assert false; } @Override public boolean hasEdge(CGNode src, CGNode dst) { return getPossibleSites(src, dst).hasNext(); } @Override public IntSet getSuccNodeNumbers(CGNode node) { MutableIntSet result = IntSetUtil.make(); for (CGNode s : Iterator2Iterable.make(getSuccNodes(node))) { result.add(s.getGraphNodeId()); } return result; } } private final CHACallGraphEdgeManager edgeManager = new CHACallGraphEdgeManager(); @Override protected NumberedEdgeManager<CGNode> getEdgeManager() { return edgeManager; } }
11,669
29.791557
100
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/ipa/callgraph/cha/CHAContextInterpreter.java
/* * Copyright (c) 2007 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package com.ibm.wala.ipa.callgraph.cha; import com.ibm.wala.classLoader.CallSiteReference; import com.ibm.wala.classLoader.NewSiteReference; import com.ibm.wala.ipa.callgraph.CGNode; import java.util.Iterator; public interface CHAContextInterpreter { /** * Does this object understand the given method? The caller had better check this before inquiring * on other properties. */ boolean understands(CGNode node); /** * @return an Iterator of the call statements that may execute in a given method for a given * context */ Iterator<CallSiteReference> iterateCallSites(CGNode node); Iterator<NewSiteReference> iterateNewSites(CGNode node); }
1,045
29.764706
100
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/ipa/callgraph/cha/ContextInsensitiveCHAContextInterpreter.java
/* * Copyright (c) 2007 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package com.ibm.wala.ipa.callgraph.cha; import com.ibm.wala.classLoader.CallSiteReference; import com.ibm.wala.classLoader.CodeScanner; import com.ibm.wala.classLoader.NewSiteReference; import com.ibm.wala.ipa.callgraph.CGNode; import com.ibm.wala.shrike.shrikeCT.InvalidClassFileException; import com.ibm.wala.util.debug.Assertions; import java.util.Iterator; public class ContextInsensitiveCHAContextInterpreter implements CHAContextInterpreter { @Override public boolean understands(CGNode node) { return true; } @Override public Iterator<CallSiteReference> iterateCallSites(CGNode node) { if (node == null) { throw new IllegalArgumentException("node is null"); } try { return CodeScanner.getCallSites(node.getMethod()).iterator(); } catch (InvalidClassFileException e) { e.printStackTrace(); Assertions.UNREACHABLE(); return null; } } @Override public Iterator<NewSiteReference> iterateNewSites(CGNode node) { if (node == null) { throw new IllegalArgumentException("node is null"); } try { return CodeScanner.getNewSites(node.getMethod()).iterator(); } catch (InvalidClassFileException e) { throw new RuntimeException(e); } } }
1,615
28.925926
87
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/ipa/callgraph/impl/AbstractRootMethod.java
/* * Copyright (c) 2002 - 2006 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package com.ibm.wala.ipa.callgraph.impl; import com.ibm.wala.cfg.InducedCFG; import com.ibm.wala.classLoader.ArrayClass; import com.ibm.wala.classLoader.CallSiteReference; import com.ibm.wala.classLoader.IClass; import com.ibm.wala.classLoader.IMethod; import com.ibm.wala.classLoader.NewSiteReference; import com.ibm.wala.classLoader.SyntheticMethod; import com.ibm.wala.core.util.warnings.Warning; import com.ibm.wala.core.util.warnings.Warnings; import com.ibm.wala.ipa.callgraph.AnalysisOptions; import com.ibm.wala.ipa.callgraph.CGNode; import com.ibm.wala.ipa.callgraph.Context; import com.ibm.wala.ipa.callgraph.IAnalysisCacheView; import com.ibm.wala.ipa.callgraph.propagation.rta.RTAContextInterpreter; import com.ibm.wala.ipa.cha.IClassHierarchy; import com.ibm.wala.ipa.summaries.SyntheticIR; import com.ibm.wala.shrike.shrikeBT.IInvokeInstruction; import com.ibm.wala.ssa.ConstantValue; 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.SSAInstructionFactory; import com.ibm.wala.ssa.SSAInvokeInstruction; import com.ibm.wala.ssa.SSANewInstruction; import com.ibm.wala.ssa.SSAOptions; import com.ibm.wala.ssa.SSAPhiInstruction; 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 com.ibm.wala.util.collections.EmptyIterator; import com.ibm.wala.util.collections.HashMapFactory; import com.ibm.wala.util.debug.Assertions; import java.util.ArrayList; import java.util.Arrays; import java.util.Iterator; import java.util.Map; /** A synthetic method from the {@link FakeRootClass} */ public abstract class AbstractRootMethod extends SyntheticMethod { public final ArrayList<SSAInstruction> statements = new ArrayList<>(); private final Map<ConstantValue, Integer> constant2ValueNumber = HashMapFactory.make(); /** * The number of the next local value number available for the fake root method. Note that we * reserve value number 1 to represent the value "any exception caught by the root method" */ public int nextLocal = 2; public final IClassHierarchy cha; private final AnalysisOptions options; protected final IAnalysisCacheView cache; protected final SSAInstructionFactory insts; public AbstractRootMethod( MethodReference method, IClass declaringClass, final IClassHierarchy cha, AnalysisOptions options, IAnalysisCacheView cache) { super(method, declaringClass, true, false); this.cha = cha; this.options = options; this.cache = cache; this.insts = declaringClass.getClassLoader().getInstructionFactory(); if (cache == null) { throw new IllegalArgumentException("null cache"); } // I'd like to enforce that declaringClass is a FakeRootClass ... but CASt would currently // break. // so checking dynamically instead. if (declaringClass instanceof FakeRootClass) { ((FakeRootClass) declaringClass).addMethod(this); } } public AbstractRootMethod( MethodReference method, final IClassHierarchy cha, AnalysisOptions options, IAnalysisCacheView cache) { this( method, new FakeRootClass(method.getDeclaringClass().getClassLoader(), cha), cha, options, cache); } /** @see SyntheticMethod#getStatements() */ @SuppressWarnings("deprecation") @Override public SSAInstruction[] getStatements(SSAOptions options) { SSAInstruction[] result = new SSAInstruction[statements.size()]; int i = 0; for (SSAInstruction ssaInstruction : statements) { result[i++] = ssaInstruction; } return result; } @Override public IR makeIR(Context context, SSAOptions options) { SSAInstruction instrs[] = getStatements(options); Map<Integer, ConstantValue> constants = null; if (!constant2ValueNumber.isEmpty()) { constants = HashMapFactory.make(constant2ValueNumber.size()); for (Map.Entry<ConstantValue, Integer> entry : constant2ValueNumber.entrySet()) { constants.put(entry.getValue(), entry.getKey()); } } InducedCFG cfg = makeControlFlowGraph(instrs); return new SyntheticIR(this, Everywhere.EVERYWHERE, cfg, instrs, options, constants); } public int addLocal() { return nextLocal++; } /** * @return the invoke instructions added by this operation * @throws IllegalArgumentException if site is null */ public SSAAbstractInvokeInstruction addInvocation(int[] params, CallSiteReference site) { if (site == null) { throw new IllegalArgumentException("site is null"); } CallSiteReference newSite = CallSiteReference.make( statements.size(), site.getDeclaredTarget(), site.getInvocationCode()); SSAAbstractInvokeInstruction s = null; if (newSite.getDeclaredTarget().getReturnType().equals(TypeReference.Void)) { s = insts.InvokeInstruction(statements.size(), params, nextLocal++, newSite, null); } else { s = insts.InvokeInstruction( statements.size(), nextLocal++, params, nextLocal++, newSite, null); } statements.add(s); cache.invalidate(this, Everywhere.EVERYWHERE); return s; } /** Add a return statement */ public SSAReturnInstruction addReturn(int vn, boolean isPrimitive) { SSAReturnInstruction s = insts.ReturnInstruction(statements.size(), vn, isPrimitive); statements.add(s); cache.invalidate(this, Everywhere.EVERYWHERE); return s; } /** * Add a New statement of the given type * * <p>Side effect: adds call to default constructor of given type if one exists. * * @return instruction added, or null * @throws IllegalArgumentException if T is null */ public SSANewInstruction addAllocation(TypeReference T) { return addAllocation(T, true); } /** Add a New statement of the given array type and length */ public SSANewInstruction add1DArrayAllocation(TypeReference T, int length) { int instance = nextLocal++; NewSiteReference ref = NewSiteReference.make(statements.size(), T); assert T.isArrayType(); assert ((ArrayClass) cha.lookupClass(T)).getDimensionality() == 1; int[] sizes = new int[1]; Arrays.fill(sizes, getValueNumberForIntConstant(length)); SSANewInstruction result = insts.NewInstruction(statements.size(), instance, ref, sizes); statements.add(result); cache.invalidate(this, Everywhere.EVERYWHERE); return result; } /** Add a New statement of the given type */ public SSANewInstruction addAllocationWithoutCtor(TypeReference T) { return addAllocation(T, false); } /** * Add a New statement of the given type * * @return instruction added, or null * @throws IllegalArgumentException if T is null */ private SSANewInstruction addAllocation(TypeReference T, boolean invokeCtor) { if (T == null) { throw new IllegalArgumentException("T is null"); } int instance = nextLocal++; SSANewInstruction result = null; if (T.isReferenceType()) { NewSiteReference ref = NewSiteReference.make(statements.size(), T); if (T.isArrayType()) { int[] sizes = new int[ArrayClass.getArrayTypeDimensionality(T)]; Arrays.fill(sizes, getValueNumberForIntConstant(1)); result = insts.NewInstruction(statements.size(), instance, ref, sizes); } else { result = insts.NewInstruction(statements.size(), instance, ref); } statements.add(result); IClass klass = cha.lookupClass(T); if (klass == null) { Warnings.add(AllocationFailure.create(T)); return null; } if (klass.isArrayClass()) { int arrayRef = result.getDef(); TypeReference e = klass.getReference().getArrayElementType(); while (e != null && !e.isPrimitiveType()) { // allocate an instance for the array contents NewSiteReference n = NewSiteReference.make(statements.size(), e); int alloc = nextLocal++; SSANewInstruction ni = null; if (e.isArrayType()) { int[] sizes = new int[((ArrayClass) cha.lookupClass(T)).getDimensionality()]; Arrays.fill(sizes, getValueNumberForIntConstant(1)); ni = insts.NewInstruction(statements.size(), alloc, n, sizes); } else { ni = insts.NewInstruction(statements.size(), alloc, n); } statements.add(ni); // emit an astore SSAArrayStoreInstruction store = insts.ArrayStoreInstruction( statements.size(), arrayRef, getValueNumberForIntConstant(0), alloc, e); statements.add(store); e = e.isArrayType() ? e.getArrayElementType() : null; arrayRef = alloc; } } if (invokeCtor) { IMethod ctor = cha.resolveMethod(klass, MethodReference.initSelector); if (ctor != null) { addInvocation( new int[] {instance}, CallSiteReference.make( statements.size(), ctor.getReference(), IInvokeInstruction.Dispatch.SPECIAL)); } } } cache.invalidate(this, Everywhere.EVERYWHERE); return result; } public int getValueNumberForIntConstant(int c) { ConstantValue v = new ConstantValue(c); Integer result = constant2ValueNumber.get(v); if (result == null) { result = nextLocal++; constant2ValueNumber.put(v, result); } return result; } public int getValueNumberForByteConstant(byte c) { // treat it like an int constant for now. ConstantValue v = new ConstantValue(c); Integer result = constant2ValueNumber.get(v); if (result == null) { result = nextLocal++; constant2ValueNumber.put(v, result); } return result; } public int getValueNumberForCharConstant(char c) { // treat it like an int constant for now. ConstantValue v = new ConstantValue(c); Integer result = constant2ValueNumber.get(v); if (result == null) { result = nextLocal++; constant2ValueNumber.put(v, result); } return result; } /** A warning for when we fail to allocate a type in the fake root method */ private static class AllocationFailure extends Warning { final TypeReference t; AllocationFailure(TypeReference t) { super(Warning.SEVERE); this.t = t; } @Override public String getMsg() { return getClass().toString() + " : " + t; } public static AllocationFailure create(TypeReference t) { return new AllocationFailure(t); } } public int addPhi(int[] values) { int result = nextLocal++; SSAPhiInstruction phi = insts.PhiInstruction(statements.size(), result, values); statements.add(phi); return result; } public int addGetInstance(FieldReference ref, int object) { int result = nextLocal++; statements.add(insts.GetInstruction(statements.size(), result, object, ref)); return result; } public int addGetStatic(FieldReference ref) { int result = nextLocal++; statements.add(insts.GetInstruction(statements.size(), result, ref)); return result; } public int addCheckcast(TypeReference[] types, int rv, boolean isPEI) { int lv = nextLocal++; statements.add(insts.CheckCastInstruction(statements.size(), lv, rv, types, isPEI)); return lv; } public void addSetInstance(final FieldReference ref, final int baseObject, final int value) { statements.add(insts.PutInstruction(statements.size(), baseObject, value, ref)); } public void addSetStatic(final FieldReference ref, final int value) { statements.add(insts.PutInstruction(statements.size(), value, ref)); } public void addSetArrayField( final TypeReference elementType, final int baseObject, final int indexValue, final int value) { statements.add( insts.ArrayStoreInstruction(statements.size(), baseObject, indexValue, value, elementType)); } public int addGetArrayField( final TypeReference elementType, final int baseObject, final int indexValue) { int result = nextLocal++; statements.add( insts.ArrayLoadInstruction(statements.size(), result, baseObject, indexValue, elementType)); return result; } public RTAContextInterpreter getInterpreter() { return new RTAContextInterpreter() { @Override public Iterator<NewSiteReference> iterateNewSites(CGNode node) { ArrayList<NewSiteReference> result = new ArrayList<>(); SSAInstruction[] statements = getStatements(options.getSSAOptions()); for (SSAInstruction statement : statements) { if (statement instanceof SSANewInstruction) { SSANewInstruction s = (SSANewInstruction) statement; result.add(s.getNewSite()); } } return result.iterator(); } public Iterator<SSAInstruction> getInvokeStatements() { ArrayList<SSAInstruction> result = new ArrayList<>(); SSAInstruction[] statements = getStatements(options.getSSAOptions()); for (SSAInstruction statement : statements) { if (statement instanceof SSAInvokeInstruction) { result.add(statement); } } return result.iterator(); } @Override public Iterator<CallSiteReference> iterateCallSites(CGNode node) { final Iterator<SSAInstruction> I = getInvokeStatements(); return new Iterator<>() { @Override public boolean hasNext() { return I.hasNext(); } @Override public CallSiteReference next() { SSAInvokeInstruction s = (SSAInvokeInstruction) I.next(); return s.getCallSite(); } @Override public void remove() { Assertions.UNREACHABLE(); } }; } @Override public boolean understands(CGNode node) { return node.getMethod() .getDeclaringClass() .equals(AbstractRootMethod.this.getDeclaringClass()); } @Override public boolean recordFactoryType(CGNode node, IClass klass) { // not a factory type return false; } @Override public Iterator<FieldReference> iterateFieldsRead(CGNode node) { return EmptyIterator.instance(); } @Override public Iterator<FieldReference> iterateFieldsWritten(CGNode node) { return EmptyIterator.instance(); } }; } }
15,060
32.468889
100
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/ipa/callgraph/impl/AllApplicationEntrypoints.java
/* * Copyright (c) 2002 - 2006 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package com.ibm.wala.ipa.callgraph.impl; import com.ibm.wala.classLoader.IClass; import com.ibm.wala.classLoader.IMethod; import com.ibm.wala.ipa.callgraph.AnalysisScope; import com.ibm.wala.ipa.callgraph.Entrypoint; import com.ibm.wala.ipa.cha.IClassHierarchy; import java.util.HashSet; import java.util.function.Function; /** Includes all application methods in an analysis scope as entrypoints. */ public class AllApplicationEntrypoints extends HashSet<Entrypoint> { private static final long serialVersionUID = 6541081454519490199L; private static final boolean DEBUG = false; /** * @param scope governing analyais scope * @param cha governing class hierarchy * @throws IllegalArgumentException if cha is null */ public AllApplicationEntrypoints( AnalysisScope scope, final IClassHierarchy cha, Function<IClass, Boolean> isApplicationClass) { if (cha == null) { throw new IllegalArgumentException("cha is null"); } for (IClass klass : cha) { if (!klass.isInterface()) { if (isApplicationClass.apply(klass)) { for (IMethod method : klass.getDeclaredMethods()) { if (!method.isAbstract()) { add(new ArgumentTypeEntrypoint(method, cha)); } } } } } if (DEBUG) { System.err.println((getClass() + "Number of EntryPoints:" + size())); } } public AllApplicationEntrypoints(AnalysisScope scope, final IClassHierarchy cha) { this( scope, cha, (IClass klass) -> scope.getApplicationLoader().equals(klass.getClassLoader().getReference())); } }
2,023
30.625
88
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/ipa/callgraph/impl/ArgumentTypeEntrypoint.java
/* * Copyright (c) 2002 - 2006 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package com.ibm.wala.ipa.callgraph.impl; import com.ibm.wala.classLoader.ArrayClass; import com.ibm.wala.classLoader.IClass; import com.ibm.wala.classLoader.IMethod; import com.ibm.wala.ipa.callgraph.Entrypoint; import com.ibm.wala.ipa.cha.IClassHierarchy; import com.ibm.wala.types.TypeReference; import java.util.Collection; import java.util.Set; /** * An entrypoint which chooses some valid (non-interface) concrete type for each argument, if one is * available. */ public class ArgumentTypeEntrypoint extends Entrypoint { private final TypeReference[][] paramTypes; private final IClassHierarchy cha; /** @throws IllegalArgumentException if method == null */ protected TypeReference[][] makeParameterTypes(IMethod method) throws IllegalArgumentException { if (method == null) { throw new IllegalArgumentException("method == null"); } TypeReference[][] result = new TypeReference[method.getNumberOfParameters()][]; for (int i = 0; i < result.length; i++) { TypeReference t = method.getParameterType(i); if (!t.isPrimitiveType()) { IClass klass = cha.lookupClass(t); if (klass == null) { t = null; } else if (!klass.isInterface() && klass.isAbstract()) { // yes, I've seen classes that are marked as "abstract interface" :) t = chooseAConcreteSubClass(klass); } else if (klass.isInterface()) { t = chooseAnImplementor(klass); } else if (klass.isArrayClass()) { ArrayClass arrayKlass = (ArrayClass) klass; IClass innermost = arrayKlass.getInnermostElementClass(); if (innermost != null && innermost.isInterface()) { TypeReference impl = chooseAnImplementor(innermost); if (impl == null) { t = null; } else { t = TypeReference.findOrCreateArrayOf(impl); for (int dim = 1; dim < arrayKlass.getDimensionality(); dim++) { t = TypeReference.findOrCreateArrayOf(t); } } } } } result[i] = (t == null) ? new TypeReference[0] : new TypeReference[] {t}; } return result; } private TypeReference chooseAnImplementor(IClass iface) { Set<IClass> implementors = cha.getImplementors(iface.getReference()); if (!implementors.isEmpty()) { return implementors.iterator().next().getReference(); } else { return null; } } private TypeReference chooseAConcreteSubClass(IClass klass) { Collection<IClass> subclasses = cha.computeSubClasses(klass.getReference()); for (IClass c : subclasses) { if (!c.isAbstract()) { return c.getReference(); } } return null; } public ArgumentTypeEntrypoint(IMethod method, IClassHierarchy cha) { super(method); this.cha = cha; paramTypes = makeParameterTypes(method); } @Override public TypeReference[] getParameterTypes(int i) { return paramTypes[i]; } @Override public int getNumberOfParameters() { return paramTypes.length; } }
3,452
31.575472
100
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/ipa/callgraph/impl/BasicCallGraph.java
/* * Copyright (c) 2002 - 2006 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package com.ibm.wala.ipa.callgraph.impl; import com.ibm.wala.analysis.reflection.JavaTypeContext; import com.ibm.wala.analysis.typeInference.TypeAbstraction; import com.ibm.wala.classLoader.CallSiteReference; import com.ibm.wala.classLoader.IMethod; import com.ibm.wala.ipa.callgraph.CGNode; import com.ibm.wala.ipa.callgraph.CallGraph; import com.ibm.wala.ipa.callgraph.Context; import com.ibm.wala.ipa.callgraph.ContextKey; import com.ibm.wala.ipa.callgraph.propagation.InstanceKey; import com.ibm.wala.ipa.callgraph.propagation.ReceiverInstanceContext; import com.ibm.wala.ipa.cha.IClassHierarchy; import com.ibm.wala.shrike.shrikeBT.IInvokeInstruction; import com.ibm.wala.types.MethodReference; import com.ibm.wala.util.CancelException; import com.ibm.wala.util.collections.HashMapFactory; import com.ibm.wala.util.collections.HashSetFactory; import com.ibm.wala.util.collections.Iterator2Iterable; import com.ibm.wala.util.collections.NonNullSingletonIterator; import com.ibm.wala.util.debug.Assertions; import com.ibm.wala.util.debug.UnimplementedError; import com.ibm.wala.util.graph.AbstractNumberedGraph; import com.ibm.wala.util.graph.NumberedNodeManager; import com.ibm.wala.util.graph.impl.DelegatingNumberedNodeManager; import com.ibm.wala.util.graph.impl.NodeWithNumber; import com.ibm.wala.util.graph.traverse.DFS; import java.util.Collection; import java.util.Collections; import java.util.Iterator; import java.util.Map; import java.util.Set; /** Basic data structure support for a call graph. */ public abstract class BasicCallGraph<T> extends AbstractNumberedGraph<CGNode> implements CallGraph { private static final boolean DEBUG = false; private final DelegatingNumberedNodeManager<CGNode> nodeManager = new DelegatingNumberedNodeManager<>(); /** A fake root node for the graph */ private CGNode fakeRoot; /** A node which handles all calls to class initializers */ private CGNode fakeWorldClinit; /** An object that handles context interpreter functions */ private T interpreter; /** Set of nodes that are entrypoints for this analysis */ private final Set<CGNode> entrypointNodes = HashSetFactory.make(); /** * A mapping from Key to NodeImpls in the graph. Note that each node is created on demand. This * Map does not include the root node. */ private final Map<Key, CGNode> nodes = HashMapFactory.make(); /** * A mapping from MethodReference to Set of nodes that represent this methodReference. * * <p>TODO: rhs of mapping doesn't have to be a set if it's a singleton; could be a node instead. * * <p>TODO: this is a bit redundant with the nodes Map. Restructure these data structures for * space efficiency. */ protected final Map<MethodReference, Set<CGNode>> mr2Nodes = HashMapFactory.make(); public BasicCallGraph() { super(); } public void init() throws CancelException { fakeRoot = makeFakeRootNode(); Key k = new Key(fakeRoot.getMethod(), fakeRoot.getContext()); registerNode(k, fakeRoot); fakeWorldClinit = makeFakeWorldClinitNode(); if (fakeWorldClinit != null) { k = new Key(fakeWorldClinit.getMethod(), fakeWorldClinit.getContext()); registerNode(k, fakeWorldClinit); // add a call from fakeRoot to fakeWorldClinit CallSiteReference site = CallSiteReference.make( 1, fakeWorldClinit.getMethod().getReference(), IInvokeInstruction.Dispatch.STATIC); // note that the result of addInvocation is a different site, with a different program // counter! site = ((AbstractRootMethod) fakeRoot.getMethod()).addInvocation(null, site).getCallSite(); fakeRoot.addTarget(site, fakeWorldClinit); } } protected abstract CGNode makeFakeRootNode() throws CancelException; protected abstract CGNode makeFakeWorldClinitNode() throws CancelException; /** * Use with extreme care. * * @throws CancelException TODO */ public abstract CGNode findOrCreateNode(IMethod method, Context C) throws CancelException; protected void registerNode(Key K, CGNode N) { nodes.put(K, N); addNode(N); Set<CGNode> s = findOrCreateMr2Nodes(K.m); s.add(N); if (DEBUG) { System.err.println(("registered Node: " + N + " for key " + K)); System.err.println(("now size = " + getNumberOfNodes())); } } private Set<CGNode> findOrCreateMr2Nodes(IMethod method) { Set<CGNode> result = mr2Nodes.get(method.getReference()); if (result == null) { result = HashSetFactory.make(3); mr2Nodes.put(method.getReference(), result); } return result; } protected CGNode getNode(Key K) { return nodes.get(K); } @Override public CGNode getFakeRootNode() { return fakeRoot; } @Override public CGNode getFakeWorldClinitNode() { return fakeWorldClinit; } /** record that a node is an entrypoint */ public void registerEntrypoint(CGNode node) { entrypointNodes.add(node); } /** Note: not all successors of the root node are entrypoints */ @Override public Collection<CGNode> getEntrypointNodes() { return entrypointNodes; } /** A class that represents the a normal node in a call graph. */ public abstract static class NodeImpl extends NodeWithNumber implements CGNode { /** The method this node represents. */ protected final IMethod method; /** The context this node represents. */ private final Context context; protected NodeImpl(IMethod method, Context C) { this.method = method; this.context = C; if (method != null && !method.isWalaSynthetic() && method.isAbstract()) { assert !method.isAbstract() : "Abstract method " + method; } assert C != null; } @Override public IMethod getMethod() { return method; } /** @see java.lang.Object#equals(Object) */ @Override public abstract boolean equals(Object obj); /** @see java.lang.Object#hashCode() */ @Override public abstract int hashCode(); /** @see java.lang.Object#toString() */ @Override public String toString() { return "Node: " + method.toString() + " Context: " + context.toString(); } @Override public Context getContext() { return context; } @Override public IClassHierarchy getClassHierarchy() { return method.getClassHierarchy(); } } @Override public String toString() { StringBuilder result = new StringBuilder(); for (CGNode n : Iterator2Iterable.make( DFS.iterateDiscoverTime(this, new NonNullSingletonIterator<>(getFakeRootNode())))) { result.append(nodeToString(this, n)).append('\n'); } return result.toString(); } public static String nodeToString(CallGraph CG, CGNode n) { StringBuilder result = new StringBuilder(n.toString() + '\n'); if (n.getMethod() != null) { for (CallSiteReference site : Iterator2Iterable.make(n.iterateCallSites())) { Iterator<CGNode> targets = CG.getPossibleTargets(n, site).iterator(); if (targets.hasNext()) { result.append(" - ").append(site).append('\n'); } for (CGNode target : Iterator2Iterable.make(targets)) { result.append(" -> ").append(target).append('\n'); } } } return result.toString(); } @Override public void removeNodeAndEdges(CGNode N) throws UnimplementedError { Assertions.UNREACHABLE(); } /** @return NodeImpl, or null if none found */ @Override public CGNode getNode(IMethod method, Context C) { Key key = new Key(method, C); return getNode(key); } protected static final class Key { private final IMethod m; private final Context C; public Key(IMethod m, Context C) { assert m != null : "null method"; assert C != null : "null context"; this.m = m; this.C = C; } @Override public int hashCode() { return 17 * m.hashCode() + C.hashCode(); } @Override public boolean equals(Object o) { assert o instanceof Key; Key other = (Key) o; return (m.equals(other.m) && C.equals(other.C)); } @Override public String toString() { return "{" + m + ',' + C + '}'; } } @Override public Set<CGNode> getNodes(MethodReference m) { IMethod im = getClassHierarchy().resolveMethod(m); if (im != null) { m = im.getReference(); } Set<CGNode> result = mr2Nodes.get(m); return (result == null) ? Collections.emptySet() : result; } /** * @param node a call graph node we want information about * @return an object that knows how to interpret information about the node */ protected T getInterpreter(CGNode node) { if (interpreter == null) { throw new IllegalStateException("must register an interpreter for this call graph"); } return interpreter; } /** * We override this since this class supports remove() on nodes, but the superclass doesn't. * * @see com.ibm.wala.util.graph.Graph#getNumberOfNodes() */ @Override public int getNumberOfNodes() { return nodes.size(); } /** * We override this since this class supports remove() on nodes, but the superclass doesn't. * * @see com.ibm.wala.util.graph.Graph#iterator() */ @Override public Iterator<CGNode> iterator() { return nodes.values().iterator(); } /** * This implementation is necessary because the underlying SparseNumberedGraph may not support * node membership tests. * * @throws IllegalArgumentException if N is null */ @Override public boolean containsNode(CGNode N) { if (N == null) { throw new IllegalArgumentException("N is null"); } return getNode(N.getMethod(), N.getContext()) != null; } public void setInterpreter(T interpreter) { this.interpreter = interpreter; } @Override protected NumberedNodeManager<CGNode> getNodeManager() { return nodeManager; } public void summarizeByPackage() { Map<String, Integer> packages = HashMapFactory.make(); for (CGNode n : this) { final StringBuilder nmBuilder = new StringBuilder(n.getMethod().getDeclaringClass().getName().toString()) .append('/') .append(n.getMethod().getName()) .append('/') .append(n.getContext().getClass().toString()); if (n.getContext().isA(ReceiverInstanceContext.class)) { nmBuilder .append('/') .append( ((InstanceKey) n.getContext().get(ContextKey.RECEIVER)) .getConcreteType() .getName()); } else if (n.getContext() instanceof JavaTypeContext) { nmBuilder .append('/') .append( ((TypeAbstraction) n.getContext().get(ContextKey.RECEIVER)) .getTypeReference() .getName()); } String nm = nmBuilder.toString(); do { if (packages.containsKey(nm)) { packages.put(nm, 1 + packages.get(nm)); } else { packages.put(nm, 1); } if (nm.indexOf('/') < 0) { break; } nm = nm.substring(0, nm.lastIndexOf('/')); } while (true); } System.err.println("dump of CG"); for (Map.Entry<String, Integer> e : packages.entrySet()) { System.err.println(e + " " + e.getKey()); } } }
11,815
29.375321
100
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/ipa/callgraph/impl/ClassHierarchyClassTargetSelector.java
/* * Copyright (c) 2002 - 2006 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package com.ibm.wala.ipa.callgraph.impl; import com.ibm.wala.classLoader.IClass; import com.ibm.wala.classLoader.NewSiteReference; import com.ibm.wala.ipa.callgraph.CGNode; import com.ibm.wala.ipa.callgraph.ClassTargetSelector; import com.ibm.wala.ipa.cha.IClassHierarchy; /** * A {@link ClassTargetSelector} that simply looks up the declared type of a {@link * NewSiteReference} in the appropriate class hierarchy. */ public class ClassHierarchyClassTargetSelector implements ClassTargetSelector { private final IClassHierarchy cha; /** @param cha governing class hierarchy */ public ClassHierarchyClassTargetSelector(IClassHierarchy cha) { this.cha = cha; } @Override public IClass getAllocatedTarget(CGNode caller, NewSiteReference site) { if (site == null) { throw new IllegalArgumentException("site is null"); } IClass klass = cha.lookupClass(site.getDeclaredType()); if (klass == null) { return null; } else if (klass.isAbstract()) { return null; } else { return klass; } } }
1,435
29.553191
83
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/ipa/callgraph/impl/ClassHierarchyMethodTargetSelector.java
/* * Copyright (c) 2002 - 2006 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package com.ibm.wala.ipa.callgraph.impl; import com.ibm.wala.classLoader.CallSiteReference; import com.ibm.wala.classLoader.IClass; import com.ibm.wala.classLoader.IMethod; import com.ibm.wala.ipa.callgraph.CGNode; import com.ibm.wala.ipa.callgraph.MethodTargetSelector; import com.ibm.wala.ipa.cha.IClassHierarchy; import com.ibm.wala.types.TypeReference; /** * A {@link MethodTargetSelector} that simply looks up the declared type, name and descriptor of a * {@link CallSiteReference} in the appropriate class hierarchy. */ public class ClassHierarchyMethodTargetSelector implements MethodTargetSelector { /** Governing class hierarchy */ private final IClassHierarchy classHierarchy; /** * Initialization. The class hierarchy is needed for lookups and the warnings are used when the * lookups fails (which should never happen). * * @param cha The class hierarchy to use. */ public ClassHierarchyMethodTargetSelector(IClassHierarchy cha) { classHierarchy = cha; } /** * This target selector searches the class hierarchy for the method matching the signature of the * call that is appropriate for the receiver type. * * @throws IllegalArgumentException if call is null */ @Override public IMethod getCalleeTarget(CGNode caller, CallSiteReference call, IClass receiver) { if (call == null) { throw new IllegalArgumentException("call is null"); } IClass klass; TypeReference targetType = call.getDeclaredTarget().getDeclaringClass(); // java virtual calls if (call.isDispatch()) { assert receiver != null : "null receiver for " + call; klass = receiver; // java static calls } else if (call.isFixed()) { klass = classHierarchy.lookupClass(targetType); if (klass == null) { return null; } // anything else } else { return null; } return classHierarchy.resolveMethod(klass, call.getDeclaredTarget().getSelector()); } public boolean mightReturnSyntheticMethod() { return false; } }
2,428
30.141026
99
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/ipa/callgraph/impl/ComposedEntrypoints.java
/* * Copyright (c) 2002 - 2006 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package com.ibm.wala.ipa.callgraph.impl; import com.ibm.wala.ipa.callgraph.Entrypoint; import com.ibm.wala.util.collections.HashSetFactory; import java.util.Iterator; import java.util.Set; /** This class represents the union of two sets of {@link Entrypoint}s. */ public class ComposedEntrypoints implements Iterable<Entrypoint> { private final Set<Entrypoint> entrypoints = HashSetFactory.make(); public ComposedEntrypoints(Iterable<Entrypoint> A, Iterable<Entrypoint> B) { if (A == null) { throw new IllegalArgumentException("A is null"); } if (B == null) { throw new IllegalArgumentException("B is null"); } for (Entrypoint entrypoint : A) { entrypoints.add(entrypoint); } for (Entrypoint entrypoint : B) { entrypoints.add(entrypoint); } } @Override public Iterator<Entrypoint> iterator() { return entrypoints.iterator(); } }
1,282
28.159091
78
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/ipa/callgraph/impl/ContextInsensitiveSelector.java
/* * Copyright (c) 2002 - 2006 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package com.ibm.wala.ipa.callgraph.impl; import com.ibm.wala.classLoader.CallSiteReference; import com.ibm.wala.classLoader.IMethod; import com.ibm.wala.ipa.callgraph.CGNode; import com.ibm.wala.ipa.callgraph.Context; import com.ibm.wala.ipa.callgraph.ContextSelector; import com.ibm.wala.ipa.callgraph.propagation.InstanceKey; import com.ibm.wala.util.intset.EmptyIntSet; import com.ibm.wala.util.intset.IntSet; /** A basic context selector that ignores context. */ public class ContextInsensitiveSelector implements ContextSelector { @Override public Context getCalleeTarget( CGNode caller, CallSiteReference site, IMethod callee, InstanceKey[] receiver) { return Everywhere.EVERYWHERE; } @Override public IntSet getRelevantParameters(CGNode caller, CallSiteReference site) { return EmptyIntSet.instance; } }
1,217
31.918919
86
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/ipa/callgraph/impl/DefaultContextSelector.java
/* * Copyright (c) 2002 - 2006 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package com.ibm.wala.ipa.callgraph.impl; import com.ibm.wala.analysis.reflection.ReflectionContextSelector; import com.ibm.wala.classLoader.CallSiteReference; import com.ibm.wala.classLoader.IMethod; import com.ibm.wala.ipa.callgraph.AnalysisOptions; import com.ibm.wala.ipa.callgraph.CGNode; import com.ibm.wala.ipa.callgraph.Context; import com.ibm.wala.ipa.callgraph.ContextSelector; import com.ibm.wala.ipa.callgraph.propagation.CloneContextSelector; import com.ibm.wala.ipa.callgraph.propagation.InstanceKey; import com.ibm.wala.ipa.cha.IClassHierarchy; import com.ibm.wala.util.intset.IntSet; /** * Default object to control context-insensitive context selection, This includes reflection logic. */ public class DefaultContextSelector implements ContextSelector { private final ContextSelector delegate; public DefaultContextSelector(AnalysisOptions options, IClassHierarchy cha) { if (options == null) { throw new IllegalArgumentException("null options"); } ContextInsensitiveSelector ci = new ContextInsensitiveSelector(); ContextSelector r = ReflectionContextSelector.createReflectionContextSelector(options); ContextSelector s = new DelegatingContextSelector(r, ci); delegate = new DelegatingContextSelector(new CloneContextSelector(cha), s); } @Override public Context getCalleeTarget( CGNode caller, CallSiteReference site, IMethod callee, InstanceKey[] receiver) { if (caller == null) { throw new IllegalArgumentException("null caller"); } return delegate.getCalleeTarget(caller, site, callee, receiver); } @Override public IntSet getRelevantParameters(CGNode caller, CallSiteReference site) { return delegate.getRelevantParameters(caller, site); } }
2,123
36.928571
99
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/ipa/callgraph/impl/DefaultEntrypoint.java
/* * Copyright (c) 2002 - 2006 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package com.ibm.wala.ipa.callgraph.impl; import com.ibm.wala.classLoader.IMethod; import com.ibm.wala.ipa.callgraph.Entrypoint; import com.ibm.wala.ipa.cha.IClassHierarchy; import com.ibm.wala.types.MethodReference; import com.ibm.wala.types.TypeReference; import java.util.Arrays; /** An entrypoint whose parameter types are the declared types. */ public class DefaultEntrypoint extends Entrypoint { private final TypeReference[][] paramTypes; private final IClassHierarchy cha; public DefaultEntrypoint(IMethod method, IClassHierarchy cha) { super(method); if (method == null) { throw new IllegalArgumentException("method is null"); } this.cha = cha; paramTypes = makeParameterTypes(method); assert paramTypes != null : method.toString(); } public DefaultEntrypoint(MethodReference method, IClassHierarchy cha) { super(method, cha); if (method == null) { throw new IllegalArgumentException("method is null"); } this.cha = cha; paramTypes = makeParameterTypes(getMethod()); assert paramTypes != null : method.toString(); } protected TypeReference[][] makeParameterTypes(IMethod method) { TypeReference[][] result = new TypeReference[method.getNumberOfParameters()][]; Arrays.setAll(result, i -> makeParameterTypes(method, i)); return result; } protected TypeReference[] makeParameterTypes(IMethod method, int i) { return new TypeReference[] {method.getParameterType(i)}; } @Override public TypeReference[] getParameterTypes(int i) { return paramTypes[i]; } public void setParameterTypes(int i, TypeReference[] types) { paramTypes[i] = types; } @Override public int getNumberOfParameters() { return paramTypes.length; } public IClassHierarchy getCha() { return cha; } @Override public int hashCode() { final int prime = 31; int result = super.hashCode(); result = prime * result + Arrays.deepHashCode(paramTypes); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (!super.equals(obj)) return false; if (getClass() != obj.getClass()) return false; final DefaultEntrypoint other = (DefaultEntrypoint) obj; if (!Arrays.deepEquals(paramTypes, other.paramTypes)) return false; return true; } }
2,710
27.536842
83
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/ipa/callgraph/impl/DelegatingContextSelector.java
/* * Copyright (c) 2002 - 2006 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package com.ibm.wala.ipa.callgraph.impl; import com.ibm.wala.classLoader.CallSiteReference; import com.ibm.wala.classLoader.IMethod; import com.ibm.wala.ipa.callgraph.CGNode; import com.ibm.wala.ipa.callgraph.Context; import com.ibm.wala.ipa.callgraph.ContextSelector; import com.ibm.wala.ipa.callgraph.DelegatingContext; import com.ibm.wala.ipa.callgraph.propagation.InstanceKey; import com.ibm.wala.util.intset.IntSet; /** * A context selector that first checks with A, then defaults to B. * * <p>If A generates a Context B is ignored completely regardless of the ContextKeys in A. * * @see com.ibm.wala.ipa.callgraph.impl.UnionContextSelector */ public class DelegatingContextSelector implements ContextSelector { private static final boolean DEBUG = false; private final ContextSelector A; private final ContextSelector B; public DelegatingContextSelector(ContextSelector A, ContextSelector B) { this.A = A; this.B = B; if (A == null) { throw new IllegalArgumentException("null A"); } if (B == null) { throw new IllegalArgumentException("null B"); } } @Override public Context getCalleeTarget( CGNode caller, CallSiteReference site, IMethod callee, InstanceKey[] receiver) { if (DEBUG) { System.err.println(("getCalleeTarget " + caller + ' ' + site + ' ' + callee)); System.err.println("Trying with A: " + A.getClass()); System.err.println("Trying with B: " + B.getClass()); } if (A != null) { Context C = A.getCalleeTarget(caller, site, callee, receiver); if (C != null) { if (DEBUG) { System.err.println(("Case A " + A.getClass() + ' ' + C)); } Context CB = B.getCalleeTarget(caller, site, callee, receiver); if (CB != null) { return new DelegatingContext(C, CB); } else { return C; } } } Context C = B.getCalleeTarget(caller, site, callee, receiver); if (DEBUG) { System.err.println(("Case B " + B.getClass() + ' ' + C)); } return C; } @Override public IntSet getRelevantParameters(CGNode caller, CallSiteReference site) { return A.getRelevantParameters(caller, site).union(B.getRelevantParameters(caller, site)); } @Override public String toString() { return "<DelegatingContextSelector A=" + A + " B=" + B + " />"; } }
2,747
30.953488
94
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/ipa/callgraph/impl/Everywhere.java
/* * Copyright (c) 2002 - 2006 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package com.ibm.wala.ipa.callgraph.impl; import com.ibm.wala.ipa.callgraph.Context; import com.ibm.wala.ipa.callgraph.ContextItem; import com.ibm.wala.ipa.callgraph.ContextKey; /** An object that represent the context everywhere; used for context-insensitive analysis */ public class Everywhere implements Context { public static final Everywhere EVERYWHERE = new Everywhere(); private Everywhere() {} /** This context gives no information. */ @Override public ContextItem get(ContextKey name) { return null; } @Override public String toString() { return "Everywhere"; } /** Don't use default hashCode (java.lang.Object) as it's nondeterministic. */ @Override public int hashCode() { return 9851; } @Override public boolean equals(Object obj) { return this == obj; } }
1,200
25.108696
93
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/ipa/callgraph/impl/ExplicitCallGraph.java
/* * Copyright (c) 2002 - 2006 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package com.ibm.wala.ipa.callgraph.impl; import com.ibm.wala.cfg.ControlFlowGraph; import com.ibm.wala.classLoader.CallSiteReference; import com.ibm.wala.classLoader.IMethod; import com.ibm.wala.classLoader.NewSiteReference; import com.ibm.wala.ipa.callgraph.AnalysisOptions; import com.ibm.wala.ipa.callgraph.CGNode; import com.ibm.wala.ipa.callgraph.Context; import com.ibm.wala.ipa.callgraph.IAnalysisCacheView; import com.ibm.wala.ipa.callgraph.propagation.SSAContextInterpreter; import com.ibm.wala.ipa.cha.IClassHierarchy; import com.ibm.wala.shrike.shrikeBT.BytecodeConstants; import com.ibm.wala.ssa.DefUse; import com.ibm.wala.ssa.IR; import com.ibm.wala.ssa.ISSABasicBlock; import com.ibm.wala.ssa.SSAInstruction; import com.ibm.wala.util.CancelException; import com.ibm.wala.util.collections.FilterIterator; import com.ibm.wala.util.collections.HashSetFactory; import com.ibm.wala.util.collections.IntMapIterator; import com.ibm.wala.util.collections.SparseVector; import com.ibm.wala.util.debug.Assertions; import com.ibm.wala.util.graph.NumberedEdgeManager; import com.ibm.wala.util.intset.IntIterator; import com.ibm.wala.util.intset.IntSet; import com.ibm.wala.util.intset.MutableIntSet; import com.ibm.wala.util.intset.MutableSharedBitVectorIntSet; import com.ibm.wala.util.intset.SparseIntSet; import java.lang.ref.WeakReference; import java.util.Collections; import java.util.HashSet; import java.util.Iterator; import java.util.Set; /** A call graph which explicitly holds the target for each call site in each node. */ public class ExplicitCallGraph extends BasicCallGraph<SSAContextInterpreter> implements BytecodeConstants { protected final IClassHierarchy cha; protected final AnalysisOptions options; private final IAnalysisCacheView cache; private final long maxNumberOfNodes; private final IMethod fakeRootMethod; /** special object to track call graph edges */ private final ExplicitEdgeManager edgeManager = makeEdgeManger(); public ExplicitCallGraph( IMethod fakeRootMethod, AnalysisOptions options, IAnalysisCacheView cache) { super(); if (options == null) { throw new IllegalArgumentException("null options"); } if (cache == null) { throw new IllegalArgumentException("null cache"); } this.cha = fakeRootMethod.getClassHierarchy(); this.options = options; this.cache = cache; this.maxNumberOfNodes = options.getMaxNumberOfNodes(); this.fakeRootMethod = fakeRootMethod; } /** subclasses may wish to override! */ protected ExplicitNode makeNode(IMethod method, Context context) { return new ExplicitNode(method, context); } /** subclasses may wish to override! */ @Override protected CGNode makeFakeRootNode() throws CancelException { return findOrCreateNode(fakeRootMethod, Everywhere.EVERYWHERE); } /** subclasses may wish to override! */ @Override protected CGNode makeFakeWorldClinitNode() throws CancelException { return findOrCreateNode( new FakeWorldClinitMethod(fakeRootMethod.getDeclaringClass(), options, cache), Everywhere.EVERYWHERE); } /** */ @Override public CGNode findOrCreateNode(IMethod method, Context context) throws CancelException { if (method == null) { throw new IllegalArgumentException("null method"); } if (context == null) { throw new IllegalArgumentException("null context"); } Key k = new Key(method, context); CGNode result = getNode(k); if (result == null) { if (maxNumberOfNodes == -1 || getNumberOfNodes() < maxNumberOfNodes) { result = makeNode(method, context); registerNode(k, result); } else { throw CancelException.make("Too many nodes"); } } return result; } public class ExplicitNode extends NodeImpl { /** * A Mapping from call site program counter (int) -&gt; Object, where Object is a CGNode if * we've discovered exactly one target for the site, or an IntSet of node numbers if we've * discovered more than one target for the site. */ protected final SparseVector<Object> targets = new SparseVector<>(); private final MutableSharedBitVectorIntSet allTargets = new MutableSharedBitVectorIntSet(); private WeakReference<IR> ir = new WeakReference<>(null); private WeakReference<DefUse> du = new WeakReference<>(null); protected ExplicitNode(IMethod method, Context C) { super(method, C); } protected Set<CGNode> getPossibleTargets(CallSiteReference site) { Object result = targets.get(site.getProgramCounter()); if (result == null) { return Collections.emptySet(); } else if (result instanceof CGNode) { Set<CGNode> s = Collections.singleton((CGNode) result); return s; } else { IntSet s = (IntSet) result; HashSet<CGNode> h = HashSetFactory.make(s.size()); for (IntIterator it = s.intIterator(); it.hasNext(); ) { h.add(getCallGraph().getNode(it.next())); } return h; } } protected IntSet getPossibleTargetNumbers(CallSiteReference site) { Object t = targets.get(site.getProgramCounter()); if (t == null) { return null; } else if (t instanceof CGNode) { return SparseIntSet.singleton(getCallGraph().getNumber((CGNode) t)); } else { return (IntSet) t; } } protected Iterator<CallSiteReference> getPossibleSites(final CGNode to) { final int n = getCallGraph().getNumber(to); return new FilterIterator<>( iterateCallSites(), o -> { IntSet s = getPossibleTargetNumbers(o); return s == null ? false : s.contains(n); }); } protected int getNumberOfTargets(CallSiteReference site) { Object result = targets.get(site.getProgramCounter()); if (result == null) { return 0; } else if (result instanceof CGNode) { return 1; } else { return ((IntSet) result).size(); } } @Override public boolean addTarget(CallSiteReference site, CGNode tNode) { return addTarget(site.getProgramCounter(), tNode); } protected boolean addTarget(int pc, CGNode tNode) { allTargets.add(getCallGraph().getNumber(tNode)); Object S = targets.get(pc); if (S == null) { S = tNode; targets.set(pc, S); getCallGraph().addEdge(this, tNode); return true; } else { if (S instanceof CGNode) { if (S.equals(tNode)) { return false; } else { MutableSharedBitVectorIntSet s = new MutableSharedBitVectorIntSet(); s.add(getCallGraph().getNumber((CGNode) S)); s.add(getCallGraph().getNumber(tNode)); getCallGraph().addEdge(this, tNode); targets.set(pc, s); return true; } } else { MutableIntSet s = (MutableIntSet) S; int n = getCallGraph().getNumber(tNode); if (!s.contains(n)) { s.add(n); getCallGraph().addEdge(this, tNode); return true; } else { return false; } } } } /** * @see * com.ibm.wala.ipa.callgraph.impl.BasicCallGraph.NodeImpl#removeNodeAndEdges(com.ibm.wala.ipa.callgraph.CGNode) */ public void removeTarget(CGNode target) { allTargets.remove(getCallGraph().getNumber(target)); for (IntIterator it = targets.safeIterateIndices(); it.hasNext(); ) { int pc = it.next(); Object value = targets.get(pc); if (value instanceof CGNode) { if (value.equals(target)) { targets.remove(pc); } } else { MutableIntSet s = (MutableIntSet) value; int n = getCallGraph().getNumber(target); if (s.size() > 2) { s.remove(n); } else { assert s.size() == 2; if (s.contains(n)) { s.remove(n); int i = s.intIterator().next(); targets.set(pc, getCallGraph().getNode(i)); } } } } } @Override public boolean equals(Object obj) { // we can use object equality since these objects are canonical as created // by the governing ExplicitCallGraph return this == obj; } @Override public int hashCode() { // TODO: cache? return getMethod().hashCode() * 8681 + getContext().hashCode(); } protected MutableSharedBitVectorIntSet getAllTargetNumbers() { return allTargets; } public void clearAllTargets() { targets.clear(); allTargets.clear(); } @Override public IR getIR() { if (getMethod().isWalaSynthetic()) { // disable local cache in this case, as context interpreters // do weird things like mutate IRs return getCallGraph().getInterpreter(this).getIR(this); } IR ir = this.ir.get(); if (ir == null) { ir = getCallGraph().getInterpreter(this).getIR(this); this.ir = new WeakReference<>(ir); } return ir; } @Override public DefUse getDU() { if (getMethod().isWalaSynthetic()) { // disable local cache in this case, as context interpreters // do weird things like mutate IRs return getCallGraph().getInterpreter(this).getDU(this); } DefUse du = this.du.get(); if (du == null) { du = getCallGraph().getInterpreter(this).getDU(this); this.du = new WeakReference<>(du); } return du; } public ExplicitCallGraph getCallGraph() { return ExplicitCallGraph.this; } @Override public Iterator<CallSiteReference> iterateCallSites() { return getCallGraph().getInterpreter(this).iterateCallSites(this); } @Override public Iterator<NewSiteReference> iterateNewSites() { return getCallGraph().getInterpreter(this).iterateNewSites(this); } public ControlFlowGraph<SSAInstruction, ISSABasicBlock> getCFG() { return getCallGraph().getInterpreter(this).getCFG(this); } } /** @see com.ibm.wala.ipa.callgraph.CallGraph#getClassHierarchy() */ @Override public IClassHierarchy getClassHierarchy() { return cha; } protected class ExplicitEdgeManager extends ExplicitPredecessorsEdgeManager { protected ExplicitEdgeManager() { super(ExplicitCallGraph.this); } @Override public IntSet getSuccNodeNumbers(CGNode node) { ExplicitNode n = (ExplicitNode) node; return n.getAllTargetNumbers(); } @Override public Iterator<CGNode> getSuccNodes(CGNode N) { ExplicitNode n = (ExplicitNode) N; return new IntMapIterator<>(n.getAllTargetNumbers().intIterator(), toNode); } @Override public int getSuccNodeCount(CGNode N) { ExplicitNode n = (ExplicitNode) N; return n.getAllTargetNumbers().size(); } @Override public void addEdge(CGNode src, CGNode dst) { // we assume that this is called from ExplicitNode.addTarget(). // so we only have to track the inverse edge. int x = getNumber(src); int y = getNumber(dst); predecessors.add(y, x); } @Override public void removeEdge(CGNode src, CGNode dst) { int x = getNumber(src); int y = getNumber(dst); predecessors.remove(y, x); } protected void addEdge(int x, int y) { // we only have to track the inverse edge. predecessors.add(y, x); } @Override public void removeAllIncidentEdges(CGNode node) { Assertions.UNREACHABLE(); } @Override public void removeIncomingEdges(CGNode node) { Assertions.UNREACHABLE(); } @Override public void removeOutgoingEdges(CGNode node) { Assertions.UNREACHABLE(); } @Override public boolean hasEdge(CGNode src, CGNode dst) { int x = getNumber(src); int y = getNumber(dst); return predecessors.contains(y, x); } } /** @return Returns the edgeManger. */ @Override public NumberedEdgeManager<CGNode> getEdgeManager() { return edgeManager; } protected ExplicitEdgeManager makeEdgeManger() { return new ExplicitEdgeManager(); } @Override public int getNumberOfTargets(CGNode node, CallSiteReference site) { if (!containsNode(node)) { throw new IllegalArgumentException("node not in callgraph " + node); } assert (node instanceof ExplicitNode); ExplicitNode n = (ExplicitNode) node; return n.getNumberOfTargets(site); } @Override public Iterator<CallSiteReference> getPossibleSites(CGNode src, CGNode target) { if (!containsNode(src)) { throw new IllegalArgumentException("node not in callgraph " + src); } if (!containsNode(target)) { throw new IllegalArgumentException("node not in callgraph " + target); } assert (src instanceof ExplicitNode); ExplicitNode n = (ExplicitNode) src; return n.getPossibleSites(target); } @Override public Set<CGNode> getPossibleTargets(CGNode node, CallSiteReference site) { if (!containsNode(node)) { throw new IllegalArgumentException("node not in callgraph " + node); } assert (node instanceof ExplicitNode); ExplicitNode n = (ExplicitNode) node; return n.getPossibleTargets(site); } public IntSet getPossibleTargetNumbers(CGNode node, CallSiteReference site) { if (!containsNode(node)) { throw new IllegalArgumentException("node not in callgraph " + node + " Site: " + site); } assert (node instanceof ExplicitNode); ExplicitNode n = (ExplicitNode) node; return n.getPossibleTargetNumbers(site); } public IAnalysisCacheView getAnalysisCache() { return cache; } }
14,224
29.991285
120
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/ipa/callgraph/impl/ExplicitPredecessorsEdgeManager.java
package com.ibm.wala.ipa.callgraph.impl; import com.ibm.wala.ipa.callgraph.CGNode; import com.ibm.wala.util.collections.EmptyIterator; import com.ibm.wala.util.collections.IntMapIterator; import com.ibm.wala.util.graph.NumberedEdgeManager; import com.ibm.wala.util.graph.NumberedNodeManager; import com.ibm.wala.util.intset.BasicNaturalRelation; import com.ibm.wala.util.intset.IBinaryNaturalRelation; import com.ibm.wala.util.intset.IntSet; import java.util.Iterator; import java.util.function.IntFunction; /** * An abstract {@link NumberedEdgeManager} where predecessor edges are represented explicitly. The * representation of successor edges is determined by concrete subclasses. */ public abstract class ExplicitPredecessorsEdgeManager implements NumberedEdgeManager<CGNode> { private final NumberedNodeManager<CGNode> nodeManager; protected final IntFunction<CGNode> toNode; /** for each y, the {x | (x,y) is an edge) */ protected final IBinaryNaturalRelation predecessors = new BasicNaturalRelation( new byte[] {BasicNaturalRelation.SIMPLE_SPACE_STINGY}, BasicNaturalRelation.SIMPLE); protected ExplicitPredecessorsEdgeManager(NumberedNodeManager<CGNode> nodeManager) { this.nodeManager = nodeManager; toNode = nodeManager::getNode; } @Override public IntSet getPredNodeNumbers(CGNode node) { int y = nodeManager.getNumber(node); return predecessors.getRelated(y); } @Override public Iterator<CGNode> getPredNodes(CGNode N) { IntSet s = getPredNodeNumbers(N); if (s == null) { return EmptyIterator.instance(); } else { return new IntMapIterator<>(s.intIterator(), toNode); } } @Override public int getPredNodeCount(CGNode node) { int y = nodeManager.getNumber(node); return predecessors.getRelatedCount(y); } }
1,828
31.660714
98
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/ipa/callgraph/impl/FakeRootClass.java
/* * Copyright (c) 2002 - 2006 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package com.ibm.wala.ipa.callgraph.impl; import com.ibm.wala.classLoader.IClass; import com.ibm.wala.classLoader.IClassLoader; import com.ibm.wala.classLoader.IField; import com.ibm.wala.classLoader.IMethod; import com.ibm.wala.classLoader.SyntheticClass; import com.ibm.wala.core.util.strings.Atom; import com.ibm.wala.ipa.cha.IClassHierarchy; import com.ibm.wala.types.ClassLoaderReference; import com.ibm.wala.types.FieldReference; import com.ibm.wala.types.Selector; import com.ibm.wala.types.TypeName; import com.ibm.wala.types.TypeReference; import com.ibm.wala.types.annotations.Annotation; import com.ibm.wala.util.collections.HashMapFactory; import com.ibm.wala.util.collections.HashSetFactory; import com.ibm.wala.util.debug.Assertions; import com.ibm.wala.util.debug.UnimplementedError; import java.io.Reader; import java.util.Collection; import java.util.Collections; import java.util.Map; import java.util.Set; /** A synthetic class for the fake root method. */ public class FakeRootClass extends SyntheticClass { public static final TypeReference fakeRootClass(ClassLoaderReference clr) { return TypeReference.findOrCreate(clr, TypeName.string2TypeName("Lcom/ibm/wala/FakeRootClass")); } private Map<Atom, IField> fakeRootStaticFields = null; private final Set<IMethod> methods = HashSetFactory.make(); public FakeRootClass(ClassLoaderReference clr, IClassHierarchy cha) { this(fakeRootClass(clr), cha); } public FakeRootClass(TypeReference typeRef, IClassHierarchy cha) { super(typeRef, cha); } @Override public IClassLoader getClassLoader() { return getClassHierarchy().getLoader(getReference().getClassLoader()); } public void addMethod(IMethod m) { methods.add(m); } public void addStaticField(final Atom name, final TypeReference fieldType) { if (fakeRootStaticFields == null) { fakeRootStaticFields = HashMapFactory.make(2); } fakeRootStaticFields.put( name, new IField() { @Override public IClassHierarchy getClassHierarchy() { return FakeRootClass.this.getClassHierarchy(); } @Override public TypeReference getFieldTypeReference() { return fieldType; } @Override public IClass getDeclaringClass() { return FakeRootClass.this; } @Override public Atom getName() { return name; } @Override public boolean isStatic() { return true; } @Override public boolean isVolatile() { return false; } @Override public FieldReference getReference() { return FieldReference.findOrCreate(FakeRootClass.this.getReference(), name, fieldType); } @Override public boolean isFinal() { return false; } @Override public boolean isPrivate() { return true; } @Override public boolean isProtected() { return false; } @Override public boolean isPublic() { return false; } @Override public Collection<Annotation> getAnnotations() { return Collections.emptySet(); } }); } /** @see com.ibm.wala.classLoader.IClass#getModifiers() */ @Override public int getModifiers() throws UnsupportedOperationException { throw new UnsupportedOperationException(); } /** @see com.ibm.wala.classLoader.IClass#getSuperclass() */ @Override public IClass getSuperclass() throws UnsupportedOperationException { return getClassHierarchy().getRootClass(); } /** @see com.ibm.wala.classLoader.IClass#getAllImplementedInterfaces() */ @Override public Collection<IClass> getAllImplementedInterfaces() throws UnsupportedOperationException { return Collections.emptySet(); } /** @see com.ibm.wala.classLoader.IClass#getAllImplementedInterfaces() */ public Collection<IClass> getAllAncestorInterfaces() throws UnsupportedOperationException { throw new UnsupportedOperationException(); } /** @see com.ibm.wala.classLoader.IClass#getMethod(com.ibm.wala.types.Selector) */ @Override public IMethod getMethod(Selector selector) throws UnsupportedOperationException { for (IMethod m : methods) { if (m.getSelector().equals(selector)) { return m; } } return null; } /** @see com.ibm.wala.classLoader.IClass#getMethod(com.ibm.wala.types.Selector) */ @Override public IField getField(Atom name) { if (fakeRootStaticFields != null) { return fakeRootStaticFields.get(name); } else { return null; } } /** @see com.ibm.wala.classLoader.IClass#getClassInitializer() */ @Override public IMethod getClassInitializer() throws UnimplementedError { Assertions.UNREACHABLE(); return null; } /** @see com.ibm.wala.classLoader.IClass#getDeclaredMethods() */ @Override public Collection<IMethod> getDeclaredMethods() throws UnsupportedOperationException { return Collections.unmodifiableCollection(methods); } /** @see com.ibm.wala.classLoader.IClass#getDeclaredInstanceFields() */ @Override public Collection<IField> getDeclaredInstanceFields() throws UnsupportedOperationException { return Collections.emptySet(); } /** @see com.ibm.wala.classLoader.IClass#getDeclaredStaticFields() */ @Override public Collection<IField> getDeclaredStaticFields() { if (fakeRootStaticFields != null) { return fakeRootStaticFields.values(); } else { return Collections.emptySet(); } } /** @see com.ibm.wala.classLoader.IClass#isReferenceType() */ @Override public boolean isReferenceType() { return getReference().isReferenceType(); } /** @see com.ibm.wala.classLoader.IClass#getDirectInterfaces() */ @Override public Collection<IClass> getDirectInterfaces() throws UnsupportedOperationException { throw new UnsupportedOperationException(); } /** @see com.ibm.wala.classLoader.IClass#getAllInstanceFields() */ @Override public Collection<IField> getAllInstanceFields() { return Collections.emptySet(); } /** @see com.ibm.wala.classLoader.IClass#getAllStaticFields() */ @Override public Collection<IField> getAllStaticFields() { return getDeclaredStaticFields(); } /** @see com.ibm.wala.classLoader.IClass#getAllMethods() */ @Override public Collection<IMethod> getAllMethods() { throw new UnsupportedOperationException(); } /** @see com.ibm.wala.classLoader.IClass#getAllFields() */ @Override public Collection<IField> getAllFields() { return getDeclaredStaticFields(); } @Override public boolean isPublic() { return false; } @Override public boolean isPrivate() { return false; } @Override public Reader getSource() { return null; } }
7,364
27.657588
100
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/ipa/callgraph/impl/FakeRootMethod.java
/* * Copyright (c) 2002 - 2006 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package com.ibm.wala.ipa.callgraph.impl; import com.ibm.wala.cfg.IBasicBlock; import com.ibm.wala.classLoader.IClass; import com.ibm.wala.classLoader.IMethod; import com.ibm.wala.core.util.strings.Atom; import com.ibm.wala.ipa.callgraph.AnalysisOptions; import com.ibm.wala.ipa.callgraph.IAnalysisCacheView; import com.ibm.wala.types.Descriptor; import com.ibm.wala.types.MemberReference; import com.ibm.wala.types.MethodReference; import com.ibm.wala.types.TypeName; import com.ibm.wala.types.TypeReference; /** A synthetic method that models the fake root node. */ public class FakeRootMethod extends AbstractRootMethod { public static final Atom name = Atom.findOrCreateAsciiAtom("fakeRootMethod"); public static final Descriptor descr = Descriptor.findOrCreate(new TypeName[0], TypeReference.VoidName); public FakeRootMethod( final IClass fakeRootClass, AnalysisOptions options, IAnalysisCacheView cache) { super( MethodReference.findOrCreate(fakeRootClass.getReference(), name, descr), fakeRootClass.getClassHierarchy(), options, cache); } /** * @return true iff m is the fake root method. * @throws IllegalArgumentException if m is null */ public boolean isFakeRootMethod(MemberReference m) { if (m == null) { throw new IllegalArgumentException("m is null"); } return m.equals(getReference()); } /** * @return true iff block is a basic block in the fake root method * @throws IllegalArgumentException if block is null */ public static boolean isFromFakeRoot(IBasicBlock<?> block) { if (block == null) { throw new IllegalArgumentException("block is null"); } IMethod m = block.getMethod(); return m instanceof FakeRootMethod && ((FakeRootMethod) m).isFakeRootMethod(m.getReference()); } }
2,202
32.892308
98
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/ipa/callgraph/impl/FakeWorldClinitMethod.java
/* * Copyright (c) 2002 - 2006 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package com.ibm.wala.ipa.callgraph.impl; import com.ibm.wala.classLoader.IClass; import com.ibm.wala.core.util.strings.Atom; import com.ibm.wala.ipa.callgraph.AnalysisOptions; import com.ibm.wala.ipa.callgraph.IAnalysisCacheView; import com.ibm.wala.types.Descriptor; import com.ibm.wala.types.MethodReference; import com.ibm.wala.types.TypeName; import com.ibm.wala.types.TypeReference; /** A synthetic method that calls all class initializers */ public class FakeWorldClinitMethod extends AbstractRootMethod { private static final Atom name = Atom.findOrCreateAsciiAtom("fakeWorldClinit"); private static final Descriptor descr = Descriptor.findOrCreate(new TypeName[0], TypeReference.VoidName); public FakeWorldClinitMethod( final IClass fakeRootClass, AnalysisOptions options, IAnalysisCacheView cache) { super( MethodReference.findOrCreate(fakeRootClass.getReference(), name, descr), fakeRootClass.getClassHierarchy(), options, cache); } }
1,381
34.435897
86
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/ipa/callgraph/impl/PartialCallGraph.java
/* * Copyright (c) 2002 - 2006 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package com.ibm.wala.ipa.callgraph.impl; import com.ibm.wala.classLoader.CallSiteReference; import com.ibm.wala.classLoader.IMethod; import com.ibm.wala.ipa.callgraph.CGNode; import com.ibm.wala.ipa.callgraph.CallGraph; import com.ibm.wala.ipa.callgraph.Context; import com.ibm.wala.ipa.cha.IClassHierarchy; import com.ibm.wala.types.MethodReference; import com.ibm.wala.util.collections.FilterIterator; import com.ibm.wala.util.collections.HashSetFactory; import com.ibm.wala.util.collections.Iterator2Iterable; import com.ibm.wala.util.graph.Graph; import com.ibm.wala.util.graph.GraphSlicer; import com.ibm.wala.util.graph.impl.DelegatingGraph; import com.ibm.wala.util.graph.traverse.DFS; import com.ibm.wala.util.intset.IntSet; import com.ibm.wala.util.intset.IntSetUtil; import com.ibm.wala.util.intset.MutableIntSet; import java.util.Collection; import java.util.Iterator; import java.util.Set; /** a view of a portion of a call graph. */ public class PartialCallGraph extends DelegatingGraph<CGNode> implements CallGraph { protected final CallGraph cg; protected final Collection<CGNode> partialRoots; protected PartialCallGraph( CallGraph cg, Collection<CGNode> partialRoots, Graph<CGNode> partialGraph) { super(partialGraph); this.cg = cg; this.partialRoots = partialRoots; } /** * @param cg the original call graph * @param partialRoots roots of the new, partial graph * @param nodes set of nodes that will be included in the new, partial call graph */ public static PartialCallGraph make( final CallGraph cg, final Collection<CGNode> partialRoots, final Collection<CGNode> nodes) { Graph<CGNode> partialGraph = GraphSlicer.prune(cg, nodes::contains); return new PartialCallGraph(cg, partialRoots, partialGraph); } /** * @param cg the original call graph * @param partialRoots roots of the new, partial graph the result contains only nodes reachable * from the partialRoots in the original call graph. */ public static PartialCallGraph make(CallGraph cg, Collection<CGNode> partialRoots) { final Set<CGNode> nodes = DFS.getReachableNodes(cg, partialRoots); Graph<CGNode> partialGraph = GraphSlicer.prune(cg, nodes::contains); return new PartialCallGraph(cg, partialRoots, partialGraph); } @Override public CGNode getFakeRootNode() throws UnsupportedOperationException { throw new UnsupportedOperationException(); } @Override public CGNode getFakeWorldClinitNode() throws UnsupportedOperationException { throw new UnsupportedOperationException(); } @Override public Collection<CGNode> getEntrypointNodes() { return partialRoots; } @Override public CGNode getNode(IMethod method, Context C) { CGNode x = cg.getNode(method, C); if (x == null) { return null; } return (containsNode(x) ? x : null); } @Override public Set<CGNode> getNodes(MethodReference m) { Set<CGNode> result = HashSetFactory.make(); for (CGNode x : cg.getNodes(m)) { if (containsNode(x)) { result.add(x); } } return result; } @Override public IClassHierarchy getClassHierarchy() { return cg.getClassHierarchy(); } @Override public Iterator<CGNode> iterateNodes(IntSet nodes) { return new FilterIterator<>(cg.iterateNodes(nodes), this::containsNode); } @Override public int getMaxNumber() { return cg.getMaxNumber(); } @Override public CGNode getNode(int index) { CGNode n = cg.getNode(index); return (containsNode(n) ? n : null); } @Override public int getNumber(CGNode n) { return (containsNode(n) ? cg.getNumber(n) : -1); } @Override public IntSet getSuccNodeNumbers(CGNode node) { assert containsNode(node); MutableIntSet x = IntSetUtil.make(); for (CGNode succ : Iterator2Iterable.make(getSuccNodes(node))) { if (containsNode(succ)) { x.add(getNumber(succ)); } } return x; } @Override public IntSet getPredNodeNumbers(CGNode node) { assert containsNode(node); MutableIntSet x = IntSetUtil.make(); for (CGNode pred : Iterator2Iterable.make(getPredNodes(node))) { if (containsNode(pred)) { x.add(getNumber(pred)); } } return x; } @Override public int getNumberOfTargets(CGNode node, CallSiteReference site) { return (containsNode(node) ? getPossibleTargets(node, site).size() : -1); } @Override public Iterator<CallSiteReference> getPossibleSites(CGNode src, CGNode target) { return ((containsNode(src) && containsNode(target)) ? cg.getPossibleSites(src, target) : null); } @Override public Set<CGNode> getPossibleTargets(CGNode node, CallSiteReference site) { if (!containsNode(node)) { return null; } Set<CGNode> result = HashSetFactory.make(); for (CGNode target : cg.getPossibleTargets(node, site)) { if (containsNode(target)) { result.add(target); } } return result; } }
5,372
28.043243
99
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/ipa/callgraph/impl/SubtypesEntrypoint.java
/* * Copyright (c) 2002 - 2006 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package com.ibm.wala.ipa.callgraph.impl; import com.ibm.wala.classLoader.IClass; import com.ibm.wala.classLoader.IMethod; import com.ibm.wala.ipa.cha.IClassHierarchy; import com.ibm.wala.types.MethodReference; import com.ibm.wala.types.TypeReference; import com.ibm.wala.util.collections.HashSetFactory; import java.util.Arrays; import java.util.Collection; import java.util.Set; /** An entrypoint whose parameter types are cones based on declared types. */ public class SubtypesEntrypoint extends DefaultEntrypoint { public SubtypesEntrypoint(MethodReference method, IClassHierarchy cha) { super(method, cha); } public SubtypesEntrypoint(IMethod method, IClassHierarchy cha) { super(method, cha); } @Override protected TypeReference[][] makeParameterTypes(IMethod method) { TypeReference[][] result = new TypeReference[method.getNumberOfParameters()][]; Arrays.setAll(result, i -> makeParameterTypes(method, i)); return result; } @Override protected TypeReference[] makeParameterTypes(IMethod method, int i) { TypeReference nominal = method.getParameterType(i); if (nominal.isPrimitiveType() || nominal.isArrayType()) return new TypeReference[] {nominal}; else { IClass nc = getCha().lookupClass(nominal); if (nc == null) { throw new IllegalStateException("Could not resolve in cha: " + nominal); } Collection<IClass> subcs = nc.isInterface() ? getCha().getImplementors(nominal) : getCha().computeSubClasses(nominal); Set<TypeReference> subs = HashSetFactory.make(); for (IClass cs : subcs) { if (!cs.isAbstract() && !cs.isInterface()) { subs.add(cs.getReference()); } } return subs.toArray(new TypeReference[0]); } } }
2,179
32.538462
97
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/ipa/callgraph/impl/UnionContextSelector.java
/* * Copyright (c) 2002 - 2014 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package com.ibm.wala.ipa.callgraph.impl; import com.ibm.wala.classLoader.CallSiteReference; import com.ibm.wala.classLoader.IMethod; import com.ibm.wala.ipa.callgraph.CGNode; import com.ibm.wala.ipa.callgraph.Context; import com.ibm.wala.ipa.callgraph.ContextSelector; import com.ibm.wala.ipa.callgraph.DelegatingContext; import com.ibm.wala.ipa.callgraph.propagation.InstanceKey; import com.ibm.wala.util.intset.IntSet; /** * Checks ContextSelectors A and B, then returns the union of their findings. * * <p>The returned Context contains the ContextKeys from A and B. If for a given key a value is * generated by A as well as B the value generated by A has the precedence. * * <p>As the UnionContextSelector optionally returns a DelegatingContext it cannot be used to * anihilate ContextValues of B to null. * * @see com.ibm.wala.ipa.callgraph.impl.DelegatingContextSelector * @author Tobias Blaschke &lt;code@tobiasblaschke.de&gt; */ public class UnionContextSelector implements ContextSelector { private final ContextSelector A; private final ContextSelector B; public UnionContextSelector(final ContextSelector A, final ContextSelector B) { if (A == null) { throw new IllegalArgumentException("The ContextSelector given as A may not be null"); } if (B == null) { throw new IllegalArgumentException("The ContextSelector given as B may not be null"); } this.A = A; this.B = B; } /** If only one Context exists return it, else return a DelegatingContext. */ @Override public Context getCalleeTarget( CGNode caller, CallSiteReference site, IMethod callee, InstanceKey[] receiver) { final Context ctxA = A.getCalleeTarget(caller, site, callee, receiver); final Context ctxB = B.getCalleeTarget(caller, site, callee, receiver); if (ctxA == null) { return ctxB; } else if (ctxB == null) { return ctxA; } else { final Context ctxU = new DelegatingContext(ctxA, ctxB); return ctxU; } } @Override public IntSet getRelevantParameters(CGNode caller, CallSiteReference site) { return A.getRelevantParameters(caller, site).union(B.getRelevantParameters(caller, site)); } @Override public String toString() { return "<UnionContextSelector A=" + A + " B=" + B + " />"; } }
2,681
33.831169
95
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/ipa/callgraph/impl/Util.java
/* * Copyright (c) 2002 - 2006 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package com.ibm.wala.ipa.callgraph.impl; import com.ibm.wala.classLoader.IClass; import com.ibm.wala.classLoader.IMethod; import com.ibm.wala.classLoader.Language; import com.ibm.wala.core.util.strings.Atom; import com.ibm.wala.ipa.callgraph.AnalysisOptions; import com.ibm.wala.ipa.callgraph.AnalysisScope; import com.ibm.wala.ipa.callgraph.CallGraphBuilder; import com.ibm.wala.ipa.callgraph.ClassTargetSelector; import com.ibm.wala.ipa.callgraph.ContextSelector; import com.ibm.wala.ipa.callgraph.Entrypoint; import com.ibm.wala.ipa.callgraph.IAnalysisCacheView; import com.ibm.wala.ipa.callgraph.MethodTargetSelector; import com.ibm.wala.ipa.callgraph.propagation.InstanceKey; import com.ibm.wala.ipa.callgraph.propagation.SSAContextInterpreter; import com.ibm.wala.ipa.callgraph.propagation.SSAPropagationCallGraphBuilder; import com.ibm.wala.ipa.callgraph.propagation.cfa.ZeroXCFABuilder; import com.ibm.wala.ipa.callgraph.propagation.cfa.ZeroXContainerCFABuilder; import com.ibm.wala.ipa.callgraph.propagation.cfa.ZeroXInstanceKeys; import com.ibm.wala.ipa.callgraph.propagation.cfa.nCFABuilder; import com.ibm.wala.ipa.callgraph.propagation.cfa.nObjBuilder; import com.ibm.wala.ipa.callgraph.propagation.rta.BasicRTABuilder; import com.ibm.wala.ipa.cha.IClassHierarchy; import com.ibm.wala.ipa.summaries.BypassClassTargetSelector; import com.ibm.wala.ipa.summaries.BypassMethodTargetSelector; import com.ibm.wala.ipa.summaries.LambdaMethodTargetSelector; import com.ibm.wala.ipa.summaries.XMLMethodSummaryReader; import com.ibm.wala.types.ClassLoaderReference; import com.ibm.wala.types.Descriptor; import com.ibm.wala.types.MethodReference; import com.ibm.wala.types.TypeName; import com.ibm.wala.types.TypeReference; import com.ibm.wala.util.collections.HashSetFactory; import com.ibm.wala.util.debug.Assertions; import com.ibm.wala.util.graph.Graph; import java.io.BufferedInputStream; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.util.HashSet; import java.util.Iterator; import java.util.Set; /** Call graph utilities */ public class Util { /** TODO: Make these properties? */ public static String nativeSpec = "natives.xml"; /* BEGIN Custom change: change native spec */ public static void setNativeSpec(String xmlFile) { nativeSpec = xmlFile; } public static String getNativeSpec() { return nativeSpec; } /* END Custom change: change native spec */ /** * Set up an AnalysisOptions object with default selectors, corresponding to class hierarchy * lookup * * @throws IllegalArgumentException if options is null */ public static void addDefaultSelectors(AnalysisOptions options, IClassHierarchy cha) { if (options == null) { throw new IllegalArgumentException("options is null"); } options.setSelector( new LambdaMethodTargetSelector(new ClassHierarchyMethodTargetSelector(cha))); options.setSelector(new ClassHierarchyClassTargetSelector(cha)); } /** * Modify an options object to include bypass logic as specified by a an XML file. * * @throws IllegalArgumentException if scope is null * @throws IllegalArgumentException if cl is null * @throws IllegalArgumentException if options is null * @throws IllegalArgumentException if scope is null * @deprecated This method is being replaced. Please * <p>Use {@link Util#addBypassLogic(AnalysisOptions, ClassLoader, String, IClassHierarchy)} * instead */ @Deprecated public static void addBypassLogic( AnalysisOptions options, @SuppressWarnings("unused") AnalysisScope scope, ClassLoader cl, String xmlFile, IClassHierarchy cha) throws IllegalArgumentException { addBypassLogic(options, cl, xmlFile, cha); } /** * Modify an options object to include bypass logic as specified by a an XML file. * * @throws IllegalArgumentException if scope is null * @throws IllegalArgumentException if cl is null * @throws IllegalArgumentException if options is null * @throws IllegalArgumentException if scope is null */ public static void addBypassLogic( AnalysisOptions options, ClassLoader cl, String xmlFile, IClassHierarchy cha) throws IllegalArgumentException { if (options == null) { throw new IllegalArgumentException("options is null"); } if (cl == null) { throw new IllegalArgumentException("cl is null"); } if (cha == null) { throw new IllegalArgumentException("cha cannot be null"); } try (final InputStream s = cl.getResourceAsStream(xmlFile)) { XMLMethodSummaryReader summary = new XMLMethodSummaryReader(s, cha.getScope()); addBypassLogic(options, cl, summary, cha); } catch (IOException e) { System.err.println("Could not close XML method summary reader: " + e.getLocalizedMessage()); e.printStackTrace(); } } /** * @deprecated Method will be replaced. Please * <p>Use {@link Util#addBypassLogic(AnalysisOptions, ClassLoader, XMLMethodSummaryReader, * IClassHierarchy)} instead */ @Deprecated public static void addBypassLogic( AnalysisOptions options, @SuppressWarnings("unused") AnalysisScope scope, ClassLoader cl, XMLMethodSummaryReader summary, IClassHierarchy cha) throws IllegalArgumentException { addBypassLogic(options, cl, summary, cha); } public static void addBypassLogic( AnalysisOptions options, ClassLoader cl, XMLMethodSummaryReader summary, IClassHierarchy cha) throws IllegalArgumentException { if (options == null) { throw new IllegalArgumentException("options is null"); } if (cl == null) { throw new IllegalArgumentException("cl is null"); } if (cha == null) { throw new IllegalArgumentException("cha cannot be null"); } MethodTargetSelector ms = new BypassMethodTargetSelector( options.getMethodTargetSelector(), summary.getSummaries(), summary.getIgnoredPackages(), cha); options.setSelector(ms); ClassTargetSelector cs = new BypassClassTargetSelector( options.getClassTargetSelector(), summary.getAllocatableClasses(), cha, cha.getLoader(cha.getScope().getLoader(Atom.findOrCreateUnicodeAtom("Synthetic")))); options.setSelector(cs); } /** * @return set of all eligible Main classes in the class hierarchy * @throws IllegalArgumentException if scope is null * @deprecated * <p>Use {@link Util#makeMainEntrypoints(IClassHierarchy)} instead */ @Deprecated public static Iterable<Entrypoint> makeMainEntrypoints( @SuppressWarnings("unused") AnalysisScope scope, IClassHierarchy cha) { return makeMainEntrypoints(cha); } /** * @return set of all eligible Main classes in the class hierarchy * @throws IllegalArgumentException if scope is null */ public static Iterable<Entrypoint> makeMainEntrypoints(IClassHierarchy cha) { return makeMainEntrypoints(cha.getScope().getApplicationLoader(), cha); } public static Iterable<Entrypoint> makeMainEntrypoints( ClassLoaderReference clr, IClassHierarchy cha) { if (cha == null) { throw new IllegalArgumentException("cha is null"); } final Atom mainMethod = Atom.findOrCreateAsciiAtom("main"); final HashSet<Entrypoint> result = HashSetFactory.make(); for (IClass klass : cha) { if (klass.getClassLoader().getReference().equals(clr)) { MethodReference mainRef = MethodReference.findOrCreate( klass.getReference(), mainMethod, Descriptor.findOrCreateUTF8("([Ljava/lang/String;)V")); IMethod m = klass.getMethod(mainRef.getSelector()); if (m != null) { result.add(new DefaultEntrypoint(m, cha)); } } } return result::iterator; } /** * @deprecated * <p>Use {@link Util#makeMainEntrypoints(IClassHierarchy, String)} */ @Deprecated public static Iterable<Entrypoint> makeMainEntrypoints( @SuppressWarnings("unused") AnalysisScope scope, final IClassHierarchy cha, String className) { return makeMainEntrypoints(scope, cha, new String[] {className}); } /** @return Entrypoints for a set of J2SE Main classes */ public static Iterable<Entrypoint> makeMainEntrypoints( final IClassHierarchy cha, String className) { return makeMainEntrypoints(cha, new String[] {className}); } /** * @deprecated Please * <p>Use {@link Util#makeMainEntrypoints(IClassHierarchy, String[])} */ @Deprecated public static Iterable<Entrypoint> makeMainEntrypoints( @SuppressWarnings("unused") final AnalysisScope scope, final IClassHierarchy cha, final String[] classNames) { return makeMainEntrypoints(cha, classNames); } /** @return Entrypoints for a set of J2SE Main classes */ public static Iterable<Entrypoint> makeMainEntrypoints( final IClassHierarchy cha, final String[] classNames) { if (cha == null) { throw new IllegalArgumentException("cha is null"); } return makeMainEntrypoints(cha.getScope().getApplicationLoader(), cha, classNames); } /** * @return Entrypoints for a set of J2SE Main classes * @throws IllegalArgumentException if classNames == null * @throws IllegalArgumentException if (classNames != null) and (0 &lt; classNames.length) and * (classNames[0] == null) * @throws IllegalArgumentException if classNames.length == 0 */ public static Iterable<Entrypoint> makeMainEntrypoints( final ClassLoaderReference loaderRef, final IClassHierarchy cha, final String[] classNames) throws IllegalArgumentException { if (classNames == null) { throw new IllegalArgumentException("classNames == null"); } if (classNames.length == 0) { throw new IllegalArgumentException("classNames.length == 0"); } if (classNames[0] == null && 0 < classNames.length) { throw new IllegalArgumentException("(0 < classNames.length) and (classNames[0] == null)"); } for (String className : classNames) { if (className.indexOf('L') != 0) { throw new IllegalArgumentException("Expected class name to start with L " + className); } if (className.indexOf('.') > 0) { Assertions.productionAssertion( false, "Expected class name formatted with /, not . " + className); } } return () -> { final Atom mainMethod = Atom.findOrCreateAsciiAtom("main"); return new Iterator<>() { private int index = 0; @Override public void remove() { Assertions.UNREACHABLE(); } @Override public boolean hasNext() { return index < classNames.length; } @Override public Entrypoint next() { TypeReference T = TypeReference.findOrCreate(loaderRef, TypeName.string2TypeName(classNames[index++])); MethodReference mainRef = MethodReference.findOrCreate( T, mainMethod, Descriptor.findOrCreateUTF8("([Ljava/lang/String;)V")); return new DefaultEntrypoint(mainRef, cha); } }; }; } /** create a set holding the contents of an {@link Iterator} */ public static <T> Set<T> setify(Iterator<? extends T> x) { if (x == null) { throw new IllegalArgumentException("Null x"); } Set<T> y = HashSetFactory.make(); while (x.hasNext()) { y.add(x.next()); } return y; } /** * @throws IllegalArgumentException if subG is null * @throws IllegalArgumentException if supG is null */ public static <T> void checkGraphSubset(Graph<T> supG, Graph<T> subG) { if (supG == null) { throw new IllegalArgumentException("supG is null"); } if (subG == null) { throw new IllegalArgumentException("subG is null"); } Set<T> nodeDiff = setify(subG.iterator()); nodeDiff.removeAll(setify(supG.iterator())); if (!nodeDiff.isEmpty()) { System.err.println("supergraph: "); System.err.println(supG); System.err.println("subgraph: "); System.err.println(subG); System.err.println("nodeDiff: "); for (T t : nodeDiff) { System.err.println(t.toString()); } Assertions.productionAssertion(nodeDiff.isEmpty(), "bad superset, see tracefile\n"); } for (T m : subG) { Set<T> succDiff = setify(subG.getSuccNodes(m)); succDiff.removeAll(setify(supG.getSuccNodes(m))); if (!succDiff.isEmpty()) { Assertions.productionAssertion( succDiff.isEmpty(), "bad superset for successors of " + m + ':' + succDiff); } Set<T> predDiff = setify(subG.getPredNodes(m)); predDiff.removeAll(setify(supG.getPredNodes(m))); if (!predDiff.isEmpty()) { System.err.println("supergraph: "); System.err.println(supG); System.err.println("subgraph: "); System.err.println(subG); System.err.println("predDiff: "); for (T t : predDiff) { System.err.println(t.toString()); } Assertions.UNREACHABLE("bad superset for predecessors of " + m + ':' + predDiff); } } } /** * @return an RTA Call Graph builder. * @param options options that govern call graph construction * @param cha governing class hierarchy * @param scope representation of the analysis scope * @deprecated * <p>Use {@link Util#makeRTABuilder(AnalysisOptions, IAnalysisCacheView, IClassHierarchy)} */ @Deprecated public static CallGraphBuilder<InstanceKey> makeRTABuilder( AnalysisOptions options, IAnalysisCacheView cache, IClassHierarchy cha, @SuppressWarnings("unused") AnalysisScope scope) { return makeRTABuilder(options, cache, cha); } /** * @return an RTA Call Graph builder. * @param options options that govern call graph construction * @param cha governing class hierarchy */ public static CallGraphBuilder<InstanceKey> makeRTABuilder( AnalysisOptions options, IAnalysisCacheView cache, IClassHierarchy cha) { addDefaultSelectors(options, cha); addDefaultBypassLogic(options, cha.getScope(), Util.class.getClassLoader(), cha); return new BasicRTABuilder(cha, options, cache, null, null); } /** * @param options options that govern call graph construction * @param cha governing class hierarchy * @param scope representation of the analysis scope * @return a 0-CFA Call Graph Builder. * @deprecated * <p>Use {@link Util#makeZeroCFABuilder(Language, AnalysisOptions, IAnalysisCacheView, * IClassHierarchy)} */ @Deprecated public static SSAPropagationCallGraphBuilder makeZeroCFABuilder( Language l, AnalysisOptions options, IAnalysisCacheView cache, IClassHierarchy cha, @SuppressWarnings("unused") AnalysisScope scope) { return makeZeroCFABuilder(l, options, cache, cha); } /** * @param options options that govern call graph construction * @param cha governing class hierarchy * @return a 0-CFA Call Graph Builder. */ public static SSAPropagationCallGraphBuilder makeZeroCFABuilder( Language l, AnalysisOptions options, IAnalysisCacheView cache, IClassHierarchy cha) { return makeZeroCFABuilder(l, options, cache, cha, null, null); } /** * @param options options that govern call graph construction * @param cha governing class hierarchy * @param scope representation of the analysis scope * @param customSelector user-defined context selector, or null if none * @param customInterpreter user-defined context interpreter, or null if none * @return a 0-CFA Call Graph Builder. * @throws IllegalArgumentException if options is null * @deprecated * <p>Use {@link Util#makeZeroCFABuilder(Language, AnalysisOptions, IAnalysisCacheView, * IClassHierarchy, ContextSelector, SSAContextInterpreter)} */ @Deprecated public static SSAPropagationCallGraphBuilder makeZeroCFABuilder( Language l, AnalysisOptions options, IAnalysisCacheView cache, IClassHierarchy cha, @SuppressWarnings("unused") AnalysisScope scope, ContextSelector customSelector, SSAContextInterpreter customInterpreter) { return makeZeroCFABuilder(l, options, cache, cha, customSelector, customInterpreter); } /** * @param options options that govern call graph construction * @param cha governing class hierarchy * @param customSelector user-defined context selector, or null if none * @param customInterpreter user-defined context interpreter, or null if none * @return a 0-CFA Call Graph Builder. * @throws IllegalArgumentException if options is null */ public static SSAPropagationCallGraphBuilder makeZeroCFABuilder( Language l, AnalysisOptions options, IAnalysisCacheView cache, IClassHierarchy cha, ContextSelector customSelector, SSAContextInterpreter customInterpreter) { if (options == null) { throw new IllegalArgumentException("options is null"); } addDefaultSelectors(options, cha); addDefaultBypassLogic(options, Util.class.getClassLoader(), cha); return ZeroXCFABuilder.make( l, cha, options, cache, customSelector, customInterpreter, ZeroXInstanceKeys.NONE); } /** * @return a 0-1-CFA Call Graph Builder. * @param options options that govern call graph construction * @param cha governing class hierarchy * @param scope representation of the analysis scope * @deprecated * <p>Use {@link Util#makeZeroOneCFABuilder(Language, AnalysisOptions, IAnalysisCacheView, * IClassHierarchy)} */ @Deprecated public static SSAPropagationCallGraphBuilder makeZeroOneCFABuilder( Language l, AnalysisOptions options, IAnalysisCacheView cache, IClassHierarchy cha, @SuppressWarnings("unused") AnalysisScope scope) { return makeZeroOneCFABuilder(l, options, cache, cha, null, null); } /** * @return a 0-1-CFA Call Graph Builder. * @param options options that govern call graph construction * @param cha governing class hierarchy */ public static SSAPropagationCallGraphBuilder makeZeroOneCFABuilder( Language l, AnalysisOptions options, IAnalysisCacheView cache, IClassHierarchy cha) { return makeZeroOneCFABuilder(l, options, cache, cha, null, null); } /** * @param options options that govern call graph construction * @param cha governing class hierarchy * @param scope representation of the analysis scope * @param customSelector user-defined context selector, or null if none * @param customInterpreter user-defined context interpreter, or null if none * @return a 0-1-CFA Call Graph Builder. * @throws IllegalArgumentException if options is null * @deprecated * <p>Use {@link Util#makeVanillaZeroOneCFABuilder(Language, AnalysisOptions, * IAnalysisCacheView, IClassHierarchy, ContextSelector, SSAContextInterpreter)} */ @Deprecated public static SSAPropagationCallGraphBuilder makeVanillaZeroOneCFABuilder( Language l, AnalysisOptions options, IAnalysisCacheView analysisCache, IClassHierarchy cha, @SuppressWarnings("unused") AnalysisScope scope, ContextSelector customSelector, SSAContextInterpreter customInterpreter) { return makeVanillaZeroOneCFABuilder( l, options, analysisCache, cha, customSelector, customInterpreter); } /** * @param options options that govern call graph construction * @param cha governing class hierarchy * @param customSelector user-defined context selector, or null if none * @param customInterpreter user-defined context interpreter, or null if none * @return a 0-1-CFA Call Graph Builder. * @throws IllegalArgumentException if options is null */ public static SSAPropagationCallGraphBuilder makeVanillaZeroOneCFABuilder( Language l, AnalysisOptions options, IAnalysisCacheView analysisCache, IClassHierarchy cha, ContextSelector customSelector, SSAContextInterpreter customInterpreter) { if (options == null) { throw new IllegalArgumentException("options is null"); } addDefaultSelectors(options, cha); addDefaultBypassLogic(options, Util.class.getClassLoader(), cha); return ZeroXCFABuilder.make( l, cha, options, analysisCache, customSelector, customInterpreter, ZeroXInstanceKeys.ALLOCATIONS | ZeroXInstanceKeys.CONSTANT_SPECIFIC); } /** * @return a 0-1-CFA Call Graph Builder. * @param options options that govern call graph construction * @param cha governing class hierarchy * @param scope representation of the analysis scope * @deprecated * <p>use {@link Util#makeVanillaZeroOneCFABuilder(Language, AnalysisOptions, * IAnalysisCacheView, IClassHierarchy)} */ @Deprecated public static SSAPropagationCallGraphBuilder makeVanillaZeroOneCFABuilder( Language l, AnalysisOptions options, IAnalysisCacheView analysisCache, IClassHierarchy cha, @SuppressWarnings("unused") AnalysisScope scope) { return makeVanillaZeroOneCFABuilder(l, options, analysisCache, cha, null, null); } /** * @return a 0-1-CFA Call Graph Builder. * @param options options that govern call graph construction * @param cha governing class hierarchy */ public static SSAPropagationCallGraphBuilder makeVanillaZeroOneCFABuilder( Language l, AnalysisOptions options, IAnalysisCacheView analysisCache, IClassHierarchy cha) { return makeVanillaZeroOneCFABuilder(l, options, analysisCache, cha, null, null); } /** * @param options options that govern call graph construction * @param cha governing class hierarchy * @param scope representation of the analysis scope * @param customSelector user-defined context selector, or null if none * @param customInterpreter user-defined context interpreter, or null if none * @return a 0-1-CFA Call Graph Builder. * @throws IllegalArgumentException if options is null * @deprecated * <p>Use {@link Util#makeZeroOneCFABuilder(Language, AnalysisOptions, IAnalysisCacheView, * IClassHierarchy, ContextSelector, SSAContextInterpreter)} */ @Deprecated public static SSAPropagationCallGraphBuilder makeZeroOneCFABuilder( Language l, AnalysisOptions options, IAnalysisCacheView cache, IClassHierarchy cha, @SuppressWarnings("unused") AnalysisScope scope, ContextSelector customSelector, SSAContextInterpreter customInterpreter) { return makeZeroOneCFABuilder(l, options, cache, cha, customSelector, customInterpreter); } /** * @param options options that govern call graph construction * @param cha governing class hierarchy * @param customSelector user-defined context selector, or null if none * @param customInterpreter user-defined context interpreter, or null if none * @return a 0-1-CFA Call Graph Builder. * @throws IllegalArgumentException if options is null */ public static SSAPropagationCallGraphBuilder makeZeroOneCFABuilder( Language l, AnalysisOptions options, IAnalysisCacheView cache, IClassHierarchy cha, ContextSelector customSelector, SSAContextInterpreter customInterpreter) { if (options == null) { throw new IllegalArgumentException("options is null"); } addDefaultSelectors(options, cha); addDefaultBypassLogic(options, Util.class.getClassLoader(), cha); return ZeroXCFABuilder.make( l, cha, options, cache, customSelector, customInterpreter, ZeroXInstanceKeys.ALLOCATIONS | ZeroXInstanceKeys.SMUSH_MANY | ZeroXInstanceKeys.SMUSH_PRIMITIVE_HOLDERS | ZeroXInstanceKeys.SMUSH_STRINGS | ZeroXInstanceKeys.SMUSH_THROWABLES); } /** * @param options options that govern call graph construction * @param cha governing class hierarchy * @param scope representation of the analysis scope * @return a 0-CFA Call Graph Builder augmented with extra logic for containers * @throws IllegalArgumentException if options is null * @deprecated * <p>Use {@link Util#makeZeroContainerCFABuilder(AnalysisOptions, IAnalysisCacheView, * IClassHierarchy)} */ @Deprecated public static SSAPropagationCallGraphBuilder makeZeroContainerCFABuilder( AnalysisOptions options, IAnalysisCacheView cache, IClassHierarchy cha, @SuppressWarnings("unused") AnalysisScope scope) { return makeZeroContainerCFABuilder(options, cache, cha); } /** * @param options options that govern call graph construction * @param cha governing class hierarchy * @return a 0-CFA Call Graph Builder augmented with extra logic for containers * @throws IllegalArgumentException if options is null */ public static SSAPropagationCallGraphBuilder makeZeroContainerCFABuilder( AnalysisOptions options, IAnalysisCacheView cache, IClassHierarchy cha) { if (options == null) { throw new IllegalArgumentException("options is null"); } addDefaultSelectors(options, cha); addDefaultBypassLogic(options, Util.class.getClassLoader(), cha); ContextSelector appSelector = null; SSAContextInterpreter appInterpreter = null; return new ZeroXContainerCFABuilder( cha, options, cache, appSelector, appInterpreter, ZeroXInstanceKeys.NONE); } /** * @param options options that govern call graph construction * @param cha governing class hierarchy * @param scope representation of the analysis scope * @return a 0-1-CFA Call Graph Builder augmented with extra logic for containers * @throws IllegalArgumentException if options is null * @deprecated * <p>Use {@link Util#makeZeroOneCFABuilder(Language, AnalysisOptions, IAnalysisCacheView, * IClassHierarchy)} */ @Deprecated public static SSAPropagationCallGraphBuilder makeZeroOneContainerCFABuilder( AnalysisOptions options, IAnalysisCacheView cache, IClassHierarchy cha, @SuppressWarnings("unused") AnalysisScope scope) { return makeZeroOneContainerCFABuilder(options, cache, cha); } /** * @deprecated * <p>Use {@link Util#makeZeroOneContainerCFABuilder(AnalysisOptions, IAnalysisCacheView, * IClassHierarchy, ContextSelector, SSAContextInterpreter)} */ @Deprecated public static SSAPropagationCallGraphBuilder makeZeroOneContainerCFABuilder( AnalysisOptions options, IAnalysisCacheView cache, IClassHierarchy cha, @SuppressWarnings("unused") AnalysisScope scope, ContextSelector appSelector, SSAContextInterpreter appInterpreter) { return makeZeroOneContainerCFABuilder(options, cache, cha, appSelector, appInterpreter); } /** * @param options options that govern call graph construction * @param cha governing class hierarchy * @return a 0-1-CFA Call Graph Builder augmented with extra logic for containers * @throws IllegalArgumentException if options is null */ public static SSAPropagationCallGraphBuilder makeZeroOneContainerCFABuilder( AnalysisOptions options, IAnalysisCacheView cache, IClassHierarchy cha) { return makeZeroOneContainerCFABuilder(options, cache, cha, null, null); } public static SSAPropagationCallGraphBuilder makeZeroOneContainerCFABuilder( AnalysisOptions options, IAnalysisCacheView cache, IClassHierarchy cha, ContextSelector appSelector, SSAContextInterpreter appInterpreter) { if (options == null) { throw new IllegalArgumentException("options is null"); } addDefaultSelectors(options, cha); addDefaultBypassLogic(options, Util.class.getClassLoader(), cha); return new ZeroXContainerCFABuilder( cha, options, cache, appSelector, appInterpreter, ZeroXInstanceKeys.ALLOCATIONS | ZeroXInstanceKeys.SMUSH_MANY | ZeroXInstanceKeys.SMUSH_PRIMITIVE_HOLDERS | ZeroXInstanceKeys.SMUSH_STRINGS | ZeroXInstanceKeys.SMUSH_THROWABLES); } /** * make a {@link CallGraphBuilder} that uses call-string context sensitivity, with call-string * length limited to n, and a context-sensitive allocation-site-based heap abstraction. * * @deprecated * <p>Use {@link Util#makeNCFABuilder(int, AnalysisOptions, * IAnalysisCacheView,IClassHierarchy)} */ @Deprecated public static SSAPropagationCallGraphBuilder makeNCFABuilder( int n, AnalysisOptions options, IAnalysisCacheView cache, IClassHierarchy cha, @SuppressWarnings("unused") AnalysisScope scope) { return makeNCFABuilder(n, options, cache, cha); } /** * make a {@link CallGraphBuilder} that uses call-string context sensitivity, with call-string * length limited to n, and a context-sensitive allocation-site-based heap abstraction. */ public static SSAPropagationCallGraphBuilder makeNCFABuilder( int n, AnalysisOptions options, IAnalysisCacheView cache, IClassHierarchy cha) { if (options == null) { throw new IllegalArgumentException("options is null"); } addDefaultSelectors(options, cha); addDefaultBypassLogic(options, Util.class.getClassLoader(), cha); ContextSelector appSelector = null; SSAContextInterpreter appInterpreter = null; SSAPropagationCallGraphBuilder result = new nCFABuilder( n, Language.JAVA.getFakeRootMethod(cha, options, cache), options, cache, appSelector, appInterpreter); // nCFABuilder uses type-based heap abstraction by default, but we want allocation sites result.setInstanceKeys( new ZeroXInstanceKeys( options, cha, result.getContextInterpreter(), ZeroXInstanceKeys.ALLOCATIONS | ZeroXInstanceKeys.SMUSH_MANY | ZeroXInstanceKeys.SMUSH_PRIMITIVE_HOLDERS | ZeroXInstanceKeys.SMUSH_STRINGS | ZeroXInstanceKeys.SMUSH_THROWABLES)); return result; } /** * make a {@link CallGraphBuilder} that uses object context sensitivity, with allocation-string * length limited to n * * @deprecated * <p>Use {@link Util#makeNObjBuilder(int, AnalysisOptions, IAnalysisCacheView, * IClassHierarchy)} */ @Deprecated public static SSAPropagationCallGraphBuilder makeNObjBuilder( int n, AnalysisOptions options, IAnalysisCacheView cache, IClassHierarchy cha, @SuppressWarnings("unused") AnalysisScope scope) { return makeNObjBuilder(n, options, cache, cha); } /** * make a {@link CallGraphBuilder} that uses object context sensitivity, with allocation-string * length limited to n */ public static SSAPropagationCallGraphBuilder makeNObjBuilder( int n, AnalysisOptions options, IAnalysisCacheView cache, IClassHierarchy cha) { if (options == null) { throw new IllegalArgumentException("options is null"); } addDefaultSelectors(options, cha); addDefaultBypassLogic(options, Util.class.getClassLoader(), cha); ContextSelector appSelector = null; SSAContextInterpreter appInterpreter = null; SSAPropagationCallGraphBuilder result = new nObjBuilder( n, cha, options, cache, appSelector, appInterpreter, ZeroXInstanceKeys.ALLOCATIONS | ZeroXInstanceKeys.SMUSH_MANY | ZeroXInstanceKeys.SMUSH_PRIMITIVE_HOLDERS | ZeroXInstanceKeys.SMUSH_STRINGS | ZeroXInstanceKeys.SMUSH_THROWABLES); return result; } /** * make a {@link CallGraphBuilder} that uses object context sensitivity, with allocation-string * length limited to n * * @deprecated * <p>Use {@link Util#makeVanillaNObjBuilder(int, AnalysisOptions, IAnalysisCacheView, * IClassHierarchy)} */ @Deprecated public static SSAPropagationCallGraphBuilder makeVanillaNObjBuilder( int n, AnalysisOptions options, IAnalysisCacheView cache, IClassHierarchy cha, @SuppressWarnings("unused") AnalysisScope scope) { return makeVanillaNCFABuilder(n, options, cache, cha); } /** * make a {@link CallGraphBuilder} that uses object context sensitivity, with allocation-string * length limited to n */ public static SSAPropagationCallGraphBuilder makeVanillaNObjBuilder( int n, AnalysisOptions options, IAnalysisCacheView cache, IClassHierarchy cha) { if (options == null) { throw new IllegalArgumentException("options is null"); } addDefaultSelectors(options, cha); addDefaultBypassLogic(options, Util.class.getClassLoader(), cha); ContextSelector appSelector = null; SSAContextInterpreter appInterpreter = null; SSAPropagationCallGraphBuilder result = new nObjBuilder( n, cha, options, cache, appSelector, appInterpreter, ZeroXInstanceKeys.ALLOCATIONS); return result; } /** * @deprecated * <p>Use {@link Util#makeVanillaNCFABuilder(int, AnalysisOptions, IAnalysisCacheView, * IClassHierarchy)} */ @Deprecated public static SSAPropagationCallGraphBuilder makeVanillaNCFABuilder( int n, AnalysisOptions options, IAnalysisCacheView cache, IClassHierarchy cha, @SuppressWarnings("unused") AnalysisScope scope) { return makeVanillaNCFABuilder(n, options, cache, cha); } /** * make a {@link CallGraphBuilder} that uses call-string context sensitivity, with call-string * length limited to n, and a context-sensitive allocation-site-based heap abstraction. Standard * optimizations in the heap abstraction like smushing of strings are disabled. */ public static SSAPropagationCallGraphBuilder makeVanillaNCFABuilder( int n, AnalysisOptions options, IAnalysisCacheView cache, IClassHierarchy cha) { if (options == null) { throw new IllegalArgumentException("options is null"); } addDefaultSelectors(options, cha); addDefaultBypassLogic(options, Util.class.getClassLoader(), cha); ContextSelector appSelector = null; SSAContextInterpreter appInterpreter = null; SSAPropagationCallGraphBuilder result = new nCFABuilder( n, Language.JAVA.getFakeRootMethod(cha, options, cache), options, cache, appSelector, appInterpreter); // nCFABuilder uses type-based heap abstraction by default, but we want allocation sites result.setInstanceKeys( new ZeroXInstanceKeys( options, cha, result.getContextInterpreter(), ZeroXInstanceKeys.ALLOCATIONS | ZeroXInstanceKeys.CONSTANT_SPECIFIC)); return result; } /** * @deprecated * <p>Use {@link Util#makeVanillaZeroOneContainerCFABuilder(AnalysisOptions, * IAnalysisCacheView, IClassHierarchy)} */ @Deprecated public static SSAPropagationCallGraphBuilder makeVanillaZeroOneContainerCFABuilder( AnalysisOptions options, IAnalysisCacheView cache, IClassHierarchy cha, @SuppressWarnings("unused") AnalysisScope scope) { return makeVanillaZeroOneContainerCFABuilder(options, cache, cha); } /** * @param options options that govern call graph construction * @param cha governing class hierarchy * @return a 0-1-CFA Call Graph Builder augmented with extra logic for containers * @throws IllegalArgumentException if options is null */ public static SSAPropagationCallGraphBuilder makeVanillaZeroOneContainerCFABuilder( AnalysisOptions options, IAnalysisCacheView cache, IClassHierarchy cha) { if (options == null) { throw new IllegalArgumentException("options is null"); } addDefaultSelectors(options, cha); addDefaultBypassLogic(options, Util.class.getClassLoader(), cha); ContextSelector appSelector = null; SSAContextInterpreter appInterpreter = null; options.setUseConstantSpecificKeys(true); return new ZeroXContainerCFABuilder( cha, options, cache, appSelector, appInterpreter, ZeroXInstanceKeys.ALLOCATIONS); } /** * @deprecated * <p>Use {@link Util#addDefaultBypassLogic(AnalysisOptions, ClassLoader, IClassHierarchy)} */ @Deprecated public static void addDefaultBypassLogic( AnalysisOptions options, @SuppressWarnings("unused") AnalysisScope scope, ClassLoader cl, IClassHierarchy cha) { addDefaultBypassLogic(options, cl, cha); } public static void addDefaultBypassLogic( AnalysisOptions options, ClassLoader cl, IClassHierarchy cha) { if (nativeSpec == null) return; if (cl.getResourceAsStream(nativeSpec) != null) { addBypassLogic(options, cl, nativeSpec, cha); } else { // try to load from filesystem try (final BufferedInputStream bIn = new BufferedInputStream(new FileInputStream(nativeSpec))) { XMLMethodSummaryReader reader = new XMLMethodSummaryReader(bIn, cha.getScope()); addBypassLogic(options, cl, reader, cha); } catch (FileNotFoundException e) { System.err.println("Could not load natives xml file from: " + nativeSpec); e.printStackTrace(); } catch (IOException e) { System.err.println("Could not close natives xml file " + nativeSpec); e.printStackTrace(); } } } }
38,265
35.758886
99
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/ipa/callgraph/propagation/AbstractFieldPointerKey.java
/* * Copyright (c) 2002 - 2006 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package com.ibm.wala.ipa.callgraph.propagation; /** Common implementation for {@link InstanceFieldPointerKey} implementations. */ public abstract class AbstractFieldPointerKey extends AbstractPointerKey implements InstanceFieldPointerKey { protected final InstanceKey instance; protected AbstractFieldPointerKey(InstanceKey container) { if (container == null) { throw new IllegalArgumentException("container is null"); } this.instance = container; } @Override public InstanceKey getInstanceKey() { return instance; } }
935
30.2
81
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/ipa/callgraph/propagation/AbstractLocalPointerKey.java
/* * Copyright (c) 2002 - 2006 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package com.ibm.wala.ipa.callgraph.propagation; import com.ibm.wala.ipa.callgraph.CGNode; /** A {@link PointerKey} representing a local variable must carry at least a {@link CGNode}. */ public abstract class AbstractLocalPointerKey extends AbstractPointerKey { public abstract CGNode getNode(); }
677
32.9
95
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/ipa/callgraph/propagation/AbstractPointerAnalysis.java
/* * Copyright (c) 2002 - 2006 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package com.ibm.wala.ipa.callgraph.propagation; import com.ibm.wala.analysis.pointers.BasicHeapGraph; import com.ibm.wala.analysis.pointers.HeapGraph; import com.ibm.wala.ipa.callgraph.CallGraph; import com.ibm.wala.util.intset.MutableMapping; import com.ibm.wala.util.intset.OrdinalSetMapping; import java.util.Collection; import java.util.Collections; /** Abstract superclass for {@link PointerAnalysis} implementations. */ public abstract class AbstractPointerAnalysis implements PointerAnalysis<InstanceKey> { /** graph representation of pointer-analysis results */ private HeapGraph<InstanceKey> heapGraph; /** Governing call graph. */ private final CallGraph cg; /** bijection from InstanceKey &lt;=&gt; Integer */ protected final MutableMapping<InstanceKey> instanceKeys; protected AbstractPointerAnalysis(CallGraph cg, MutableMapping<InstanceKey> instanceKeys) { this.cg = cg; this.instanceKeys = instanceKeys; } @Override public HeapGraph<InstanceKey> getHeapGraph() { if (heapGraph == null) { heapGraph = new BasicHeapGraph<>(this, cg); } return heapGraph; } protected CallGraph getCallGraph() { return cg; } @Override public Collection<InstanceKey> getInstanceKeys() { return Collections.unmodifiableCollection(instanceKeys.getObjects()); } @Override public OrdinalSetMapping<InstanceKey> getInstanceKeyMapping() { return instanceKeys; } }
1,811
29.711864
93
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/ipa/callgraph/propagation/AbstractPointerKey.java
/* * Copyright (c) 2002 - 2006 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package com.ibm.wala.ipa.callgraph.propagation; /** * This class exists to force {@link PointerKey} implementations to implement equals() and * hashCode()s. */ public abstract class AbstractPointerKey implements PointerKey { @Override public abstract boolean equals(Object obj); @Override public abstract int hashCode(); }
711
28.666667
90
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/ipa/callgraph/propagation/AbstractPointsToSolver.java
/* * Copyright (c) 2002 - 2006 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package com.ibm.wala.ipa.callgraph.propagation; import com.ibm.wala.util.CancelException; import com.ibm.wala.util.MonitorUtil.IProgressMonitor; /** Abstract base class for solver for pointer analysis. */ public abstract class AbstractPointsToSolver implements IPointsToSolver { protected static final boolean DEBUG = false; private final PropagationSystem system; private final PropagationCallGraphBuilder builder; private final ReflectionHandler reflectionHandler; public AbstractPointsToSolver(PropagationSystem system, PropagationCallGraphBuilder builder) { if (system == null) { throw new IllegalArgumentException("null system"); } this.system = system; this.builder = builder; this.reflectionHandler = new ReflectionHandler(builder); } @Override public abstract void solve(IProgressMonitor monitor) throws IllegalArgumentException, CancelException; protected PropagationCallGraphBuilder getBuilder() { return builder; } protected ReflectionHandler getReflectionHandler() { return reflectionHandler; } protected PropagationSystem getSystem() { return system; } }
1,526
28.365385
96
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/ipa/callgraph/propagation/AbstractTypeInNode.java
/* * Copyright (c) 2002 - 2006 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package com.ibm.wala.ipa.callgraph.propagation; import com.ibm.wala.analysis.reflection.InstanceKeyWithNode; import com.ibm.wala.classLoader.IClass; import com.ibm.wala.ipa.callgraph.CGNode; import com.ibm.wala.util.debug.Assertions; /** * Abstract base class for {@link InstanceKey} which represents at least some {@link IClass} in some * {@link CGNode}. */ public abstract class AbstractTypeInNode implements InstanceKeyWithNode { private final IClass type; private final CGNode node; public AbstractTypeInNode(CGNode node, IClass type) { if (node == null) { throw new IllegalArgumentException("null node"); } if (type != null && type.isInterface()) { Assertions.UNREACHABLE("unexpected type: " + type); } this.node = node; this.type = type; } @Override public abstract boolean equals(Object obj); @Override public abstract int hashCode(); @Override public abstract String toString(); /** @return the concrete type allocated */ @Override public IClass getConcreteType() { return type; } /** @return the call graph node which contains this allocation */ @Override public CGNode getNode() { return node; } }
1,575
25.711864
100
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/ipa/callgraph/propagation/AllocationSite.java
/* * Copyright (c) 2002 - 2006 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package com.ibm.wala.ipa.callgraph.propagation; import com.ibm.wala.classLoader.IClass; import com.ibm.wala.classLoader.IMethod; import com.ibm.wala.classLoader.NewSiteReference; import com.ibm.wala.ipa.callgraph.CGNode; import com.ibm.wala.ipa.callgraph.CallGraph; import com.ibm.wala.ipa.callgraph.Context; import com.ibm.wala.util.collections.FilterIterator; import com.ibm.wala.util.collections.MapIterator; import com.ibm.wala.util.collections.Pair; import java.util.Iterator; /** * An {@link InstanceKey} which represents a {@link NewSiteReference} in some {@link IMethod}. Note * that this differs from {@link AllocationSiteInNode}, which represents an allocation in a {@link * CGNode} that may carry some {@link Context}. This type is useful for a * context-<em>insensitive</em> heap abstraction. */ public class AllocationSite implements InstanceKey { private final NewSiteReference site; private final IMethod method; private final IClass concreteType; public AllocationSite(IMethod method, NewSiteReference allocation, IClass type) { this.site = allocation; this.method = method; this.concreteType = type; } @Override public String toString() { return "SITE{" + getMethod() + ':' + site + '}'; } public NewSiteReference getSite() { return site; } public IMethod getMethod() { return method; } @Override public IClass getConcreteType() { return concreteType; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((method == null) ? 0 : method.hashCode()); result = prime * result + ((site == null) ? 0 : site.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 AllocationSite other = (AllocationSite) obj; if (method == null) { if (other.method != null) return false; } else if (!method.equals(other.method)) return false; if (site == null) { if (other.site != null) return false; } else if (!site.equals(other.site)) return false; return true; } @Override public Iterator<Pair<CGNode, NewSiteReference>> getCreationSites(CallGraph CG) { return new MapIterator<>( new FilterIterator<>( CG.getNodes(method.getReference()).iterator(), o -> o.getMethod().equals(method)), object -> Pair.make(object, site)); } }
2,873
29.903226
99
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/ipa/callgraph/propagation/AllocationSiteInNode.java
/* * Copyright (c) 2002 - 2006 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package com.ibm.wala.ipa.callgraph.propagation; import com.ibm.wala.classLoader.IClass; import com.ibm.wala.classLoader.NewSiteReference; import com.ibm.wala.ipa.callgraph.CGNode; import com.ibm.wala.ipa.callgraph.CallGraph; import com.ibm.wala.util.collections.NonNullSingletonIterator; import com.ibm.wala.util.collections.Pair; import java.util.Iterator; /** An {@link InstanceKey} which represents a {@link NewSiteReference} in some {@link CGNode}. */ public abstract class AllocationSiteInNode extends AbstractTypeInNode { private final NewSiteReference site; public AllocationSiteInNode(CGNode node, NewSiteReference allocation, IClass type) { super(node, type); this.site = allocation; } @Override public abstract boolean equals(Object obj); @Override public abstract int hashCode(); @Override public String toString() { return "SITE_IN_NODE{" + getNode().getMethod() + ':' + getConcreteType().getName().toUnicodeString() + " in " + getNode().getContext() + '}'; } /** @return Returns the site. */ public NewSiteReference getSite() { return site; } @Override public Iterator<Pair<CGNode, NewSiteReference>> getCreationSites(CallGraph CG) { return new NonNullSingletonIterator<>(Pair.make(getNode(), getSite())); } }
1,706
28.947368
97
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/ipa/callgraph/propagation/AllocationSiteInNodeFactory.java
/* * Copyright (c) 2002 - 2006 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package com.ibm.wala.ipa.callgraph.propagation; import com.ibm.wala.classLoader.ArrayClass; import com.ibm.wala.classLoader.IClass; import com.ibm.wala.classLoader.IMethod; import com.ibm.wala.classLoader.NewSiteReference; import com.ibm.wala.classLoader.ProgramCounter; import com.ibm.wala.ipa.callgraph.AnalysisOptions; import com.ibm.wala.ipa.callgraph.CGNode; import com.ibm.wala.ipa.callgraph.propagation.cfa.CallerContext; import com.ibm.wala.ipa.callgraph.propagation.cfa.ContainerContextSelector; import com.ibm.wala.ipa.cha.IClassHierarchy; import com.ibm.wala.ssa.IR; import com.ibm.wala.ssa.SSANewInstruction; import com.ibm.wala.types.TypeReference; /** * A factory which tries by default to create {@link InstanceKey}s which are {@link * AllocationSiteInNode}s. * * <p>Notes: * * <ul> * <li>This class checks to avoid creating recursive contexts when {@link CGNode}s are based on * {@link ReceiverInstanceContext}, as in object-sensitivity. * <li>Up till recursion, this class will happily create unlimited object sensitivity, so be * careful. * <li>This class resorts to {@link ClassBasedInstanceKeys} for exceptions from PEIs and class * objects. * <li>This class consults the {@link AnalysisOptions} to determine whether to disambiguate * individual constants. * </ul> */ public class AllocationSiteInNodeFactory implements InstanceKeyFactory { /** Governing call graph construction options */ private final AnalysisOptions options; /** Governing class hierarchy */ private final IClassHierarchy cha; private final ClassBasedInstanceKeys classBased; /** @param options Governing call graph construction options */ public AllocationSiteInNodeFactory(AnalysisOptions options, IClassHierarchy cha) { this.options = options; this.cha = cha; this.classBased = new ClassBasedInstanceKeys(options, cha); } @Override public InstanceKey getInstanceKeyForAllocation(CGNode node, NewSiteReference allocation) { IClass type = options.getClassTargetSelector().getAllocatedTarget(node, allocation); if (type == null) { return null; } CGNode nodeToUse = node; // disallow recursion in contexts. if (node.getContext().isA(ReceiverInstanceContext.class) || node.getContext().isA(CallerContext.class)) { IMethod m = node.getMethod(); CGNode n = ContainerContextSelector.findNodeRecursiveMatchingContext(m, node.getContext()); if (n != null) { nodeToUse = n; } } if (type.isArrayClass()) { // special case for arrays with zero length in their first dimension IR ir = node.getIR(); SSANewInstruction newInstruction = ir.getNew(allocation); int lengthVN = newInstruction.getUse(0); if (ir.getSymbolTable().isIntegerConstant(lengthVN)) { Integer c = (Integer) ir.getSymbolTable().getConstantValue(lengthVN); if (c == 0) { if (options.getHandleZeroLengthArray()) { return new ZeroLengthArrayInNode(nodeToUse, allocation, type); } else { return new NormalAllocationInNode(nodeToUse, allocation, type); } } } } InstanceKey key = new NormalAllocationInNode(nodeToUse, allocation, type); return key; } @Override public InstanceKey getInstanceKeyForMultiNewArray( CGNode node, NewSiteReference allocation, int dim) { ArrayClass type = (ArrayClass) options.getClassTargetSelector().getAllocatedTarget(node, allocation); if (type == null) { return null; } InstanceKey key = new MultiNewArrayInNode(node, allocation, type, dim); return key; } @Override public <T> InstanceKey getInstanceKeyForConstant(TypeReference type, T S) { if (options.getUseConstantSpecificKeys()) { return new ConstantKey<>(S, cha.lookupClass(type)); } else { return new ConcreteTypeKey(cha.lookupClass(type)); } } @Override public InstanceKey getInstanceKeyForPEI(CGNode node, ProgramCounter pei, TypeReference type) { return classBased.getInstanceKeyForPEI(node, pei, type); } @Override public InstanceKey getInstanceKeyForMetadataObject(Object obj, TypeReference objType) { return classBased.getInstanceKeyForMetadataObject(obj, objType); } }
4,679
33.925373
97
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/ipa/callgraph/propagation/ArrayContentsKey.java
/* * Copyright (c) 2002 - 2006 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package com.ibm.wala.ipa.callgraph.propagation; import com.ibm.wala.classLoader.ArrayClass; /** A {@link PointerKey} which represents the contents of an array instance. */ public final class ArrayContentsKey extends AbstractFieldPointerKey implements FilteredPointerKey { public ArrayContentsKey(InstanceKey instance) { super(instance); } @Override public boolean equals(Object obj) { if (obj instanceof ArrayContentsKey) { ArrayContentsKey other = (ArrayContentsKey) obj; return instance.equals(other.instance); } else { return false; } } @Override public int hashCode() { return 1061 * instance.hashCode(); } @Override public String toString() { return "[" + instance + "[]]"; } @Override public TypeFilter getTypeFilter() { return new SingleClassFilter(((ArrayClass) instance.getConcreteType()).getElementClass()); } }
1,277
26.782609
99
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/ipa/callgraph/propagation/AssignEquation.java
/* * Copyright (c) 2002 - 2006 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package com.ibm.wala.ipa.callgraph.propagation; import com.ibm.wala.fixpoint.UnaryOperator; import com.ibm.wala.fixpoint.UnaryStatement; /** A specialized equation class introduced for efficiency. */ public final class AssignEquation extends UnaryStatement<PointsToSetVariable> { AssignEquation(PointsToSetVariable lhs, PointsToSetVariable rhs) { super(lhs, rhs); } @Override public UnaryOperator<PointsToSetVariable> getOperator() { return PropagationCallGraphBuilder.assignOperator; } @Override public boolean equals(Object o) { if (o instanceof AssignEquation) { AssignEquation other = (AssignEquation) o; return getLHS().equals(other.getLHS()) && getRightHandSide().equals(other.getRightHandSide()); } else { return false; } } }
1,167
29.736842
100
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/ipa/callgraph/propagation/AssignOperator.java
/* * Copyright (c) 2002 - 2006 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package com.ibm.wala.ipa.callgraph.propagation; import com.ibm.wala.fixpoint.UnaryOperator; import com.ibm.wala.fixpoint.UnaryStatement; /** * Corresponds to: "is a superset of". Used for assignment. * * <p>Unary op: &lt;lhs&gt;:= Assign(&lt;rhs&gt;) * * <p>(Technically, it's a binary op, since it includes lhs as an implicit input; this allows it to * compose with other ops that define the same lhs, so long as they're all Assign ops) */ class AssignOperator extends UnaryOperator<PointsToSetVariable> implements IPointerOperator { @Override public UnaryStatement<PointsToSetVariable> makeEquation( PointsToSetVariable lhs, PointsToSetVariable rhs) { return new AssignEquation(lhs, rhs); } @Override public byte evaluate(PointsToSetVariable lhs, PointsToSetVariable rhs) { if (PropagationCallGraphBuilder.DEBUG_ASSIGN) { String S = "EVAL Assign " + lhs.getPointerKey() + ' ' + rhs.getPointerKey(); S = S + "\nEVAL " + lhs + ' ' + rhs; System.err.println(S); } boolean changed = lhs.addAll(rhs); if (PropagationCallGraphBuilder.DEBUG_ASSIGN) { System.err.println("RESULT " + lhs + (changed ? " (changed)" : "")); } return changed ? CHANGED : NOT_CHANGED; } @Override public String toString() { return "Assign"; } @Override public int hashCode() { return 9883; } @Override public final boolean equals(Object o) { // this is a singleton return (this == o); } @Override public boolean isComplex() { return false; } }
1,922
26.869565
99
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/ipa/callgraph/propagation/CPAContextSelector.java
/* * Copyright (c) 2007 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package com.ibm.wala.ipa.callgraph.propagation; import com.ibm.wala.classLoader.CallSiteReference; import com.ibm.wala.classLoader.IMethod; import com.ibm.wala.ipa.callgraph.CGNode; import com.ibm.wala.ipa.callgraph.Context; import com.ibm.wala.ipa.callgraph.ContextSelector; import com.ibm.wala.util.intset.IntSet; import com.ibm.wala.util.intset.IntSetUtil; import com.ibm.wala.util.intset.MutableIntSet; public class CPAContextSelector implements ContextSelector { private final ContextSelector base; public CPAContextSelector(ContextSelector base) { this.base = base; } public static class CPAContext extends SelectiveCPAContext { public CPAContext(Context base, InstanceKey[] x) { super(base, x); } } @Override public Context getCalleeTarget( CGNode caller, CallSiteReference site, IMethod callee, InstanceKey[] actualParameters) { Context target = base.getCalleeTarget(caller, site, callee, actualParameters); if (actualParameters != null && actualParameters.length > 0) { return new CPAContext(target, actualParameters); } else { return target; } } private static boolean dispatchIndex(CallSiteReference ref, int i) { if (ref.isStatic()) { return !ref.getDeclaredTarget().getParameterType(i).isPrimitiveType(); } else { return i == 0 || !ref.getDeclaredTarget().getParameterType(i - 1).isPrimitiveType(); } } @Override public IntSet getRelevantParameters(CGNode caller, CallSiteReference site) { MutableIntSet s = IntSetUtil.make(); for (int i = 0; i < caller.getIR().getCalls(site)[0].getNumberOfUses(); i++) { if (!caller .getMethod() .getDeclaringClass() .getClassLoader() .getLanguage() .methodsHaveDeclaredParameterTypes() || dispatchIndex(site, i)) { s.add(i); } } return s; } }
2,287
30.342466
94
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/ipa/callgraph/propagation/ClassBasedInstanceKeys.java
/* * Copyright (c) 2002 - 2006 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package com.ibm.wala.ipa.callgraph.propagation; import com.ibm.wala.classLoader.ArrayClass; import com.ibm.wala.classLoader.IClass; import com.ibm.wala.classLoader.IMethod; import com.ibm.wala.classLoader.NewSiteReference; import com.ibm.wala.classLoader.ProgramCounter; import com.ibm.wala.ipa.callgraph.AnalysisOptions; import com.ibm.wala.ipa.callgraph.CGNode; import com.ibm.wala.ipa.cha.IClassHierarchy; import com.ibm.wala.types.Descriptor; import com.ibm.wala.types.MethodReference; import com.ibm.wala.types.TypeReference; import com.ibm.wala.util.debug.Assertions; /** * This class provides Instance Key call backs where each instance is in the same equivalence class * as all other instances of the same concrete type. */ public class ClassBasedInstanceKeys implements InstanceKeyFactory { private static final boolean DEBUG = false; private final AnalysisOptions options; private final IClassHierarchy cha; public ClassBasedInstanceKeys(AnalysisOptions options, IClassHierarchy cha) { if (cha == null) { throw new IllegalArgumentException("null cha"); } this.cha = cha; this.options = options; } @Override public InstanceKey getInstanceKeyForAllocation(CGNode node, NewSiteReference allocation) { if (allocation == null) { throw new IllegalArgumentException("allocation is null"); } if (String.valueOf(allocation).contains("java/lang/invoke/DirectMethodHandle$StaticAccessor")) { System.err.println("got " + allocation + " in " + node); } if (options.getClassTargetSelector() == null) { throw new IllegalStateException("options did not specify class target selector"); } IClass type = options.getClassTargetSelector().getAllocatedTarget(node, allocation); if (type == null) { return null; } ConcreteTypeKey key = new ConcreteTypeKey(type); return key; } /** * dim == 0 represents the first dimension, e.g., the [Object; instances in [[Object; e.g., the * [[Object; instances in [[[Object; * * <p>dim == 1 represents the second dimension, e.g., the [Object instances in [[[Object; */ @Override public InstanceKey getInstanceKeyForMultiNewArray( CGNode node, NewSiteReference allocation, int dim) { if (DEBUG) { System.err.println(("getInstanceKeyForMultiNewArray " + allocation + ' ' + dim)); } ArrayClass type = (ArrayClass) options.getClassTargetSelector().getAllocatedTarget(node, allocation); assert (type != null); if (DEBUG) { System.err.println(("type: " + type)); } assert type != null : "null type for " + allocation; int i = 0; while (i <= dim) { i++; if (type == null) { Assertions.UNREACHABLE(); } type = (ArrayClass) type.getElementClass(); if (DEBUG) { System.err.println(("intermediate: " + i + ' ' + type)); } } if (DEBUG) { System.err.println(("final type: " + type)); } if (type == null) { return null; } ConcreteTypeKey key = new ConcreteTypeKey(type); return key; } @Override public <T> InstanceKey getInstanceKeyForConstant(TypeReference type, T S) { if (type == null || cha.lookupClass(type) == null) { return null; } else { if (options.getUseConstantSpecificKeys()) { return new ConstantKey<>(S, cha.lookupClass(type)); } else { return new ConcreteTypeKey(cha.lookupClass(type)); } } } /** @return a set of ConcreteTypeKeys that represent the exceptions the PEI may throw. */ @Override public InstanceKey getInstanceKeyForPEI(CGNode node, ProgramCounter peiLoc, TypeReference type) { IClass klass = cha.lookupClass(type); if (klass == null) { return null; } return new ConcreteTypeKey(cha.lookupClass(type)); } @Override public InstanceKey getInstanceKeyForMetadataObject(Object obj, TypeReference objType) { IClass cls = cha.lookupClass(objType); assert cls != null : objType; if (obj instanceof TypeReference) { IClass klass = cha.lookupClass((TypeReference) obj); if (klass == null) { return new ConcreteTypeKey(cls); } else { // return the IClass itself, wrapped as a constant! return new ConstantKey<>(klass, cls); } } else if (obj instanceof MethodReference) { IMethod m = cha.resolveMethod((MethodReference) obj); if (m == null) { return new ConcreteTypeKey(cls); } else { return new ConstantKey<>(m, cls); } } else if (obj instanceof Descriptor) { return new ConstantKey<>((Descriptor) obj, cls); } else { // other cases throw new Error(); } } /** @return Returns the class hierarchy. */ public IClassHierarchy getClassHierarchy() { return cha; } }
5,207
30.373494
100
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/ipa/callgraph/propagation/CloneContextSelector.java
/* * Copyright (c) 2002 - 2006 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package com.ibm.wala.ipa.callgraph.propagation; import com.ibm.wala.analysis.reflection.CloneInterpreter; import com.ibm.wala.classLoader.CallSiteReference; import com.ibm.wala.classLoader.IMethod; import com.ibm.wala.ipa.callgraph.CGNode; import com.ibm.wala.ipa.callgraph.Context; import com.ibm.wala.ipa.callgraph.ContextSelector; import com.ibm.wala.ipa.cha.IClassHierarchy; import com.ibm.wala.util.intset.EmptyIntSet; import com.ibm.wala.util.intset.IntSet; /** * This context selector selects a context based on the concrete type of the receiver to a call of * java.lang.Object.clone */ public class CloneContextSelector implements ContextSelector { private final ReceiverTypeContextSelector selector; private final IClassHierarchy cha; public CloneContextSelector(IClassHierarchy cha) { this.selector = new ReceiverTypeContextSelector(); this.cha = cha; } @Override public Context getCalleeTarget( CGNode caller, CallSiteReference site, IMethod callee, InstanceKey[] receiver) { if (receiver == null) { return null; } if (callee.getReference().equals(CloneInterpreter.CLONE)) { return selector.getCalleeTarget(caller, site, callee, receiver); } else { return null; } } @Override public IntSet getRelevantParameters(CGNode caller, CallSiteReference site) { IMethod declaredTarget = cha.resolveMethod(site.getDeclaredTarget()); if (declaredTarget != null && declaredTarget.getReference().equals(CloneInterpreter.CLONE)) { return selector.getRelevantParameters(caller, site); } else { return EmptyIntSet.instance; } } }
2,010
31.967213
98
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/ipa/callgraph/propagation/ConcreteTypeKey.java
/* * Copyright (c) 2002 - 2006 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package com.ibm.wala.ipa.callgraph.propagation; import com.ibm.wala.classLoader.IClass; import com.ibm.wala.classLoader.NewSiteReference; import com.ibm.wala.ipa.callgraph.CGNode; import com.ibm.wala.ipa.callgraph.CallGraph; import com.ibm.wala.ipa.cha.IClassHierarchy; import com.ibm.wala.ssa.SSAInstruction; import com.ibm.wala.types.TypeReference; import com.ibm.wala.util.collections.ComposedIterator; import com.ibm.wala.util.collections.FilterIterator; import com.ibm.wala.util.collections.MapIterator; import com.ibm.wala.util.collections.Pair; import com.ibm.wala.util.debug.Assertions; import java.util.Collection; import java.util.Iterator; /** An instance key which represents a unique set for each concrete type. */ public final class ConcreteTypeKey implements InstanceKey { private final IClass type; public ConcreteTypeKey(IClass type) { if (type == null) { throw new IllegalArgumentException("type is null"); } if (type.isInterface()) { Assertions.UNREACHABLE("unexpected interface: " + type); } this.type = type; } @Override public boolean equals(Object obj) { if (obj instanceof ConcreteTypeKey) { ConcreteTypeKey other = (ConcreteTypeKey) obj; return type.equals(other.type); } else { return false; } } @Override public int hashCode() { return 461 * type.hashCode(); } @Override public String toString() { return "[" + type + ']'; } public IClass getType() { return type; } @Override public IClass getConcreteType() { return type; } /** * @param pei a PEI instruction * @param cha governing class hierarchy * @return a set of ConcreteTypeKeys that represent the exceptions the PEI may throw. * @throws IllegalArgumentException if pei is null */ public static InstanceKey[] getInstanceKeysForPEI(SSAInstruction pei, IClassHierarchy cha) { if (pei == null) { throw new IllegalArgumentException("pei is null"); } Collection<TypeReference> types = pei.getExceptionTypes(); // TODO: institute a cache? if (types == null) { return null; } InstanceKey[] result = new InstanceKey[types.size()]; int i = 0; for (TypeReference type : types) { assert type != null; IClass klass = cha.lookupClass(type); result[i++] = new ConcreteTypeKey(klass); } return result; } @Override public Iterator<Pair<CGNode, NewSiteReference>> getCreationSites(CallGraph CG) { return new ComposedIterator<>(CG.iterator()) { @Override public Iterator<? extends Pair<CGNode, NewSiteReference>> makeInner(final CGNode outer) { return new MapIterator<>( new FilterIterator<>( outer.iterateNewSites(), o -> o.getDeclaredType().equals(type.getReference())), object -> Pair.make(outer, object)); } }; } }
3,256
28.880734
95
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/ipa/callgraph/propagation/ConstantKey.java
/* * Copyright (c) 2002 - 2006 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package com.ibm.wala.ipa.callgraph.propagation; import com.ibm.wala.classLoader.IClass; import com.ibm.wala.classLoader.NewSiteReference; import com.ibm.wala.ipa.callgraph.CGNode; import com.ibm.wala.ipa.callgraph.CallGraph; import com.ibm.wala.util.collections.EmptyIterator; import com.ibm.wala.util.collections.Pair; import java.util.Iterator; import java.util.Objects; /** An instance key which represents a unique, constant object. */ public final class ConstantKey<T> implements InstanceKey { private final T value; private final IClass valueClass; public ConstantKey(T value, IClass valueClass) { this.value = value; this.valueClass = valueClass; assert valueClass != null; } @Override public boolean equals(Object obj) { if (obj instanceof ConstantKey) { ConstantKey<?> other = (ConstantKey<?>) obj; return valueClass.equals(other.valueClass) ? Objects.equals(value, other.value) : false; } else { return false; } } @Override public int hashCode() { return value == null ? 65535 : 1877 * value.hashCode(); } @Override public String toString() { if (value == null) return "[ConstantKey:null]"; else return "[ConstantKey:" + value + ':' + valueClass.getReference() + ']'; } @Override public IClass getConcreteType() { return valueClass; } public T getValue() { return value; } @Override public Iterator<Pair<CGNode, NewSiteReference>> getCreationSites(CallGraph CG) { return EmptyIterator.instance(); } }
1,904
26.608696
94
java
WALA
WALA-master/core/src/main/java/com/ibm/wala/ipa/callgraph/propagation/ContainerUtil.java
/* * Copyright (c) 2002 - 2006 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package com.ibm.wala.ipa.callgraph.propagation; import com.ibm.wala.classLoader.ArrayClass; import com.ibm.wala.classLoader.IClass; import com.ibm.wala.types.ClassLoaderReference; import com.ibm.wala.types.TypeName; import com.ibm.wala.types.TypeReference; import com.ibm.wala.util.collections.HashSetFactory; import java.util.Collection; /** Utilities for container class analysis */ public class ContainerUtil { private static final TypeName FreezableListName = TypeName.string2TypeName("Lcom/sun/corba/se/internal/ior/FreezableList"); public static final TypeReference FreezableList = TypeReference.findOrCreate(ClassLoaderReference.Primordial, FreezableListName); private static final TypeName JarAttributesName = TypeName.string2TypeName("Ljava/util/jar/Attributes"); public static final TypeReference JarAttributes = TypeReference.findOrCreate(ClassLoaderReference.Primordial, JarAttributesName); private static final Collection<TypeReference> miscContainers = HashSetFactory.make(); static { miscContainers.add(FreezableList); miscContainers.add(JarAttributes); } /** * @return true iff C is a container class from java.util * @throws IllegalArgumentException if C is null */ public static boolean isContainer(IClass c) { if (c == null) { throw new IllegalArgumentException("c is null"); } if (ClassLoaderReference.Primordial.equals(c.getClassLoader().getReference()) && TypeReference.JavaUtilCollection.getName() .getPackage() .equals(c.getReference().getName().getPackage())) { IClass collection = c.getClassHierarchy().lookupClass(TypeReference.JavaUtilCollection); IClass map = c.getClassHierarchy().lookupClass(TypeReference.JavaUtilMap); if (c.isInterface()) { assert collection != null; assert map != null; Collection<IClass> s; s = c.getAllImplementedInterfaces(); if (s.contains(collection) || s.contains(map)) { return true; } } else { if (c.getClassHierarchy().implementsInterface(c, collection) || c.getClassHierarchy().implementsInterface(c, map)) { return true; } } } if (miscContainers.contains(c.getReference())) { return true; } if (c.isArrayClass() && ((ArrayClass) c).getElementClass() != null && ((ArrayClass) c).getElementClass().getReference().isReferenceType()) { return true; } return false; } }
2,901
33.547619
94
java