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/dalvik/src/main/java/com/ibm/wala/dalvik/ipa/callgraph/propagation/cfa/AndroidContext.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 under the terms listed below. * */ /* * Copyright (c) 2013, * Tobias Blaschke <code@tobiasblaschke.de> * All rights reserved. * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The names of the contributors may not be used to endorse or promote * products derived from this software without specific prior written * permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ package com.ibm.wala.dalvik.ipa.callgraph.propagation.cfa; import com.ibm.wala.dalvik.util.AndroidTypes; import com.ibm.wala.ipa.callgraph.Context; import com.ibm.wala.ipa.callgraph.ContextItem; import com.ibm.wala.ipa.callgraph.ContextKey; /** * Fetches an android/content/Context. * * @author Tobias Blaschke &lt;code@tobiasblaschke.de&gt; * @since 2013-10-14 */ public class AndroidContext implements Context { /** Key into the Context that represents the AndroidContext. */ public static final ContextKey ANDROID_CONTEXT_KEY = new ContextKey() {}; private final AndroidTypes.AndroidContextType aCtxT; private final Context parent; public AndroidContext(Context parent, AndroidTypes.AndroidContextType aCtxT) { this.parent = parent; this.aCtxT = aCtxT; } public AndroidTypes.AndroidContextType getContextType() { return this.aCtxT; } /** * Looks up a ContextKey in the Context. * * @return an Intent or parent-managed object. * @throws IllegalArgumentException if the name is null. */ @Override public ContextItem get(ContextKey name) { if (name == null) { throw new IllegalArgumentException("name is null"); } if (name.equals(ANDROID_CONTEXT_KEY)) { return null; // TODO } else if (this.parent != null) { return this.parent.get(name); } else { return null; } } /** Special equality: Object may be equal to an object without associated Intent. */ @Override public boolean equals(Object obj) { if (obj == null) { return false; } if (obj instanceof AndroidContext) { AndroidContext other = (AndroidContext) obj; if (this.aCtxT.equals(other.aCtxT)) { if (this.parent != null) { return this.parent.equals(other.parent); } else { return other.parent == null; } } else { return false; } } else { if (this.parent != null) { // TODO: do we really want this? return this.parent.equals(obj); } else { return false; } } } @Override public int hashCode() { // TODO: do we want to "clash" with the parent here? return 71891 * this.aCtxT.hashCode(); } @Override public String toString() { if (this.parent == null) { return "AndroidContext: " + this.aCtxT; } else { return "AndroidContext: " + this.aCtxT + ", parent: " + this.parent; } } }
4,323
31.757576
86
java
WALA
WALA-master/dalvik/src/main/java/com/ibm/wala/dalvik/ipa/callgraph/propagation/cfa/Intent.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 under the terms listed below. * */ /* * Copyright (c) 2013, * Tobias Blaschke <code@tobiasblaschke.de> * All rights reserved. * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The names of the contributors may not be used to endorse or promote * products derived from this software without specific prior written * permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ package com.ibm.wala.dalvik.ipa.callgraph.propagation.cfa; import com.ibm.wala.core.util.strings.Atom; import com.ibm.wala.dalvik.util.AndroidComponent; import com.ibm.wala.dalvik.util.AndroidEntryPointManager; import com.ibm.wala.ipa.callgraph.ContextItem; import com.ibm.wala.ipa.callgraph.ContextKey; import com.ibm.wala.types.TypeName; /** * Determines the target of an Android-Intent. * * <p>An Intent is generated at each Constructor-Call of an Android-Intent. Information to that * Constructor is added as target. * * <p>If you want to change the target don't change this Object! Instead place an override using the * AndroidEntryPointManager so no information is lost. * * <p>Upon the creation of an Intent it's target-type almost always points to UNKNOWN. Again change * this using an override. * * <p>This class contains functions that determine the target-type on the Intent itself. They are * intended as fallback only. * * <p>CAUTION: If you inherit from this class - keep hashCodes and equals clashing! * * @see com.ibm.wala.dalvik.util.AndroidEntryPointManager * @see com.ibm.wala.dalvik.ipa.callgraph.propagation.cfa.IntentContextSelector * @see com.ibm.wala.dalvik.ipa.callgraph.propagation.cfa.IntentContextInterpreter * @author Tobias Blaschke &lt;code@tobiasblaschke.de&gt; * @since 2013-10-12 */ public class Intent implements ContextItem, Comparable<Intent> { /** Key into the Context that represents the Intent. */ public static final ContextKey INTENT_KEY = new ContextKey() {}; public enum IntentType { /** The target could not be Identified for sure */ UNKNOWN_TARGET, /** The Class the Intent Action refers to belongs to this App */ INTERNAL_TARGET, /** The Class the Intent Action refers to belongs to an external App */ EXTERNAL_TARGET, /** The Action is a Constant defined on the Android-Reference Manual */ STANDARD_ACTION, SYSTEM_SERVICE, /** So External and maybe internal */ BROADCAST, /** Do not handle intent */ IGNORE } private enum Explicit { UNSET, IMPLICIT, EXPLICIT, /** An other target was set for an explicit Intent */ MULTI } public static final Atom UNBOUND = Atom.findOrCreateAsciiAtom("Unbound"); private Atom action; public Atom uri; private IntentType type; private Explicit explicit = Explicit.UNSET; private AndroidComponent targetCompontent; // Activity, Service, ... private boolean immutable = false; public Intent() { this.action = null; } public Intent(String action) { this(Atom.findOrCreateAsciiAtom(action)); } public Intent(Atom action) { this(action, null); } public Intent(Atom action, Atom uri) { this.action = action; this.uri = uri; this.type = null; // Delay computation upon it's need this.targetCompontent = null; } public Intent(TypeName action, Atom uri) { this(Atom.findOrCreateAsciiAtom(action.toString()), uri); } public Intent(TypeName action) { this(action, null); } public void setExplicit() { switch (explicit) { case UNSET: // TODO: This is dangerous? explicit = Explicit.EXPLICIT; break; case EXPLICIT: unbind(); break; default: throw new UnsupportedOperationException( String.format("unexpected explicitness setting %s", explicit)); } } public boolean isExplicit() { return explicit == Explicit.EXPLICIT; } public void setImmutable() { this.immutable = true; } @Override public Intent clone() { final Intent clone = new Intent(); clone.action = this.action; // OK here? clone.uri = this.uri; clone.type = this.type; clone.explicit = this.explicit; clone.targetCompontent = this.targetCompontent; return clone; } /** * Set the explicit target of the intent. * * <p>If setAction is called multible times on an Intent it becomes UNBOUND. */ public void setActionExplicit(Atom action) { if (action == null) { throw new IllegalArgumentException("Action may not be null!"); } if (this.action == null) { assert (this.explicit == Explicit.UNSET) : "No Action but Intent is not UNSET - is " + this.explicit; assert !immutable : "Intent was marked immutable - can't change it."; this.action = action; this.explicit = Explicit.EXPLICIT; } else if (isExplicit() && !this.action.equals(action)) { // We already have the explicit target. Ignore the change. unbind(); } else if (!isExplicit()) { assert !immutable : "Intent was marked immutable - can't change it."; this.action = action; this.explicit = Explicit.EXPLICIT; // TODO: Set type? } else { // Set to same values - OK } } public void unbind() { assert !immutable : "Intent was marked immutable - can't change it."; this.action = UNBOUND; this.type = IntentType.UNKNOWN_TARGET; this.explicit = Explicit.MULTI; // XXX shoulb we do this? } /** * Set the target of the intent. * * <p>If setAction is called multible times on an Intent it becomes UNBOUND. */ public void setAction(Atom action) { if (this.action == null) { assert !immutable : "Intent was marked immutable - can't change it."; this.action = action; } else if (isExplicit()) { // We already have the explicit target. Ignore the change. } else if (!action.equals(this.action)) { unbind(); } } public Atom getAction() { if (this.action == null) { assert !isExplicit() : "Beeing explicit implies having an action!"; return UNBOUND; } return this.action; } public IntentType getType() { if (this.type != null) { return this.type; } else { if (isSystemService(this)) { this.type = IntentType.SYSTEM_SERVICE; } else if (isStandardAction(this)) { this.type = IntentType.STANDARD_ACTION; } else if (isInternal(this)) { this.type = IntentType.INTERNAL_TARGET; } else if (isExternal(this)) { this.type = IntentType.EXTERNAL_TARGET; } else { this.type = IntentType.UNKNOWN_TARGET; } } return this.type; } /** * Return the type of Component associated with this Intent. * * <p>May return null (especially on an UNKNOWN target). The IntentContextInterpreter uses the * IntentStarters.StartInfo to determine the Target. However it is nicer to set the Component * here. * * <p>TODO: Set the Component somewhere */ public AndroidComponent getComponent() { return this.targetCompontent; } private static boolean isSystemService(Intent intent) { assert (intent.action != null); return (intent.action.getVal(0) != 'L') && (intent.action.rIndex((byte) '/') < 0) && (intent.action.rIndex((byte) '.') < 0); } /** * Fallback: tries to determine on the Intent itself if it's internal. * * <p>Use {@link #isInternal(boolean)} instead. * * <p>Recomputes if the Intent is internal. TODO: * * @param intent TODO: Implement it ;) TODO: What to return if it does not, but * Summary-Information is available? TODO: We should read in the Manifest.xml rather than * relying on the packet name! */ private static boolean isInternal( @SuppressWarnings("unused") Intent intent) { // XXX: This may loop forever! /*final Intent override = AndroidEntryPointManager.MANAGER.getIntent(intent); logger.warn("Intent.isInternal(Intent) is an unsafe fallback!"); if (override.getType() != IntentType.UNKNOWN_TARGET) { return override.isInternal(true); // The isInternal defined later not this one! }*/ return false; } /** * Fallback: tries to determine on the Intent itself if it's external. * * <p>Use {@link #isExternal(boolean)} instead. */ private static boolean isExternal(Intent intent) { // XXX: This may loop forever! /*final Intent override = AndroidEntryPointManager.MANAGER.getIntent(intent); logger.warn("Intent.isExternal(Intent) is an unsafe fallback!"); if (override.getType() != IntentType.UNKNOWN_TARGET) { return override.isExternal(true); // The isExternal defined later not this one! }*/ if ((intent.action == null) || intent.action.equals(UNBOUND)) { return false; // Is Unknown } String pack = AndroidEntryPointManager.MANAGER.guessPackage(); if (pack == null) { // Unknown so not selected as external return false; } return !(intent.action.toString().startsWith('L' + pack) || intent.action.toString().startsWith(pack)); } /** Fallback: tries to determine on the Intent itself if it's a standard action. */ private static boolean isStandardAction(Intent intent) { // TODO: This may loop forever! /*final Intent override = AndroidEntryPointManager.MANAGER.getIntent(intent); logger.warn("Intent.isStandardAction(Intent) is an unsafe fallback!"); if (override.getType() != IntentType.UNKNOWN_TARGET) { return override.isStandard(true); }*/ if ((intent.action == null) || intent.action.equals(UNBOUND)) { return false; // Is Unknown } // TODO: Make this static or so final Atom andoidIntentAction = Atom.findOrCreateAsciiAtom("Landroid/intent/action"); return intent.action.startsWith(andoidIntentAction); } /** * Is the Intents target internally resolvable. * * @return if the Intent is associated to a class in the analyzed application. * @param strict if false return unknown target as internal */ public boolean isInternal(boolean strict) { IntentType type = getType(); // Asserts type is computed return ((type == IntentType.INTERNAL_TARGET) || (!strict && (type == IntentType.UNKNOWN_TARGET))); } /** * Has the target to be resolved by an external App. * * <p>The Intent is not associated to a class in this application or it's a Standard action * defined in the Android Reference Manual. * * @param strict if false return unknown target as external */ public boolean isExternal(boolean strict) { IntentType type = getType(); // Asserts type is computed return ((type == IntentType.EXTERNAL_TARGET) || (type == IntentType.STANDARD_ACTION) || (!strict && (type == IntentType.UNKNOWN_TARGET))); } /** * Is the Intent one of the System-Defined ones. * * <p>It's a Standard action defined in the Android Reference Manual. Implies isExternal. * * @param strict if false return unknown target as standard */ public boolean isStandard(boolean strict) { IntentType type = getType(); // Asserts type is computed return ((type == IntentType.STANDARD_ACTION) || (!strict && (type == IntentType.UNKNOWN_TARGET))); } @Override public String toString() { StringBuilder ret; if ((this.action == null) || this.action.equals(UNBOUND)) { return "Unbound Intent"; } else if (getType() == IntentType.SYSTEM_SERVICE) { ret = new StringBuilder("SystemService("); } else { ret = new StringBuilder("Intent("); } ret.append(this.action.toString()); if (uri != null) { ret.append(", "); ret.append(this.uri); } ret.append(") of type "); ret.append(getType()); return ret.toString(); } /** * CLASHES: Does not consider intent-type. * * <p>This clash is however intended: This aids in resolving the override of an Intent. The * AndroidEntryPointManager generates new Intent Objects. Instead of searching all overrides we * get it for free. */ @Override public int hashCode() { // DO NOT USE TYPE! if (this.uri != null) { return getAction().hashCode() * this.uri.hashCode(); } else { return getAction().hashCode(); } } /** Does not consider the associated URI. */ public boolean equalAction(Intent other) { return getAction().equals(other.getAction()); } /** * Intents are equal to Intents with other type. * * <p>This clash is however intended: This aids in resolving the override of an Intent. The * AndroidEntryPointManager generates new Intent Objects. Instead of searching all overrides we * get it for free. */ @Override public boolean equals(Object o) { if (o instanceof Intent) { Intent other = (Intent) o; // DO NOT USE TYPE! if (this.uri != null) { return (this.uri.equals(other.uri) && equalAction(other)); // && (this.explicit == other.explicit)); } else { return ((other.uri == null) && equalAction(other)); // && (this.explicit == other.explicit)) ; } } else { System.err.println("WARNING: Can't compare Intent to " + o.getClass()); return false; } } public Intent resolve() { return AndroidEntryPointManager.MANAGER.getIntent(this); } @Override public int compareTo(Intent other) { return getAction().toString().compareTo(other.getAction().toString()); } }
15,005
31.480519
100
java
WALA
WALA-master/dalvik/src/main/java/com/ibm/wala/dalvik/ipa/callgraph/propagation/cfa/IntentContext.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 under the terms listed below. * */ /* * Copyright (c) 2013, * Tobias Blaschke <code@tobiasblaschke.de> * All rights reserved. * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The names of the contributors may not be used to endorse or promote * products derived from this software without specific prior written * permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ package com.ibm.wala.dalvik.ipa.callgraph.propagation.cfa; import com.ibm.wala.ipa.callgraph.Context; import com.ibm.wala.ipa.callgraph.ContextItem; import com.ibm.wala.ipa.callgraph.ContextKey; /** * Wraps an Intent to be suitable to be a Context-Element. * * <p>This class takes a parent so we don't loose information by overwriting. * * @author Tobias Blaschke &lt;code@tobiasblaschke.de&gt; * @since 2013-10-14 */ public class IntentContext implements Context { /** Key into the Context that represents the Intent. */ public static final ContextKey INTENT_KEY = Intent.INTENT_KEY; private final Intent intent; private final Context parent; public IntentContext(Intent intent) { this(null, intent); } public IntentContext(Context parent, Intent intent) { this.parent = parent; this.intent = intent; } /** * Looks up a ContextKey in the Context. * * @return an Intent or parent-managed object. * @throws IllegalArgumentException if the name is null. */ @Override public ContextItem get(ContextKey name) { if (name == null) { throw new IllegalArgumentException("name is null"); } if (name.equals(INTENT_KEY)) { return intent; } else if (this.parent != null) { return this.parent.get(name); } else { return null; } } /** Special equality: Object may be equal to an object without associated Intent. */ @Override public boolean equals(Object obj) { if (obj == null) { return false; } if (obj instanceof IntentContext) { IntentContext other = (IntentContext) obj; if (this.intent.equals(other.intent)) { if (this.parent != null) { return this.parent.equals(other.parent); } else { return other.parent == null; } } else { return false; } } else { if (this.parent != null) { // TODO: do we really want this? return this.parent.equals(obj); } else { return false; } } } @Override public int hashCode() { // TODO: do we want to "clash" with the parent here? return 71891 * intent.hashCode(); } @Override public String toString() { if (this.parent == null) { return "Intent: " + this.intent; } else { return "Intent: " + this.intent + ", parent: " + this.parent; } } public Intent getIntent() { return this.intent; } }
4,317
30.518248
86
java
WALA
WALA-master/dalvik/src/main/java/com/ibm/wala/dalvik/ipa/callgraph/propagation/cfa/IntentContextInterpreter.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 under the terms listed below. * */ /* * Copyright (c) 2013, * Tobias Blaschke <code@tobiasblaschke.de> * All rights reserved. * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The names of the contributors may not be used to endorse or promote * products derived from this software without specific prior written * permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ package com.ibm.wala.dalvik.ipa.callgraph.propagation.cfa; import com.ibm.wala.cfg.ControlFlowGraph; import com.ibm.wala.classLoader.CallSiteReference; import com.ibm.wala.classLoader.CodeScanner; import com.ibm.wala.classLoader.IClass; import com.ibm.wala.classLoader.IMethod; import com.ibm.wala.classLoader.NewSiteReference; import com.ibm.wala.dalvik.ipa.callgraph.androidModel.AndroidModel; import com.ibm.wala.dalvik.ipa.callgraph.androidModel.MicroModel; import com.ibm.wala.dalvik.ipa.callgraph.androidModel.stubs.ExternalModel; import com.ibm.wala.dalvik.ipa.callgraph.androidModel.stubs.SystemServiceModel; import com.ibm.wala.dalvik.ipa.callgraph.androidModel.stubs.UnknownTargetModel; import com.ibm.wala.dalvik.util.AndroidComponent; import com.ibm.wala.dalvik.util.AndroidEntryPointManager; 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.ContextKey; import com.ibm.wala.ipa.callgraph.IAnalysisCacheView; import com.ibm.wala.ipa.callgraph.propagation.AbstractTypeInNode; import com.ibm.wala.ipa.callgraph.propagation.SSAContextInterpreter; import com.ibm.wala.ipa.cha.IClassHierarchy; import com.ibm.wala.ipa.summaries.SummarizedMethod; import com.ibm.wala.ssa.DefUse; import com.ibm.wala.ssa.IR; import com.ibm.wala.ssa.IRView; import com.ibm.wala.ssa.ISSABasicBlock; import com.ibm.wala.ssa.SSAInstruction; import com.ibm.wala.types.FieldReference; import com.ibm.wala.types.MethodReference; import com.ibm.wala.types.TypeReference; import com.ibm.wala.util.CancelException; import java.util.EnumSet; import java.util.Iterator; import java.util.Set; /** * An {@link SSAContextInterpreter} that redirects functions that start Android-Components. * * <p>The Starter-Functions (listed in IntentStarters) are replaced by a Model that emulates Android * Lifecycle based on their Target (Internal, External, ...): A wrapper around the single models is * generated dynamically (by the models themselves) to resemble the signature of the replaced * function. * * <p>Methods are replacement by generating a adapted Intermediate Representation of this function * on every occurrence of a call to it. * * @see com.ibm.wala.dalvik.ipa.callgraph.propagation.cfa.IntentContextSelector * @see com.ibm.wala.dalvik.ipa.callgraph.propagation.cfa.IntentStarters * @see com.ibm.wala.dalvik.ipa.callgraph.androidModel.MicroModel * @see com.ibm.wala.dalvik.ipa.callgraph.androidModel.stubs.ExternalModel * @author Tobias Blaschke &lt;code@tobiasblaschke.de&gt; * @since 2013-10-14 */ public class IntentContextInterpreter implements SSAContextInterpreter { private final IntentStarters intentStarters; private final IClassHierarchy cha; private final AnalysisOptions options; private final IAnalysisCacheView cache; public IntentContextInterpreter( IClassHierarchy cha, final AnalysisOptions options, final IAnalysisCacheView cache) { this.cha = cha; this.options = options; this.cache = cache; this.intentStarters = new IntentStarters(cha); } /** Read possible targets of the intents Infos. */ private AndroidComponent fetchTargetComponent(final Intent intent, final IMethod method) { assert (method != null); assert (intentStarters.getInfo(method.getReference()) != null) : "No IntentStarter for Method " + method + ' ' + intent; if (intent.getComponent() != null) { return intent.getComponent(); } else if (intent.getType() == Intent.IntentType.SYSTEM_SERVICE) { return AndroidComponent.UNKNOWN; } else { final Set<AndroidComponent> possibleTargets = intentStarters.getInfo(method.getReference()).getComponentsPossible(); if (possibleTargets.size() == 1) { final Iterator<AndroidComponent> it = possibleTargets.iterator(); return it.next(); } else { // TODO: Go interactive and ask user? final Iterator<AndroidComponent> it = possibleTargets.iterator(); final AndroidComponent targetComponent = it.next(); return targetComponent; } } } private static TypeReference getCaller(final Context ctx, final CGNode node) { if (ctx.get(ContextKey.CALLER) != null) { System.out.println("CALLER CONTEXT" + ctx.get(ContextKey.CALLER)); return node.getMethod().getReference().getDeclaringClass(); } else if (ctx.get(ContextKey.CALLSITE) != null) { System.out.println("CALLSITE CONTEXT" + ctx.get(ContextKey.CALLSITE)); return node.getMethod().getReference().getDeclaringClass(); } else if (ctx.get(ContextKey.RECEIVER) != null) { final AbstractTypeInNode aType = (AbstractTypeInNode) ctx.get(ContextKey.RECEIVER); return aType.getConcreteType().getReference(); } else { return node.getMethod() .getReference() .getDeclaringClass(); // TODO: This may not necessarily fit! } } /** * Generates an adapted IR of the managed functions on each call. * * @param node The function to create the IR of * @throws IllegalArgumentException on a node of null */ @Override public IR getIR(CGNode node) { if (node == null) { throw new IllegalArgumentException("node is null"); } assert understands(node); // Should already have been checked before { // TODO: CACHE! final Context ctx = node.getContext(); final TypeReference callingClass = getCaller(ctx, node); if (ctx.get(Intent.INTENT_KEY) != null) { try { // Translate CancelException to IllegalStateException final Intent inIntent = (Intent) ctx.get(Intent.INTENT_KEY); // Intent without overrides final Intent intent = AndroidEntryPointManager.MANAGER.getIntent(inIntent); // Apply overrides final IMethod method = node.getMethod(); final AndroidModel model; final IntentStarters.StartInfo info; Intent.IntentType type = intent.getType(); if (intent.getAction().equals(Intent.UNBOUND)) { type = Intent.IntentType.UNKNOWN_TARGET; } { // Fetch model and info switch (type) { case INTERNAL_TARGET: info = intentStarters.getInfo(method.getReference()); model = new MicroModel(this.cha, this.options, this.cache, intent.getAction()); break; case SYSTEM_SERVICE: info = new IntentStarters.StartInfo( node.getMethod().getReference().getDeclaringClass(), EnumSet.of(Intent.IntentType.SYSTEM_SERVICE), EnumSet.of(AndroidComponent.SERVICE), new int[] {1}); model = new SystemServiceModel(this.cha, this.options, this.cache, intent.getAction()); break; case EXTERNAL_TARGET: info = intentStarters.getInfo(method.getReference()); model = new ExternalModel( this.cha, this.options, this.cache, fetchTargetComponent(intent, method)); break; case STANDARD_ACTION: // TODO! // In Order to correctly evaluate a standard-action we would also have to look // at the URI of the Intent. case UNKNOWN_TARGET: info = intentStarters.getInfo(method.getReference()); model = new UnknownTargetModel( this.cha, this.options, this.cache, fetchTargetComponent(intent, method)); break; case IGNORE: return null; default: throw new java.lang.UnsupportedOperationException( "The Intent-Type " + intent.getType() + " is not known to IntentContextInterpreter"); // return method.makeIR(ctx, this.options.getSSAOptions()); } assert (info != null) : "IntentInfo is null! Every Starter should have an StartInfo..."; } // of model and info final SummarizedMethod override = model.getMethodAs(method.getReference(), callingClass, info, node); return override.makeIR(ctx, this.options.getSSAOptions()); } catch (CancelException e) { throw new IllegalStateException("The operation was canceled.", e); } } else { // This should _not_ happen: IntentContextSelector should always create an IntentContext. // final IMethod method = node.getMethod(); final IntentStarters.StartInfo info = intentStarters.getInfo(method.getReference()); assert (info != null) : "IntentInfo is null! Every Starter should have an StartInfo... - Method " + method.getReference(); final Intent intent = new Intent(Intent.UNBOUND); final AndroidComponent targetComponent = fetchTargetComponent(intent, method); try { final UnknownTargetModel model = new UnknownTargetModel(this.cha, this.options, this.cache, targetComponent); final SummarizedMethod override = model.getMethodAs( method.getReference(), callingClass, intentStarters.getInfo(method.getReference()), node); return override.makeIR(ctx, this.options.getSSAOptions()); } catch (CancelException e) { throw new IllegalStateException("The operation was canceled.", e); } } } } @Override public IRView getIRView(CGNode node) { return getIR(node); } /** * If the function associated with the node is handled by this class. * * @throws IllegalArgumentException if the given node is null */ @Override public boolean understands(CGNode node) { if (node == null) { throw new IllegalArgumentException("node is null"); } final MethodReference target = node.getMethod().getReference(); return intentStarters.isStarter(target); } @Override public Iterator<NewSiteReference> iterateNewSites(CGNode node) { if (node == null) { throw new IllegalArgumentException("node is null"); } assert understands(node); // Should already have been checked before { final IR ir = getIR(node); // Speeeed return ir.iterateNewSites(); } } @Override public Iterator<CallSiteReference> iterateCallSites(CGNode node) { if (node == null) { throw new IllegalArgumentException("node is null"); } assert understands(node); // Should already have been checked before { final IR ir = getIR(node); // Speeeed return ir.iterateCallSites(); } } // // Satisfy the rest of the interface // @Override public ControlFlowGraph<SSAInstruction, ISSABasicBlock> getCFG(CGNode node) { assert understands(node); return getIR(node).getControlFlowGraph(); } @Override public int getNumberOfStatements(CGNode node) { assert understands(node); return getIR(node).getInstructions().length; } @Override public DefUse getDU(CGNode node) { assert understands(node); return new DefUse(getIR(node)); } @Override public boolean recordFactoryType(CGNode node, IClass klass) { // this. return false; } @Override public Iterator<FieldReference> iterateFieldsWritten(CGNode node) { assert understands(node); final SSAInstruction[] statements = getIR(node).getInstructions(); return CodeScanner.getFieldsWritten(statements).iterator(); } @Override public Iterator<FieldReference> iterateFieldsRead(CGNode node) { assert understands(node); final SSAInstruction[] statements = getIR(node).getInstructions(); return CodeScanner.getFieldsRead(statements).iterator(); } }
13,903
37.946779
100
java
WALA
WALA-master/dalvik/src/main/java/com/ibm/wala/dalvik/ipa/callgraph/propagation/cfa/IntentContextSelector.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 under the terms listed below. * */ /* * Copyright (c) 2013, * Tobias Blaschke <code@tobiasblaschke.de> * All rights reserved. * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The names of the contributors may not be used to endorse or promote * products derived from this software without specific prior written * permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ package com.ibm.wala.dalvik.ipa.callgraph.propagation.cfa; import com.ibm.wala.classLoader.CallSiteReference; import com.ibm.wala.classLoader.IMethod; import com.ibm.wala.dalvik.ipa.callgraph.propagation.cfa.IntentStarters.StartInfo; import com.ibm.wala.dalvik.util.AndroidEntryPointManager; import com.ibm.wala.dalvik.util.AndroidTypes; 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.ConstantKey; import com.ibm.wala.ipa.callgraph.propagation.InstanceKey; import com.ibm.wala.ipa.cha.IClassHierarchy; import com.ibm.wala.types.MethodReference; import com.ibm.wala.types.Selector; import com.ibm.wala.util.intset.EmptyIntSet; import com.ibm.wala.util.intset.IntSet; import com.ibm.wala.util.intset.IntSetUtil; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Adds Intents to the Context of functions that start Android-Components. * * <p>This is done by remembering all new-sites where Intent-Objects are built and the parameters to * its Constructor. When a function managed by this Selector (see IntentStarters) is encountered the * stored information is added to its Context. * * @see com.ibm.wala.dalvik.ipa.callgraph.propagation.cfa.IntentContextInterpreter * @see com.ibm.wala.dalvik.ipa.callgraph.propagation.cfa.IntentStarters * @author Tobias Blaschke &lt;code@tobiasblaschke.de&gt; * @since 2013-10-14 */ public class IntentContextSelector implements ContextSelector { private static final Logger logger = LoggerFactory.getLogger(IntentContextSelector.class); private final IntentMap intents = new IntentMap(); private final ContextSelector parent; private final IntentStarters intentStarters; public IntentContextSelector(final IClassHierarchy cha) { this(null, cha); } /** * @param parent is always asked to build a Context first. Context generated by this class is * added then. */ public IntentContextSelector(final ContextSelector parent, final IClassHierarchy cha) { this.parent = parent; this.intentStarters = new IntentStarters(cha); } /** * Given a calling node and a call site, returns the Context in which the callee should be * evaluated. * * <p>{@inheritDoc} * * @throws IllegalArgumentException if the type of a parameter given as actualParameters does not * match an expected one */ @Override public Context getCalleeTarget( CGNode caller, CallSiteReference site, IMethod callee, InstanceKey[] actualParameters) { Context ctx = null; if (this.parent != null) { ctx = parent.getCalleeTarget(caller, site, callee, actualParameters); assert (ctx.get(Intent.INTENT_KEY) == null) : "Already have Intent: " + ctx + " caller " + caller + " callee " + callee; } if (intentStarters.isStarter(callee.getReference())) { // Handle startActivity(), startActivityForResult(), startService() and such // Search Android-Context and attach corresponding WALA-Context /* { final InstanceKey self = actualParameters[0]; assert (self != null) : "This-Pointer was not marked as relevant!"; if (seenContext.containsKey(self)) { ctx = new AndroidContext(ctx, seenContext.get(self).getContextType()); } else { logger.warn("No Android-Context seen for {}", caller); } } // */ Intent intent = null; { // Seach intent for (InstanceKey actualParameter : actualParameters) { final InstanceKey param = actualParameter; if (param == null) { continue; } else if (param.getConcreteType().getName().equals(AndroidTypes.IntentName)) { if (!intents.contains(param)) { logger.error("Unable to resolve Intent called from {}", caller.getMethod()); logger.error("Search Key: {} hash: {}", param, param.hashCode()); break; } else { intent = intents.find(param); break; } } } } // Add the context if (intent != null) { AndroidEntryPointManager.MANAGER.addCallSeen(site, intent); final Intent iintent = intents.findOrCreateImmutable(intent); return new IntentContext(ctx, iintent); // return new IntentContext(iintent); } else { logger.warn("Encountered unresolvable Intent"); intent = new Intent("Unresolvable"); intent.setImmutable(); AndroidEntryPointManager.MANAGER.addCallSeen(site, intent); return new IntentContext(ctx, intent); // return new IntentContext(intent); } } else if (callee.getReference().toString().contains("getSystemService")) { assert (actualParameters.length == 2) : "PARAMS LENGTH IS" + actualParameters.length; final InstanceKey param = actualParameters[1]; final Intent intent; { // Extract target-Service as intent if (param instanceof ConstantKey) { final String target = (String) ((ConstantKey<?>) param).getValue(); intent = new Intent(target) { @Override public Intent.IntentType getType() { return Intent.IntentType.SYSTEM_SERVICE; } // TODO override equals and hashCode? }; } else { intent = null; if (param == null) { logger.warn( "Got param as 'null'. Obviously can't handle this. Caller was: {}", caller.getMethod()); } else { logger.warn("Got param as {}. Can't handle this :(", param.getClass()); } } } // Add the context if (intent != null) { AndroidEntryPointManager.MANAGER.addCallSeen(site, intent); logger.info("SystemService {} in {} by {}", intent, site, caller); final Intent iintent = intents.findOrCreateImmutable(intent); return new IntentContext(ctx, iintent); // return new IntentContext(iintent); } } else if (callee.isInit() && callee.getDeclaringClass().getName().equals(AndroidTypes.IntentName)) { // // Handle the different Constructors of Intent // final InstanceKey self = actualParameters[0]; final Selector calleeSel = callee.getSelector(); boolean isExplicit = false; final InstanceKey actionKey; { // fetch actionKey, uriKey switch (callee.getNumberOfParameters()) { case 1: logger.debug("Handling Intent()"); actionKey = null; break; case 2: if (calleeSel.equals(Selector.make("<init>(Ljava/lang/String;)V"))) { logger.debug("Handling Intent(String action)"); actionKey = actualParameters[1]; } else if (calleeSel.equals(Selector.make("<init>(Landroid/content/Intent;)V"))) { logger.debug("Handling Intent(Intent other)"); final InstanceKey inIntent = actualParameters[1]; if (intents.contains(inIntent)) { intents.put(self, intents.find(inIntent)); } else { logger.warn("In Intent-Copy constructor: Unable to find the original"); } actionKey = null; } else { logger.error("No handling implemented for: {}", callee); actionKey = null; } break; case 3: if (calleeSel.equals(Selector.make("<init>(Ljava/lang/String;Landroid/net/Uri;)V"))) { logger.debug("Handling Intent(String action, Uri uri)"); // TODO: Use Information of the URI... actionKey = actualParameters[1]; } else if (calleeSel.equals( Selector.make("<init>(Landroid/content/Context;Ljava/lang/Class;)V"))) { logger.debug("Handling Intent(Context, Class)"); actionKey = actualParameters[2]; isExplicit = true; } else { logger.error("No handling implemented for: {}", callee); actionKey = null; } break; case 5: if (calleeSel.equals( Selector.make( "<init>(Ljava/lang/String;Landroid/net/Uri;Landroid/content/Context;Ljava/lang/Class;)V"))) { logger.debug("Handling Intent(String action, Uri uri, Context, Class)"); actionKey = actualParameters[4]; isExplicit = true; } else { logger.error("No handling implemented for: {}", callee); actionKey = null; } break; default: logger.error("Can't extract Info from Intent-Constructor: {} (not implemented)", site); actionKey = null; } } // of fetch actionKey final Intent intent = intents.findOrCreate(self); // Creates Wala-internal Intent if (actionKey == null) { logger.trace( "Got action as 'null'. Obviously can't handle this. Caller was {}", caller.getMethod()); if (isExplicit) { logger.warn( "An Intent with undeteminable target would be explicit - unbinding. Caller was {}", caller.getMethod()); intent.unbind(); } } else { intents.setAction(self, actionKey, isExplicit); } // final Intent intent = intents.find(self); // if (isExplicit && (! intent.isExplicit())) { // Has to check if already explicit as we // get here multiple times // intents.setExplicit(self); // } logger.debug("Setting the target of Intent {} in {} by {}", intent, site, caller); // TODO: Evaluate uriKey } else if (callee .getSelector() .equals(Selector.make("setAction(Ljava/lang/String;)Landroid/content/Intent;")) && callee.getDeclaringClass().getName().equals(AndroidTypes.IntentName)) { final InstanceKey self = actualParameters[0]; final InstanceKey actionKey = actualParameters[1]; final Intent intent = intents.find(self); if (AndroidEntryPointManager.MANAGER.isAllowIntentRerouting()) { logger.warn("Re-Setting the target of Intent {} in {} by {}", intent, site, caller); intents.setAction(self, actionKey, false); // May unbind internally } else { intents.unbind(self); } logger.info("Encountered Intent.setAction - Intent is now: {}", intent); } else if (callee .getSelector() .equals( Selector.make( "setComponent(Landroid/content/ComponentName;)Landroid/content/Intent;"))) { // TODO: We can't extract from ComponentName yet. final InstanceKey self = actualParameters[0]; final Intent intent = intents.find(self); logger.warn("Re-Setting the target of Intent {} in {} by {}", intent, site, caller); intent.setExplicit(); intents.unbind(self); } else if (callee .getSelector() .equals( Selector.make( "setClass(Landroid/content/Context;Ljava/lang/Class;)Landroid/content/Intent;")) || callee .getSelector() .equals( Selector.make( "setClassName(Ljava/lang/String;Ljava/lang/String;)Landroid/content/Intent;")) || callee .getSelector() .equals( Selector.make( "setClassName(Landroid/content/Context;Ljava/lang/String;)Landroid/content/Intent;"))) { final InstanceKey self = actualParameters[0]; final InstanceKey actionKey = actualParameters[2]; final Intent intent = intents.find(self); if (AndroidEntryPointManager.MANAGER.isAllowIntentRerouting()) { logger.warn("Re-Setting the target of Intent {} in {} by {}", intent, site, caller); intents.setAction(self, actionKey, true); } else { intents.unbind(self); } logger.info("Encountered Intent.setClass - Intent is now: {}", intent); } else if (callee.getSelector().equals(Selector.make("fillIn(Landroid/content/Intent;I)I"))) { // See 'setAction' before... TODO logger.warn("Intent.fillIn not implemented - Caller: {}", caller); final InstanceKey self = actualParameters[0]; intents.unbind(self); } else if (callee.isInit() && callee.getDeclaringClass().getName().equals(AndroidTypes.IntentSenderName)) { logger.error("Unable to evaluate IntentSender: Not implemented!"); // TODO } /*else if (site.isSpecial() && callee.getDeclaringClass().getName().equals( AndroidTypes.ContextWrapperName)) { final InstanceKey baseKey = actualParameters[1]; final InstanceKey wrapperKey = actualParameters[0]; logger.debug("Handling ContextWrapper(Context base)"); if (seenContext.containsKey(baseKey)) { seenContext.put(wrapperKey, seenContext.get(baseKey)); } else { if (baseKey == null) { logger.trace("Got baseKey as 'null'. Obviously can't handle this. Caller was: {}", caller.getMethod()); } else { logger.warn("ContextWrapper: No AndroidContext was seen for baseKey"); } } } else if ((site.isSpecial() && callee.getDeclaringClass().getName().equals( AndroidTypes.ContextImplName))) { final InstanceKey self = actualParameters[0]; seenContext.put(self, new AndroidContext(ctx, AndroidTypes.AndroidContextType.CONTEXT_IMPL)); } else if (callee.getDeclaringClass().getName().equals(AndroidTypes.ContextWrapperName) && callee.getSelector().equals(Selector.make("attachBaseContext(Landroid/content/Context;)V"))) { final InstanceKey baseKey = actualParameters[1]; final InstanceKey wrapperKey = actualParameters[0]; logger.debug("Handling ContextWrapper.attachBaseContext(base)"); if (seenContext.containsKey(baseKey)) { seenContext.put(wrapperKey, seenContext.get(baseKey)); } else { if (baseKey == null) { logger.trace("Got baseKey as 'null'. Obviously can't handle this. Caller was: {}", caller.getMethod()); } else { logger.warn("ContextWrapper: No AndroidContext was seen for baseKey"); } } } */ return ctx; } /** * Given a calling node and a call site, return the set of parameters based on which this selector * may choose to specialize contexts. * * <p>{@inheritDoc} */ @Override public IntSet getRelevantParameters(CGNode caller, CallSiteReference site) { IntSet ret; if (this.parent != null) { ret = this.parent.getRelevantParameters(caller, site); } else { ret = EmptyIntSet.instance; } final MethodReference target = site.getDeclaredTarget(); if (intentStarters.isStarter(target)) { final StartInfo info = intentStarters.getInfo(target); final int[] relevant = info.getRelevant(); if (relevant != null) { for (int element : relevant) { ret = IntSetUtil.add(ret, element); } } logger.debug("Get relevant for {} is {}", site, ret); } else if (site.isSpecial() && target.getDeclaringClass().getName().equals(AndroidTypes.IntentName)) { final MethodReference mRef = site.getDeclaredTarget(); final int numArgs = mRef.getNumberOfParameters(); // Intent() // Intent(Intent o) // Intent(String action) // Intent(String action, Uri uri) // Intent(Context packageContext, Class<?> cls) // Intent(String action, Uri uri, Context packageContext, Class<?> cls) // Select all params; switch (numArgs) { case 0: return EmptyIntSet.instance; case 1: return IntSetUtil.make(new int[] {0, 1}); case 2: logger.debug("Got Intent Constructor of: {}", site.getDeclaredTarget().getSelector()); return IntSetUtil.make(new int[] {0, 1, 2}); case 3: logger.debug("Got Intent Constructor of: {}", site.getDeclaredTarget().getSelector()); return IntSetUtil.make(new int[] {0, 1, 2, 3}); case 4: logger.debug("Got Intent Constructor of: {}", site.getDeclaredTarget().getSelector()); return IntSetUtil.make(new int[] {0, 1, 2, 3, 4}); default: logger.debug("Got Intent Constructor of: {}", site.getDeclaredTarget().getSelector()); return IntSetUtil.make(new int[] {0, 1, 2, 3, 4, 5}); } } else if (site.isSpecial() && target.getDeclaringClass().getName().equals(AndroidTypes.IntentSenderName)) { logger.warn("Encountered an IntentSender-Object: {}", target); if (target.getNumberOfParameters() == 0) { // public IntentSender() return IntSetUtil.make(new int[] {0}); } else { // public IntentSender(IIntentSender target) // public IntentSender(IBinder target) return IntSetUtil.make(new int[] {0, 1}); } } /*else if (site.isSpecial() && target.getDeclaringClass().getName().equals( AndroidTypes.ContextWrapperName)) { logger.debug("Fetched ContextWrapper ctor"); return IntSetUtil.make(new int[] { 0, 1 }); } else if ((site.isSpecial() && target.getDeclaringClass().getName().equals( AndroidTypes.ContextImplName))) { logger.debug("Fetched Context ctor"); return IntSetUtil.make(new int[] { 0 }); } else if (target.getDeclaringClass().getName().equals(AndroidTypes.ContextWrapperName) && target.getSelector().equals(Selector.make("attachBaseContext(Landroid/content/Context;)V"))) { logger.debug("Encountered ContextWrapper.attachBaseContext()"); return IntSetUtil.make(new int[] { 0, 1 }); }*/ else if (target .getSelector() .equals(Selector.make("getSystemService(Ljava/lang/String;)Ljava/lang/Object;"))) { logger.debug("Encountered Context.getSystemService()"); return IntSetUtil.make(new int[] {0, 1}); } else if (target .getSelector() .equals(Selector.make("setAction(Ljava/lang/String;)Landroid/content/Intent;"))) { return IntSetUtil.make(new int[] {0, 1}); } else if (target .getSelector() .equals( Selector.make( "setComponent(Landroid/content/ComponentName;)Landroid/content/Intent;"))) { return IntSetUtil.make(new int[] {0}); } else if (target .getSelector() .equals( Selector.make( "setClass(Landroid/content/Context;Ljava/lang/Class;)Landroid/content/Intent;"))) { return IntSetUtil.make(new int[] {0, 2}); } else if (target .getSelector() .equals( Selector.make( "setClassName(Landroid/content/Context;Ljava/lang/String;)Landroid/content/Intent;"))) { return IntSetUtil.make(new int[] {0, 2}); } else if (target .getSelector() .equals( Selector.make( "setClassName(Ljava/lang/String;Ljava/lang/String;)Landroid/content/Intent;"))) { return IntSetUtil.make(new int[] {0, 2}); } return ret; } // else if (site.isSpecial() && target.getDeclaringClass().getName().equals( }
21,615
41.30137
121
java
WALA
WALA-master/dalvik/src/main/java/com/ibm/wala/dalvik/ipa/callgraph/propagation/cfa/IntentMap.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 under the terms listed below. * */ /* * Copyright (c) 2013, * Tobias Blaschke <code@tobiasblaschke.de> * All rights reserved. * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The names of the contributors may not be used to endorse or promote * products derived from this software without specific prior written * permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ package com.ibm.wala.dalvik.ipa.callgraph.propagation.cfa; import com.ibm.wala.classLoader.IClass; import com.ibm.wala.core.util.strings.Atom; import com.ibm.wala.core.util.strings.StringStuff; import com.ibm.wala.ipa.callgraph.propagation.ConstantKey; import com.ibm.wala.ipa.callgraph.propagation.InstanceKey; import java.util.HashMap; import java.util.Map; /** * Stores references to the WALA-Intent objects. * * <p>This class is only of use in conjunction with the IntentContextSelector * * @author Tobias Blaschke &lt;code@tobiasblaschke.de&gt; */ /*package*/ class IntentMap { private final Map<InstanceKey, Intent> seen = new HashMap<>(); private final Map<Intent, Intent> immutables = new HashMap<>(); public Intent findOrCreateImmutable(final Intent intent) { if (immutables.containsKey(intent)) { final Intent immutable = immutables.get(intent); assert immutable.getAction().equals(intent.getAction()); return immutable; } else { final Intent immutable = intent.clone(); immutable.setImmutable(); immutables.put(intent, immutable); return immutable; } } public Intent find(final InstanceKey key) throws IndexOutOfBoundsException { if (key == null) { throw new IllegalArgumentException("InstanceKey may not be null"); } if (!seen.containsKey(key)) { throw new IndexOutOfBoundsException("No Intent was seen for key " + key); } return seen.get(key); } public Intent create(final InstanceKey key, final String action) { if (key == null) { throw new IllegalArgumentException("InstanceKey may not be null"); } if (seen.containsKey(key)) { throw new IndexOutOfBoundsException("There may only be one Intent for " + key); } final Intent intent = new Intent(action); seen.put(key, intent); return intent; } public Intent create(final InstanceKey key, final Atom action) { if (key == null) { throw new IllegalArgumentException("InstanceKey may not be null"); } if (seen.containsKey(key)) { throw new IndexOutOfBoundsException("There may only be one Intent for " + key); } final Intent intent = new Intent(action); seen.put(key, intent); return intent; } public Intent create(final InstanceKey key) { if (key == null) { throw new IllegalArgumentException("InstanceKey may not be null"); } if (seen.containsKey(key)) { throw new IndexOutOfBoundsException("There may only be one Intent for " + key); } final Intent intent = new Intent(); seen.put(key, intent); return intent; } public Intent findOrCreate(final InstanceKey key) { if (seen.containsKey(key)) { return find(key); } else { return create(key); } } public void put(final InstanceKey key, final Intent intent) { seen.put(key, intent); } public boolean contains(final InstanceKey key) { return seen.containsKey(key); } public Intent findOrCreate(final InstanceKey key, String action) { final Intent intent = findOrCreate(key); final Atom foundAction = intent.getAction(); if (!foundAction.equals(Atom.findOrCreateAsciiAtom(action))) { throw new IllegalArgumentException( "Actions differ (" + action + ", " + foundAction + ") for Intent " + key); } return intent; } public Intent setAction(final InstanceKey key, final String action, boolean isExplicit) { return setAction(key, Atom.findOrCreateAsciiAtom(action), isExplicit); } public Intent unbind(final InstanceKey key) { final Intent intent = find(key); intent.unbind(); return intent; } public Intent setExplicit(final InstanceKey key) { if (contains(key)) { final Intent intent = find(key); intent.setExplicit(); return intent; } else { throw new IllegalArgumentException("setAction: No Intent found for key " + key); // final Intent intent = create(key); // intent.setExplicit(); // return intent; } } public Intent setAction(final InstanceKey key, final Atom action, boolean isExplicit) { if (contains(key)) { final Intent intent = find(key); if (isExplicit) { intent.setActionExplicit(action); } else { intent.setAction(action); } return intent; } else { final Intent intent = create(key, action); return intent; } } public Intent setAction(final Intent intent, final String action, boolean isExplicit) { for (final Map.Entry<InstanceKey, Intent> entry : seen.entrySet()) { if (entry.getValue().equals(intent)) { return setAction(entry.getKey(), action, isExplicit); } } throw new IllegalStateException("The Intent " + intent + " was not registered before!"); } public Intent setAction(final InstanceKey key, final InstanceKey actionKey, boolean isExplicit) { if (actionKey == null) { return find(key); } final String action; { if (actionKey instanceof ConstantKey) { final Object actionO = ((ConstantKey<?>) actionKey).getValue(); if (actionO instanceof String) { action = StringStuff.deployment2CanonicalTypeString((String) actionO); } else if (actionO instanceof IClass) { action = ((IClass) actionO).getName().toString(); } else { throw new IllegalArgumentException("Wrong action type: " + actionO.getClass()); } } else { unbind(key); return null; } } return setAction(key, action, isExplicit); } }
7,474
32.520179
99
java
WALA
WALA-master/dalvik/src/main/java/com/ibm/wala/dalvik/ipa/callgraph/propagation/cfa/IntentStarters.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 under the terms listed below. * */ /* * Copyright (c) 2013, * Tobias Blaschke <code@tobiasblaschke.de> * All rights reserved. * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The names of the contributors may not be used to endorse or promote * products derived from this software without specific prior written * permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ package com.ibm.wala.dalvik.ipa.callgraph.propagation.cfa; import com.ibm.wala.dalvik.ipa.callgraph.propagation.cfa.Intent.IntentType; import com.ibm.wala.dalvik.util.AndroidComponent; import com.ibm.wala.dalvik.util.AndroidTypes; import com.ibm.wala.ipa.cha.IClassHierarchy; import com.ibm.wala.types.ClassLoaderReference; import com.ibm.wala.types.MethodReference; import com.ibm.wala.types.Selector; import com.ibm.wala.types.TypeReference; import com.ibm.wala.util.collections.HashMapFactory; import java.util.Collections; import java.util.EnumSet; import java.util.HashMap; import java.util.Set; /** * Contains Information on functions that start Android-Components based on an Intent. * * <p>This is used by the IntentContextSelector to add an IntentContext to this Methods. * * <p>TODO: TODO: Fill in better values for targetAccuracy and componentType TODO: Add declaring * class * * @author Tobias Blaschke &lt;code@tobiasblaschke.de&gt; * @since 1013-10-16 */ public class IntentStarters { /** The flags influence the later model. */ public enum StarterFlags { /** Call the function onActivityResult of the calling Activity. */ CALL_ON_ACTIVITY_RESULT, /** * The intent is started using other permissions as the caller has. * * <p>This is used with startIntentSender */ QUENCH_PERMISSIONS, /** * For internal use only. * * <p>Used during the "boot process" and when installing the context free overrides. */ CONTEXT_FREE, } /** Handling IntentSenders causes issues */ private final boolean doIntentSender = true; /** Contains information on how to call a starter-function. */ public static class StartInfo { private final Set<IntentType> targetAccuracy; /** used to dispatch to the correct MiniModel if intent-target could not be retreived */ private final Set<AndroidComponent> componentType; /** relevant for the IntentContextSelector */ private final int[] relevantParameters; private final Set<StarterFlags> flags; private final TypeReference declaringClass; StartInfo( final TypeReference declaringClass, final Set<IntentType> targetAccuracy, final Set<AndroidComponent> componentType, final int[] relevantParameters) { this( declaringClass, targetAccuracy, componentType, relevantParameters, EnumSet.noneOf(StarterFlags.class)); } StartInfo( final TypeReference declaringClass, final Set<IntentType> targetAccuracy, final Set<AndroidComponent> componentType, final int[] relevantParameters, final Set<StarterFlags> flags) { this.declaringClass = declaringClass; this.targetAccuracy = targetAccuracy; this.componentType = componentType; this.relevantParameters = relevantParameters; this.flags = flags; } public static StartInfo makeContextFree(final AndroidComponent component) { final Set<AndroidComponent> compo = (component == null) ? Collections.emptySet() : EnumSet.of(component); return new IntentStarters.StartInfo( null, EnumSet.of(IntentType.UNKNOWN_TARGET), compo, new int[0], EnumSet.of(StarterFlags.CONTEXT_FREE)); } /** Set the CONTEXT_FREE Flag. */ public void setContextFree() { this.flags.add(StarterFlags.CONTEXT_FREE); } /** The parameters the ContextSelecor shall remember. */ public int[] getRelevant() { return relevantParameters; } public TypeReference getDeclaringClass() { return this.declaringClass; } /** * These influence how the model is built. * * @see com.ibm.wala.dalvik.ipa.callgraph.propagation.cfa.IntentStarters.StarterFlags */ public Set<StarterFlags> getFlags() { return this.flags; } /** * Target-Types that may started by this. * * <p>Although a set of multiple Components may be returned in most cases it is only one type. */ public Set<AndroidComponent> getComponentsPossible() { return this.componentType; } public boolean isSystemService() { return this.targetAccuracy.contains(IntentType.SYSTEM_SERVICE); // XXX Nah.. not so nice :( } @Override public String toString() { return "<StartInfo flags=" + flags + " to possible " + componentType + " with allowed Accuracies of " + targetAccuracy + "/>"; } } private final HashMap<Selector, StartInfo> starters = HashMapFactory.make(); public boolean isStarter(MethodReference mRef) { return starters.containsKey(mRef.getSelector()); } public StartInfo getInfo(MethodReference mRef) { return starters.get(mRef.getSelector()); } public StartInfo getInfo(Selector mSel) { return starters.get(mSel); } public Set<Selector> getKnownMethods() { return starters.keySet(); } public IntentStarters(IClassHierarchy cha) { final ClassLoaderReference searchLoader = ClassLoaderReference.Primordial; final TypeReference tContextWrapper = TypeReference.find(searchLoader, "Landroid/content/ContextWrapper"); final TypeReference tContext = TypeReference.find(searchLoader, "Landroid/content/Context"); final TypeReference tActivity = TypeReference.find(searchLoader, "Landroid/app/Activity"); // Stubs may be to old for: final boolean doFragments = (cha.lookupClass(AndroidTypes.Fragment) != null); final boolean doUsers = (cha.lookupClass(AndroidTypes.UserHandle) != null); if (!doFragments) { System.out.println( "WARNING: IntentStarters skipping starters with Fragments - Stubs to old!"); } if (!doUsers) { System.out.println( "WARNING: IntentStarters skipping starters with UserHandles - Stubs to old!"); } // This does not belong here: /* starters.put(Selector.make("getSystemService(Ljava/lang/String;)Ljava/lang/Object;"), new StartInfo(tContext, EnumSet.of(IntentType.EXTERNAL_TARGET), EnumSet.of(AndroidComponent.SERVICE), new int[] {1})); starters.put(Selector.make("getSystemService(Ljava/lang/String;)Ljava/lang/Object;"), new StartInfo(tActivity, EnumSet.of(IntentType.EXTERNAL_TARGET), EnumSet.of(AndroidComponent.SERVICE), new int[] {1})); */ // android.content.ContextWrapper.bindService(Intent service, ServiceConnection conn, int flags) starters.put( /*MethodReference.findOrCreate(tContextWrapper,*/ Selector.make( "bindService(Landroid/content/Intent;Landroid/content/ServiceConnection;I)Z"), new StartInfo( tContextWrapper, EnumSet.of(IntentType.UNKNOWN_TARGET), EnumSet.of(AndroidComponent.SERVICE), new int[] {1})); // Delegates directly to android.content.Context.bindService // android.content.ContextWrapper.sendBroadcast(Intent intent) starters.put( /* MethodReference.findOrCreate(tContextWrapper, */ Selector.make( "sendBroadcast(Landroid/content/Intent;)V"), new StartInfo( tContextWrapper, EnumSet.of(IntentType.BROADCAST), EnumSet.of(AndroidComponent.BROADCAST_RECEIVER), new int[] {1})); // Delegates directly to android.content.Context. // android.content.ContextWrapper.sendBroadcast(Intent intent, String receiverPermission) starters.put( /* MethodReference.findOrCreate(tContextWrapper, */ Selector.make( "sendBroadcast(Landroid/content/Intent;Ljava/lang/String;)V"), new StartInfo( tContextWrapper, EnumSet.of(IntentType.BROADCAST), EnumSet.of(AndroidComponent.BROADCAST_RECEIVER), new int[] {1})); // Delegates directly to android.content.Context. if (doUsers) { // android.content.ContextWrapper.sendBroadcastAsUser(Intent intent, UserHandle user) starters.put( /* MethodReference.findOrCreate(tContextWrapper, */ Selector.make( "sendBroadcastAsUser(Landroid/content/Intent;Landroid/os/UserHandle;)V"), new StartInfo( tContextWrapper, EnumSet.of(IntentType.BROADCAST), EnumSet.of(AndroidComponent.BROADCAST_RECEIVER), new int[] {1})); // Delegates directly to android.content.Context. // android.content.ContextWrapper.sendBroadcastAsUser(Intent intent, UserHandle user, String // receiverPermission) starters.put( /* MethodReference.findOrCreate(tContextWrapper, */ Selector.make( "sendBroadcastAsUser(Landroid/content/Intent;Landroid/os/UserHandle;Ljava/lang/String;)V"), new StartInfo( tContextWrapper, EnumSet.of(IntentType.BROADCAST), EnumSet.of(AndroidComponent.BROADCAST_RECEIVER), new int[] {1})); // Delegates directly to android.content.Context. } // android.content.ContextWrapper.sendOrderedBroadcast(Intent intent, String receiverPermission, // BroadcastReceiver resultReceiver, // Handler scheduler, int initialCode, String initialData, Bundle initialExtras) starters.put( /* MethodReference.findOrCreate(tContextWrapper, */ Selector.make( "sendOrderedBroadcast(Landroid/content/Intent;Ljava/lang/String;Landroid/content/BroadcastReceiver;Landroid/os/Handler;I" + "Ljava/lang/String;Landroid/os/Bundle;)V"), new StartInfo( tContextWrapper, EnumSet.of(IntentType.BROADCAST), EnumSet.of(AndroidComponent.BROADCAST_RECEIVER), new int[] {1})); // Delegates directly to android.content.Context. // android.content.ContextWrapper.sendOrderedBroadcast(Intent intent, String receiverPermission) starters.put( /* MethodReference.findOrCreate(tContextWrapper, */ Selector.make( "sendOrderedBroadcast(Landroid/content/Intent;Ljava/lang/String;)V"), new StartInfo( tContextWrapper, EnumSet.of(IntentType.BROADCAST), EnumSet.of(AndroidComponent.BROADCAST_RECEIVER), new int[] {1})); // Delegates directly to android.content.Context. if (doUsers) { // android.content.ContextWrapper.sendOrderedBroadcastAsUser(Intent intent, UserHandle user, // String receiverPermission, // BroadcastReceiver resultReceiver, Handler scheduler, int initialCode, String // initialData, Bundle initialExtras) starters.put( /* MethodReference.findOrCreate(tContextWrapper, */ Selector.make( "sendOrderedBroadcastAsUser(Landroid/content/Intent;Landroid/os/UserHandle;Ljava/lang/String;Landroid/content/BroadcastReceiver;" + "Landroid/os/Handler;ILjava/lang/String;Landroid/os/Bundle;)V"), new StartInfo( tContextWrapper, EnumSet.of(IntentType.BROADCAST), EnumSet.of(AndroidComponent.BROADCAST_RECEIVER), new int[] {1})); // Delegates directly to android.content.Context. } // android.content.ContextWrapper.sendStickyBroadcast(Intent intent) starters.put( /* MethodReference.findOrCreate(tContextWrapper, */ Selector.make( "sendStickyBroadcast(Landroid/content/Intent;)V"), new StartInfo( tContextWrapper, EnumSet.of(IntentType.BROADCAST), EnumSet.of(AndroidComponent.BROADCAST_RECEIVER), new int[] {1})); // Delegates directly to android.content.Context. if (doUsers) { // android.content.ContextWrapper.sendStickyBroadcastAsUser(Intent intent, UserHandle user) starters.put( /* MethodReference.findOrCreate(tContextWrapper, */ Selector.make( "sendStickyBroadcastAsUser(Landroid/content/Intent;Landroid/os/UserHandle;)V"), new StartInfo( tContextWrapper, EnumSet.of(IntentType.BROADCAST), EnumSet.of(AndroidComponent.BROADCAST_RECEIVER), new int[] {1})); // Delegates directly to android.content.Context. } // android.content.ContextWrapper.sendStickyOrderedBroadcast(Intent intent, BroadcastReceiver // resultReceiver, Handler scheduler, int initialCode, // String initialData, Bundle initialExtras) starters.put( /* MethodReference.findOrCreate(tContextWrapper, */ Selector.make( "sendStickyOrderedBroadcast(Landroid/content/Intent;Ljava/lang/String;Landroid/content/BroadcastReceiver;Landroid/os/Handler;" + "ILjava/lang/String;Landroid/os/Bundle;)V"), new StartInfo( tContextWrapper, EnumSet.of(IntentType.BROADCAST), EnumSet.of(AndroidComponent.BROADCAST_RECEIVER), new int[] {1})); // Delegates directly to android.content.Context. if (doUsers) { // android.content.ContextWrapper.sendStickyOrderedBroadcastAsUser(Intent intent, UserHandle // user, BroadcastReceiver resultReceiver, // Handler scheduler, int initialCode, String initialData, Bundle initialExtras) starters.put( /* MethodReference.findOrCreate(tContextWrapper, */ Selector.make( "sendStickyOrderedBroadcastAsUser(Landroid/content/Intent;Landroid/os/UserHandle;Landroid/content/BroadcastReceiver;" + "Landroid/os/Handler;ILjava/lang/String;Landroid/os/Bundle;)V"), new StartInfo( tContextWrapper, EnumSet.of(IntentType.BROADCAST), EnumSet.of(AndroidComponent.BROADCAST_RECEIVER), new int[] {1})); // Delegates directly to android.content.Context. } // android.content.ContextWrapper.startActivities(Intent[] intents) starters.put( /* MethodReference.findOrCreate(tContextWrapper, */ Selector.make( "startActivities([Landroid/content/Intent;)V"), new StartInfo( tContextWrapper, EnumSet.of(IntentType.UNKNOWN_TARGET), EnumSet.of(AndroidComponent.ACTIVITY), new int[] {1})); // Delegates directly to android.content.Context. // android.content.ContextWrapper.startActivities(Intent[] intents, Bundle options) starters.put( /* MethodReference.findOrCreate(tContextWrapper, */ Selector.make( "startActivities([Landroid/content/Intent;Landroid/os/Bundle;)V"), new StartInfo( tContextWrapper, EnumSet.of(IntentType.UNKNOWN_TARGET), EnumSet.of(AndroidComponent.ACTIVITY), new int[] {1})); // Delegates directly to android.content.Context. // android.content.ContextWrapper.startActivity(Intent intent) starters.put( /* MethodReference.findOrCreate(tContextWrapper, */ Selector.make( "startActivity(Landroid/content/Intent;)V"), new StartInfo( tContextWrapper, EnumSet.of(IntentType.UNKNOWN_TARGET), EnumSet.of(AndroidComponent.ACTIVITY), new int[] {1})); // Delegates directly to android.content.Context. // android.content.ContextWrapper.startActivity(Intent intents, Bundle options) starters.put( /* MethodReference.findOrCreate(tContextWrapper, */ Selector.make( "startActivity(Landroid/content/Intent;Landroid/os/Bundle;)V"), new StartInfo( tContextWrapper, EnumSet.of(IntentType.UNKNOWN_TARGET), EnumSet.of(AndroidComponent.ACTIVITY), new int[] {1})); // Delegates directly to android.content.Context. if (doIntentSender) { // android.content.ContextWrapper.startIntentSender(IntentSender intent, Intent fillInIntent, // int flagsMask, int flagsValues, // int extraFlags, Bundle options) starters.put( /* MethodReference.findOrCreate(tContextWrapper, */ Selector.make( // TODO "startIntentSender(Landroid/content/IntentSender;Landroid/content/Intent;IIILandroid/os/Bundle;)V"), new StartInfo( tContextWrapper, EnumSet.of(IntentType.UNKNOWN_TARGET), EnumSet.of(AndroidComponent.ACTIVITY), new int[] {1, 2}, EnumSet.of(StarterFlags.QUENCH_PERMISSIONS))); // Delegates directly to android.content.Context. // android.content.ContextWrapper.startIntentSender(IntentSender intent, Intent fillInIntent, // int flagsMask, int flagsValues, int extraFlags) starters.put( /* MethodReference.findOrCreate(tContextWrapper, */ Selector.make( // TODO "startIntentSender(Landroid/content/IntentSender;Landroid/content/Intent;III)V"), new StartInfo( tContextWrapper, EnumSet.of(IntentType.UNKNOWN_TARGET), EnumSet.of(AndroidComponent.ACTIVITY), new int[] {1, 2}, EnumSet.of(StarterFlags.QUENCH_PERMISSIONS))); // Delegates directly to android.content.Context. } // android.content.ContextWrapper.startService(Intent service) starters.put( /* MethodReference.findOrCreate(tContextWrapper, */ Selector.make( "startService(Landroid/content/Intent;)Landroid/content/ComponentName;"), new StartInfo( tContextWrapper, EnumSet.of(IntentType.UNKNOWN_TARGET), EnumSet.of(AndroidComponent.SERVICE), new int[] {1})); // Delegates directly to android.content.Context. // android.content.Context.bindService(Intent service, ServiceConnection conn, int flags) starters.put( /* MethodReference.findOrCreate(tContext, */ Selector.make( "bindService(Landroid/content/Intent;Landroid/content/ServiceConnection;I)Z"), new StartInfo( tContext, EnumSet.of(IntentType.UNKNOWN_TARGET), EnumSet.of(AndroidComponent.SERVICE), new int[] {1})); // android.content.Context.sendBroadcast(Intent intent) starters.put( /* MethodReference.findOrCreate(tContext, */ Selector.make( "sendBroadcast(Landroid/content/Intent;)V"), new StartInfo( tContext, EnumSet.of(IntentType.BROADCAST), EnumSet.of(AndroidComponent.BROADCAST_RECEIVER), new int[] {1})); // android.content.Context.sendBroadcast(Intent intent, String receiverPermission) starters.put( /* MethodReference.findOrCreate(tContext, */ Selector.make( "sendBroadcast(Landroid/content/Intent;Ljava/lang/String;)V"), new StartInfo( tContext, EnumSet.of(IntentType.BROADCAST), EnumSet.of(AndroidComponent.BROADCAST_RECEIVER), new int[] {1})); if (doUsers) { // android.content.Context.sendBroadcastAsUser(Intent intent, UserHandle user) starters.put( /* MethodReference.findOrCreate(tContext, */ Selector.make( "sendBroadcastAsUser(Landroid/content/Intent;Landroid/os/UserHandle;)V"), new StartInfo( tContext, EnumSet.of(IntentType.BROADCAST), EnumSet.of(AndroidComponent.BROADCAST_RECEIVER), new int[] {1})); // android.content.Context.sendBroadcastAsUser(Intent intent, UserHandle user, String // receiverPermission) starters.put( /* MethodReference.findOrCreate(tContext, */ Selector.make( "sendBroadcastAsUser(Landroid/content/Intent;Landroid/os/UserHandle;Ljava/lang/String;)V"), new StartInfo( tContext, EnumSet.of(IntentType.BROADCAST), EnumSet.of(AndroidComponent.BROADCAST_RECEIVER), new int[] {1})); } // android.content.Context.sendOrderedBroadcast(Intent intent, String receiverPermission, // BroadcastReceiver resultReceiver, // Handler scheduler, int initialCode, String initialData, Bundle initialExtras) starters.put( /* MethodReference.findOrCreate(tContext, */ Selector.make( "sendOrderedBroadcast(Landroid/content/Intent;Ljava/lang/String;Landroid/content/BroadcastReceiver;Landroid/os/Handler;I" + "Ljava/lang/String;Landroid/os/Bundle;)V"), new StartInfo( tContext, EnumSet.of(IntentType.BROADCAST), EnumSet.of(AndroidComponent.BROADCAST_RECEIVER), new int[] {1})); // android.content.Context.sendOrderedBroadcast(Intent intent, String receiverPermission) starters.put( /* MethodReference.findOrCreate(tContext, */ Selector.make( "sendOrderedBroadcast(Landroid/content/Intent;Ljava/lang/String;)V"), new StartInfo( tContext, EnumSet.of(IntentType.BROADCAST), EnumSet.of(AndroidComponent.BROADCAST_RECEIVER), new int[] {1})); if (doUsers) { // android.content.Context.sendOrderedBroadcastAsUser(Intent intent, UserHandle user, String // receiverPermission, // BroadcastReceiver resultReceiver, Handler scheduler, int initialCode, String // initialData, Bundle initialExtras) starters.put( /* MethodReference.findOrCreate(tContext, */ Selector.make( "sendOrderedBroadcastAsUser(Landroid/content/Intent;Landroid/os/UserHandle;Ljava/lang/String;Landroid/content/BroadcastReceiver;" + "Landroid/os/Handler;ILjava/lang/String;Landroid/os/Bundle;)V"), new StartInfo( tContext, EnumSet.of(IntentType.BROADCAST), EnumSet.of(AndroidComponent.BROADCAST_RECEIVER), new int[] {1})); // android.content.Context.sendStickyBroadcast(Intent intent) starters.put( /* MethodReference.findOrCreate(tContext, */ Selector.make( "sendStickyBroadcast(Landroid/content/Intent;)V"), new StartInfo( tContext, EnumSet.of(IntentType.BROADCAST), EnumSet.of(AndroidComponent.BROADCAST_RECEIVER), new int[] {1})); // android.content.Context.sendStickyBroadcastAsUser(Intent intent, UserHandle user) starters.put( /* MethodReference.findOrCreate(tContext, */ Selector.make( "sendStickyBroadcastAsUser(Landroid/content/Intent;Landroid/os/UserHandle;)V"), new StartInfo( tContext, EnumSet.of(IntentType.BROADCAST), EnumSet.of(AndroidComponent.BROADCAST_RECEIVER), new int[] {1})); } // android.content.Context.sendStickyOrderedBroadcast(Intent intent, BroadcastReceiver // resultReceiver, Handler scheduler, int initialCode, // String initialData, Bundle initialExtras) starters.put( /* MethodReference.findOrCreate(tContext, */ Selector.make( "sendStickyOrderedBroadcast(Landroid/content/Intent;Ljava/lang/String;Landroid/content/BroadcastReceiver;Landroid/os/Handler;" + "ILjava/lang/String;Landroid/os/Bundle;)V"), new StartInfo( tContext, EnumSet.of(IntentType.BROADCAST), EnumSet.of(AndroidComponent.BROADCAST_RECEIVER), new int[] {1})); if (doUsers) { // android.content.Context.sendStickyOrderedBroadcastAsUser(Intent intent, UserHandle user, // BroadcastReceiver resultReceiver, // Handler scheduler, int initialCode, String initialData, Bundle initialExtras) starters.put( /* MethodReference.findOrCreate(tContext, */ Selector.make( "sendStickyOrderedBroadcastAsUser(Landroid/content/Intent;Landroid/os/UserHandle;Landroid/content/BroadcastReceiver;" + "Landroid/os/Handler;ILjava/lang/String;Landroid/os/Bundle;)V"), new StartInfo( tContext, EnumSet.of(IntentType.BROADCAST), EnumSet.of(AndroidComponent.BROADCAST_RECEIVER), new int[] {1})); } // android.content.Context.startActivities(Intent[] intents) starters.put( /* MethodReference.findOrCreate(tContext, */ Selector.make( "startActivities([Landroid/content/Intent;)V"), new StartInfo( tContext, EnumSet.of(IntentType.UNKNOWN_TARGET), EnumSet.of(AndroidComponent.ACTIVITY), new int[] {1})); // android.content.Context.startActivities(Intent[] intents, Bundle options) starters.put( /* MethodReference.findOrCreate(tContext, */ Selector.make( "startActivities([Landroid/content/Intent;Landroid/os/Bundle;)V"), new StartInfo( tContext, EnumSet.of(IntentType.UNKNOWN_TARGET), EnumSet.of(AndroidComponent.ACTIVITY), new int[] {1})); // android.content.Context.startActivity(Intent intent) starters.put( /* MethodReference.findOrCreate(tContext, */ Selector.make( "startActivity(Landroid/content/Intent;)V"), new StartInfo( tContext, EnumSet.of(IntentType.UNKNOWN_TARGET), EnumSet.of(AndroidComponent.ACTIVITY), new int[] {1})); // android.content.Context.startActivity(Intent intents, Bundle options) starters.put( /* MethodReference.findOrCreate(tContext, */ Selector.make( "startActivity(Landroid/content/Intent;Landroid/os/Bundle;)V"), new StartInfo( tContext, EnumSet.of(IntentType.UNKNOWN_TARGET), EnumSet.of(AndroidComponent.ACTIVITY), new int[] {1})); if (doIntentSender) { // android.content.Context.startIntentSender(IntentSender intent, Intent fillInIntent, int // flagsMask, int flagsValues, // int extraFlags, Bundle options) starters.put( /* MethodReference.findOrCreate(tContext, */ Selector.make( // TODO "startIntentSender(Landroid/content/IntentSender;Landroid/content/Intent;IIILandroid/os/Bundle;)V"), new StartInfo( tContext, EnumSet.of(IntentType.UNKNOWN_TARGET), EnumSet.of(AndroidComponent.ACTIVITY), new int[] {1, 2}, EnumSet.of(StarterFlags.QUENCH_PERMISSIONS))); // android.content.Context.startIntentSender(IntentSender intent, Intent fillInIntent, int // flagsMask, int flagsValues, int extraFlags) starters.put( /* MethodReference.findOrCreate(tContext, */ Selector.make( // TODO "startIntentSender(Landroid/content/IntentSender;Landroid/content/Intent;III)V"), new StartInfo( tContext, EnumSet.of(IntentType.UNKNOWN_TARGET), EnumSet.of(AndroidComponent.ACTIVITY), new int[] {1, 2}, EnumSet.of(StarterFlags.QUENCH_PERMISSIONS))); } // android.content.Context.startService(Intent service) starters.put( /* MethodReference.findOrCreate(tContext, */ Selector.make( "startService(Landroid/content/Intent;)Landroid/content/ComponentName;"), new StartInfo( tContext, EnumSet.of(IntentType.UNKNOWN_TARGET), EnumSet.of(AndroidComponent.SERVICE), new int[] {1})); // android.app.Activity.startActivities(Intent[] intents) starters.put( /* MethodReference.findOrCreate(tActivity, */ Selector.make( "startActivities([Landroid/content/Intent;)V"), new StartInfo( tActivity, EnumSet.of(IntentType.UNKNOWN_TARGET), EnumSet.of(AndroidComponent.ACTIVITY), new int[] {1})); // android.app.Activity.startActivities(Intent[] intents, Bundle options) starters.put( /* MethodReference.findOrCreate(tActivity, */ Selector.make( "startActivities([Landroid/content/Intent;Landroid/os/Bundle;)V"), new StartInfo( tActivity, EnumSet.of(IntentType.UNKNOWN_TARGET), EnumSet.of(AndroidComponent.ACTIVITY), new int[] {1})); // android.app.Activity.startActivity(Intent intent) starters.put( /* MethodReference.findOrCreate(tActivity, */ Selector.make( "startActivity(Landroid/content/Intent;)V"), new StartInfo( tActivity, EnumSet.of(IntentType.UNKNOWN_TARGET), EnumSet.of(AndroidComponent.ACTIVITY), new int[] {1})); // android.app.Activity.startActivity(Intent intents, Bundle options) starters.put( /* MethodReference.findOrCreate(tActivity, */ Selector.make( "startActivity(Landroid/content/Intent;Landroid/os/Bundle;)V"), new StartInfo( tActivity, EnumSet.of(IntentType.UNKNOWN_TARGET), EnumSet.of(AndroidComponent.ACTIVITY), new int[] {1})); // android.app.Activity.startActivityForResult(Intent intent, int requestCode) starters.put( /* MethodReference.findOrCreate(tActivity, */ Selector.make( "startActivityForResult(Landroid/content/Intent;I)V"), new StartInfo( tActivity, EnumSet.of(IntentType.UNKNOWN_TARGET), EnumSet.of(AndroidComponent.ACTIVITY), new int[] {1}, EnumSet.of(StarterFlags.CALL_ON_ACTIVITY_RESULT))); // android.app.Activity.startActivityForResult(Intent intent, int requestCode, Bundle options) starters.put( /* MethodReference.findOrCreate(tActivity, */ Selector.make( "startActivityForResult(Landroid/content/Intent;ILandroid/os/Bundle;)V"), new StartInfo( tActivity, EnumSet.of(IntentType.UNKNOWN_TARGET), EnumSet.of(AndroidComponent.ACTIVITY), new int[] {1}, EnumSet.of(StarterFlags.CALL_ON_ACTIVITY_RESULT))); // android.app.Activity.startActivityFromChild(Activity child, Intent intent, int requestCode) starters.put( /* MethodReference.findOrCreate(tActivity, */ Selector.make( "startActivityFromChild(Landroid/app/Activity;Landroid/content/Intent;I)V"), new StartInfo( tActivity, EnumSet.of(IntentType.UNKNOWN_TARGET), EnumSet.of(AndroidComponent.ACTIVITY), new int[] {1})); // android.app.Activity.startActivityFromChild(Activity child, Intent intent, int requestCode, // Bundle options) starters.put( /* MethodReference.findOrCreate(tActivity, */ Selector.make( "startActivityFromChild(Landroid/app/Activity;Landroid/content/Intent;ILandroid/os/Bundle;)V"), new StartInfo( tActivity, EnumSet.of(IntentType.UNKNOWN_TARGET), EnumSet.of(AndroidComponent.ACTIVITY), new int[] {1})); if (doFragments) { // android.app.Activity.startActivityFromFragment(Fragment fragment, Intent intent, int // requestCode) starters.put( /* MethodReference.findOrCreate(tActivity, */ Selector.make( "startActivityFromFragment(Landroid/app/Fragment;Landroid/content/Intent;I)V"), new StartInfo( tActivity, EnumSet.of(IntentType.UNKNOWN_TARGET), EnumSet.of(AndroidComponent.ACTIVITY), new int[] {1})); // android.app.Activity.startActivityFromFragment(Fragment fragment, Intent intent, int // requestCode, Bundle options) starters.put( /* MethodReference.findOrCreate(tActivity, */ Selector.make( "startActivityFromFragment(Landroid/app/Fragment;Landroid/content/Intent;ILandroid/os/Bundle;)V"), new StartInfo( tActivity, EnumSet.of(IntentType.UNKNOWN_TARGET), EnumSet.of(AndroidComponent.ACTIVITY), new int[] {1})); } // android.app.Activity.startActivityIfNeeded(Intent intent, int requestCode) starters.put( /* MethodReference.findOrCreate(tActivity, */ Selector.make( "startActivityIfNeeded(Landroid/content/Intent;I)Z"), new StartInfo( tActivity, EnumSet.of(IntentType.UNKNOWN_TARGET), EnumSet.of(AndroidComponent.ACTIVITY), new int[] {1})); // android.app.Activity.startActivityIfNeeded(Intent intent, int requestCode, Bundle options) starters.put( /* MethodReference.findOrCreate(tActivity, */ Selector.make( "startActivityIfNeeded(Landroid/content/Intent;ILandroid/os/Bundle;)Z"), new StartInfo( tActivity, EnumSet.of(IntentType.UNKNOWN_TARGET), EnumSet.of(AndroidComponent.ACTIVITY), new int[] {1})); if (doIntentSender) { // android.app.Activity.startIntentSender(IntentSender intent, Intent fillInIntent, int // flagsMask, int flagsValues, // int extraFlags, Bundle options) starters.put( /* MethodReference.findOrCreate(tActivity, */ Selector.make( // TODO "startIntentSender(Landroid/content/IntentSender;Landroid/content/Intent;IIILandroid/os/Bundle;)V"), new StartInfo( tActivity, EnumSet.of(IntentType.UNKNOWN_TARGET), EnumSet.of(AndroidComponent.ACTIVITY), new int[] {1, 2}, EnumSet.of(StarterFlags.QUENCH_PERMISSIONS))); // android.app.Activity.startIntentSender(IntentSender intent, Intent fillInIntent, int // flagsMask, int flagsValues, int extraFlags) starters.put( /* MethodReference.findOrCreate(tActivity, */ Selector.make( // TODO "startIntentSender(Landroid/content/IntentSender;Landroid/content/Intent;III)V"), new StartInfo( tActivity, EnumSet.of(IntentType.UNKNOWN_TARGET), EnumSet.of(AndroidComponent.ACTIVITY), new int[] {1, 2}, EnumSet.of(StarterFlags.QUENCH_PERMISSIONS))); // android.app.Activity.startIntentSenderForResult(IntentSender intent, int requestCode, // Intent fillInIntent, // int flagsMask, int flagsValues, int extraFlags, Bundle options) starters.put( /* MethodReference.findOrCreate(tActivity, */ Selector.make( // TODO "startIntentSenderForResult(Landroid/content/IntentSender;ILandroid/content/Intent;IIILandroid/os/Bundle;)V"), new StartInfo( tActivity, EnumSet.of(IntentType.UNKNOWN_TARGET), EnumSet.of(AndroidComponent.ACTIVITY), new int[] {1, 2}, EnumSet.of(StarterFlags.CALL_ON_ACTIVITY_RESULT, StarterFlags.QUENCH_PERMISSIONS))); // android.app.Activity.startIntentSenderForResult(IntentSender intent, int requestCode, // Intent fillInIntent, // int flagsMask, int flagsValues, int extraFlags) starters.put( /* MethodReference.findOrCreate(tActivity, */ Selector.make( // TODO "startIntentSenderForResult(Landroid/content/IntentSender;ILandroid/content/Intent;III)V"), new StartInfo( tActivity, EnumSet.of(IntentType.UNKNOWN_TARGET), EnumSet.of(AndroidComponent.ACTIVITY), new int[] {1, 2}, EnumSet.of(StarterFlags.CALL_ON_ACTIVITY_RESULT, StarterFlags.QUENCH_PERMISSIONS))); // android.app.Activity.startIntentSenderFromChild(Activity child, IntentSender intent, int // requestCode, // Intent fillInIntent, int flagsMask, int flagsValues, int extraFlags) starters.put( /* MethodReference.findOrCreate(tActivity, */ Selector.make( // TODO "startIntentSenderFromChild(Landroid/app/Activity;Landroid/content/IntentSender;ILandroid/content/Intent;III)V"), new StartInfo( tActivity, EnumSet.of(IntentType.UNKNOWN_TARGET), EnumSet.of(AndroidComponent.ACTIVITY), new int[] {1, 2}, EnumSet.of(StarterFlags.QUENCH_PERMISSIONS))); // android.app.Activity.startIntentSenderFromChild(Activity child, IntentSender intent, int // requestCode, // Intent fillInIntent, int flagsMask, int flagsValues, int extraFlags, Bundle // options) starters.put( /* MethodReference.findOrCreate(tActivity, */ Selector.make( // TODO "startIntentSenderFromChild(Landroid/app/Activity;Landroid/content/IntentSender;ILandroid/content/Intent;IIILandroid/os/Bundle;)V"), new StartInfo( tActivity, EnumSet.of(IntentType.UNKNOWN_TARGET), EnumSet.of(AndroidComponent.ACTIVITY), new int[] {1, 2}, EnumSet.of(StarterFlags.QUENCH_PERMISSIONS))); } // android.app.Activity.startNextMatchingActivity(Intent intent) starters.put( /* MethodReference.findOrCreate(tActivity, */ Selector.make( "startNextMatchingActivity(Landroid/content/Intent;)Z"), new StartInfo( tActivity, EnumSet.of(IntentType.UNKNOWN_TARGET), EnumSet.of(AndroidComponent.ACTIVITY), new int[] {1})); // android.app.Activity.startActivity(Intent intents, Bundle options) starters.put( /* MethodReference.findOrCreate(tActivity, */ Selector.make( "startNextMatchingActivity(Landroid/content/Intent;Landroid/os/Bundle;)Z"), new StartInfo( tActivity, EnumSet.of(IntentType.UNKNOWN_TARGET), EnumSet.of(AndroidComponent.ACTIVITY), new int[] {1})); if (doFragments) { final TypeReference tFragmentActivity = TypeReference.find(searchLoader, "Landroid/support/v4/app/FragmentActivity"); // android.support.v4.app.FragmentActivity.startActivityForResult(Intent intent, int // requestCode) starters.put( /* MethodReference.findOrCreate(tActivity, */ Selector.make( "startActivityForResult(Landroid/content/Intent;I)Z"), new StartInfo( tFragmentActivity, EnumSet.of(IntentType.UNKNOWN_TARGET), EnumSet.of(AndroidComponent.ACTIVITY), new int[] {1}, EnumSet.of(StarterFlags.CALL_ON_ACTIVITY_RESULT))); // android.support.v4.app.startActivityFromFragment(Fragment fragment, Intent intent, int // requestCode) starters.put( /* MethodReference.findOrCreate(tActivity, */ Selector.make( "startActivityFromFragment(Landroid/app/Fragment;Landroid/content/Intent;I)Z"), new StartInfo( tFragmentActivity, EnumSet.of(IntentType.UNKNOWN_TARGET), EnumSet.of(AndroidComponent.ACTIVITY), new int[] {1})); } } }
40,885
45.146727
146
java
WALA
WALA-master/dalvik/src/main/java/com/ibm/wala/dalvik/ipa/callgraph/propagation/cfa/package-info.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 under the terms listed below. * */ /* * Copyright (c) 2013, * Tobias Blaschke <code@tobiasblaschke.de> * All rights reserved. * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The names of the contributors may not be used to endorse or promote * products derived from this software without specific prior written * permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ /** * Fetch and handle information on Android-Intents. * * <p>Collects the new-Sites of Intents and tries to resolve the parameters to the Intents * constructor. * * <p>When a startComponent-function is encountered this information is used to redirect the call to * an AndroidModel (optionally syntethized at this point). For this to happen a wrapper is * synthesized using AndroidModels getMethodAs- Function. * * <p>If the target could not be determined definitely all components of the application matching * the type of the startComponent-call are invoked. * * <p>The specification on which startComponent-calls are known may be found in IntentStarters. * * <p>A context-free variant of the redirection of startComponent-calls may be found in the * Overrides mentioned below. * * @see com.ibm.wala.dalvik.ipa.callgraph.androidModel.stubs.Overrides * @see com.ibm.wala.dalvik.ipa.callgraph.androidModel.AndroidModel * @see com.ibm.wala.dalvik.ipa.callgraph.androidModel.MiniModel * @see com.ibm.wala.dalvik.ipa.callgraph.androidModel.MicroModel * @see com.ibm.wala.dalvik.ipa.callgraph.androidModel.stubs.UnknownTargetModel * @see com.ibm.wala.dalvik.ipa.callgraph.androidModel.stubs.ExternalModel * @author Tobias Blaschke &lt;code@tobiasblaschke.de&gt; */ package com.ibm.wala.dalvik.ipa.callgraph.propagation.cfa;
3,230
46.514706
100
java
WALA
WALA-master/dalvik/src/main/java/com/ibm/wala/dalvik/ssa/AbstractIntRegisterMachine.java
/* * Copyright (c) 2002 - 2006 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation * Adam Fuchs, Avik Chaudhuri, Steve Suh - Modified from stack to registers */ package com.ibm.wala.dalvik.ssa; import com.ibm.wala.core.util.CancelRuntimeException; import com.ibm.wala.dalvik.classLoader.DexCFG; import com.ibm.wala.dalvik.classLoader.DexCFG.BasicBlock; import com.ibm.wala.dalvik.classLoader.DexConstants; import com.ibm.wala.dalvik.dex.instructions.ArrayGet; import com.ibm.wala.dalvik.dex.instructions.ArrayLength; import com.ibm.wala.dalvik.dex.instructions.ArrayPut; import com.ibm.wala.dalvik.dex.instructions.BinaryOperation; import com.ibm.wala.dalvik.dex.instructions.Branch; import com.ibm.wala.dalvik.dex.instructions.Constant; import com.ibm.wala.dalvik.dex.instructions.GetField; import com.ibm.wala.dalvik.dex.instructions.InstanceOf; import com.ibm.wala.dalvik.dex.instructions.Instruction; import com.ibm.wala.dalvik.dex.instructions.Instruction.Visitor; import com.ibm.wala.dalvik.dex.instructions.Invoke; import com.ibm.wala.dalvik.dex.instructions.Monitor; import com.ibm.wala.dalvik.dex.instructions.New; import com.ibm.wala.dalvik.dex.instructions.PutField; import com.ibm.wala.dalvik.dex.instructions.Switch; import com.ibm.wala.dalvik.dex.instructions.Throw; import com.ibm.wala.dalvik.dex.instructions.UnaryOperation; import com.ibm.wala.dataflow.graph.AbstractMeetOperator; import com.ibm.wala.dataflow.graph.BasicFramework; import com.ibm.wala.dataflow.graph.DataflowSolver; import com.ibm.wala.dataflow.graph.IKilldallFramework; import com.ibm.wala.dataflow.graph.ITransferFunctionProvider; import com.ibm.wala.fixpoint.AbstractStatement; import com.ibm.wala.fixpoint.AbstractVariable; import com.ibm.wala.fixpoint.FixedPointConstants; import com.ibm.wala.fixpoint.IVariable; import com.ibm.wala.fixpoint.UnaryOperator; import com.ibm.wala.shrike.shrikeBT.ArrayLengthInstruction; import com.ibm.wala.shrike.shrikeBT.ConstantInstruction; import com.ibm.wala.shrike.shrikeBT.IArrayLoadInstruction; import com.ibm.wala.shrike.shrikeBT.IArrayStoreInstruction; import com.ibm.wala.shrike.shrikeBT.IBinaryOpInstruction; import com.ibm.wala.shrike.shrikeBT.IGetInstruction; import com.ibm.wala.shrike.shrikeBT.IInvokeInstruction; import com.ibm.wala.shrike.shrikeBT.IPutInstruction; import com.ibm.wala.shrike.shrikeBT.IUnaryOpInstruction; import com.ibm.wala.shrike.shrikeBT.MonitorInstruction; import com.ibm.wala.shrike.shrikeBT.NewInstruction; import com.ibm.wala.shrike.shrikeBT.SwitchInstruction; import com.ibm.wala.shrike.shrikeBT.ThrowInstruction; import com.ibm.wala.util.CancelException; import com.ibm.wala.util.collections.Iterator2Iterable; import com.ibm.wala.util.debug.UnimplementedError; import com.ibm.wala.util.graph.INodeWithNumber; import java.util.Arrays; /** * Skeleton of functionality to propagate information through the Java bytecode stack machine using * ShrikeBT. * * <p>This class computes properties the Java operand stack and of the local variables at the * beginning of each basic block. * * <p>In this implementation, each dataflow variable value is an integer, and the "meeter" object * provides the meets */ @SuppressWarnings("rawtypes") public abstract class AbstractIntRegisterMachine implements FixedPointConstants { private static final boolean DEBUG = false; public static final int TOP = -1; public static final int BOTTOM = -2; public static final int UNANALYZED = -3; public static final int IGNORE = -4; /** The solver */ private DataflowSolver solver; /** The control flow graph to analyze */ private final DexCFG cfg; // /** The max height of the stack. */ // final private int maxStackHeight; /** the max number of locals in play */ protected final int maxLocals; /** Should uninitialized variables be considered TOP (optimistic) or BOTTOM (pessimistic); */ public static final boolean OPTIMISTIC = true; protected AbstractIntRegisterMachine(final DexCFG G) { if (G == null) { throw new IllegalArgumentException("G is null"); } // maxStackHeight = G.getMaxStackHeight(); maxLocals = G.getDexMethod().getMaxLocals(); this.cfg = G; } protected void init(Meeter meeter, final FlowProvider flow) { final MeetOperator meet = new MeetOperator(meeter); ITransferFunctionProvider<BasicBlock, MachineState> xferFunctions = new ITransferFunctionProvider<>() { @Override public boolean hasNodeTransferFunctions() { return flow.needsNodeFlow(); } @Override public boolean hasEdgeTransferFunctions() { return flow.needsEdgeFlow(); } @Override public UnaryOperator<MachineState> getNodeTransferFunction(final BasicBlock node) { return new UnaryOperator<>() { @Override public byte evaluate(MachineState lhs, MachineState rhs) { MachineState exit = lhs; MachineState entry = rhs; MachineState newExit = flow.flow(entry, node); if (newExit.stateEquals(exit)) { return NOT_CHANGED; } else { exit.copyState(newExit); return CHANGED; } } @Override public String toString() { return "NODE-FLOW"; } @Override public int hashCode() { return 9973 * node.hashCode(); } @Override public boolean equals(Object o) { return this == o; } }; } @Override public UnaryOperator<MachineState> getEdgeTransferFunction( final BasicBlock from, final BasicBlock to) { return new UnaryOperator<>() { @Override public byte evaluate(MachineState lhs, MachineState rhs) { MachineState exit = lhs; MachineState entry = rhs; MachineState newExit = flow.flow(entry, from, to); if (newExit.stateEquals(exit)) { return NOT_CHANGED; } else { exit.copyState(newExit); return CHANGED; } } @Override public String toString() { return "EDGE-FLOW"; } @Override public int hashCode() { return 9973 * (from.hashCode() ^ to.hashCode()); } @Override public boolean equals(Object o) { return this == o; } }; } @Override public AbstractMeetOperator<MachineState> getMeetOperator() { return meet; } }; IKilldallFramework<BasicBlock, MachineState> problem = new BasicFramework<>(cfg, xferFunctions); solver = new DataflowSolver<>(problem) { private MachineState entry; @Override protected MachineState makeNodeVariable(BasicBlock n, boolean IN) { assert n != null; MachineState result = new MachineState(n); if (IN && n.equals(cfg.entry())) { entry = result; } return result; } @Override protected MachineState makeEdgeVariable(BasicBlock from, BasicBlock to) { assert from != null; assert to != null; MachineState result = new MachineState(from); return result; } @Override protected void initializeWorkList() { super.buildEquations(false, false); /* * Add only the entry variable to the work list. */ for (INodeWithNumber inn : Iterator2Iterable.make(getFixedPointSystem().getStatementsThatUse(entry))) { AbstractStatement s = (AbstractStatement) inn; addToWorkList(s); } } @Override protected void initializeVariables() { super.initializeVariables(); AbstractIntRegisterMachine.this.initializeVariables(); } @Override protected MachineState[] makeStmtRHS(int size) { return new MachineState[size]; } }; } public boolean solve() { try { return solver.solve(null); } catch (CancelException e) { throw new CancelRuntimeException(e); } } /** Convenience method ... a little ugly .. perhaps delete later. */ protected void initializeVariables() {} public MachineState getEntryState() { return (MachineState) solver.getIn(cfg.entry()); } /** @return the state at the entry to a given block */ public MachineState getIn(BasicBlock bb) { return (MachineState) solver.getIn(bb); } private class MeetOperator extends AbstractMeetOperator<MachineState> { private final Meeter meeter; MeetOperator(Meeter meeter) { this.meeter = meeter; } @Override public boolean isUnaryNoOp() { return false; } @Override public byte evaluate(MachineState lhs, MachineState[] rhs) { BasicBlock bb = lhs.getBasicBlock(); // TODO // Exception e = new Exception("evaluating a MeetOperator"); // e.printStackTrace(); // return NOT_CHANGED; if (!bb.isCatchBlock()) { return meet(lhs, rhs, bb, meeter) ? CHANGED : NOT_CHANGED; } else { return meetForCatchBlock(lhs, rhs, bb, meeter) ? CHANGED : NOT_CHANGED; } } @Override public int hashCode() { return 72223 * meeter.hashCode(); } @Override public boolean equals(Object o) { if (o instanceof MeetOperator) { MeetOperator other = (MeetOperator) o; return meeter.equals(other.meeter); } else { return false; } } @Override public String toString() { return "MEETER"; } } /** * A Meeter object provides the dataflow logic needed to meet the abstract machine state for a * dataflow meet. */ protected interface Meeter { /** * Return the integer that represents the meet of a particular local at the entry to a basic * block. * * @param n The number of the local * @param rhs The values to meet * @param bb The basic block at whose entry this meet occurs * @return The value of local n after the meet. */ int meetLocal(int n, int[] rhs, BasicBlock bb); } /** * Evaluate a meet of machine states. * * <p>TODO: add some efficiency shortcuts. TODO: clean up and refactor. * * @param bb the basic block at whose entry the meet occurs * @return true if the lhs value changes. false otherwise. */ private static boolean meet(IVariable lhs, IVariable[] rhs, BasicBlock bb, Meeter meeter) { // boolean changed = meetStacks(lhs, rhs, bb, meeter); return meetLocals(lhs, rhs, bb, meeter); // return changed; } /** * Evaluate a meet of machine states at a catch block. * * <p>TODO: add some efficiency shortcuts. TODO: clean up and refactor. * * @param bb the basic block at whose entry the meet occurs * @return true if the lhs value changes. false otherwise. */ private static boolean meetForCatchBlock( IVariable lhs, IVariable[] rhs, BasicBlock bb, Meeter meeter) { boolean changed = meetLocals(lhs, rhs, bb, meeter); // int meet = meeter.meetStackAtCatchBlock(bb); // boolean changed = meetLocals(lhs, rhs, bb, meeter); return changed; } // /** // * Evaluate a meet of the stacks of machine states at the entry of a catch block. // * // * <p>TODO: add some efficiency shortcuts. TODO: clean up and refactor. // * // * @param bb the basic block at whose entry the meet occurs // * @return true if the lhs value changes. false otherwise. // */ // private boolean meetStacksAtCatchBlock(IVariable lhs, IBasicBlock<Instruction> bb, Meeter // meeter) { // boolean changed = false; // MachineState L = (MachineState) lhs; // // // evaluate the meet of the stack of height 1, which holds the exception // // object. // // // allocate lhs.stack if it's // // not already allocated. // if (L.stack == null) { // L.allocateStack(); // L.stackHeight = 1; // } // // int meet = meeter.meetStackAtCatchBlock(bb); // if (L.stack[0] == TOP) { // if (meet != TOP) { // changed = true; // L.stack[0] = meet; // } // } else if (meet != L.stack[0]) { // changed = true; // L.stack[0] = meet; // } // return changed; // } // /** // * Evaluate a meet of the stacks of machine states at the entry of a basic block. // * // * <p>TODO: add some efficiency shortcuts. TODO: clean up and refactor. // * // * @param bb the basic block at whose entry the meet occurs // * @return true if the lhs value changes. false otherwise. // */ // private boolean meetStacks(IVariable lhs, IVariable[] rhs, IBasicBlock<Instruction> bb, Meeter // meeter) { // boolean changed = false; // MachineState L = (MachineState) lhs; // // // evaluate the element-wise meet over the stacks // // // first ... how high are the stacks? // int height = computeMeetStackHeight(rhs); // // // if there's any stack height to meet, allocate lhs.stack if it's // // not already allocated. // if (height > -1 && L.stack == null) { // L.allocateStack(); // L.stackHeight = height; // changed = true; // } // // // now do the element-wise meet. // for (int i = 0; i < height; i++) { // int[] R = new int[rhs.length]; // for (int j = 0; j < R.length; j++) { // MachineState m = (MachineState) rhs[j]; // if (m.stack == null) { // R[j] = TOP; // } else { // R[j] = m.stack[i]; // if (R[j] == 0) { // R[j] = TOP; // } // } // } // int meet = meeter.meetStack(i, R, bb); // if (L.stack[i] == TOP) { // if (meet != TOP) { // changed = true; // L.stack[i] = meet; // } // } else if (meet != L.stack[i]) { // changed = true; // L.stack[i] = meet; // } // } // return changed; // } /** * Evaluate a meet of locals of machine states at the entry to a basic block. * * <p>TODO: add some efficiency shortcuts. TODO: clean up and refactor. * * @param bb the basic block at whose entry the meet occurs * @return true if the lhs value changes. false otherwise. */ private static boolean meetLocals(IVariable lhs, IVariable[] rhs, BasicBlock bb, Meeter meeter) { boolean changed = false; MachineState L = (MachineState) lhs; // need we allocate lhs.locals? int nLocals = computeMeetNLocals(rhs); if (nLocals > -1 && L.locals == null) { L.allocateLocals(); changed = true; } // evaluate the element-wise meet over the locals. for (int i = 0; i < nLocals; i++) { int[] R = new int[rhs.length]; for (int j = 0; j < rhs.length; j++) { R[j] = ((MachineState) rhs[j]).getLocal(i); } int meet = meeter.meetLocal(i, R, bb); if (L.locals[i] == TOP) { if (meet != TOP) { changed = true; L.locals[i] = meet; } } else if (meet != L.locals[i]) { changed = true; L.locals[i] = meet; } } return changed; } /** * @return the number of locals to meet. Return -1 if there is no local meet necessary. * @param operands The operands for this operator. operands[0] is the left-hand side. */ private static int computeMeetNLocals(IVariable[] operands) { MachineState lhs = (MachineState) operands[0]; int nLocals = -1; if (lhs.locals != null) { nLocals = lhs.locals.length; } else { for (int i = 1; i < operands.length; i++) { MachineState rhs = (MachineState) operands[i]; if (rhs.locals != null) { nLocals = rhs.locals.length; break; } } } return nLocals; } /** * @return the height of stacks that are being meeted. Return -1 if there is no stack meet * necessary. * @param operands The operands for this operator. operands[0] is the left-hand side. */ @SuppressWarnings("unused") private static int computeMeetStackHeight(IVariable[] operands) { MachineState lhs = (MachineState) operands[0]; int height = -1; if (lhs.stack != null) { height = lhs.stackHeight; } else { for (int i = 1; i < operands.length; i++) { MachineState rhs = (MachineState) operands[i]; if (rhs.stack != null) { height = rhs.stackHeight; break; } } } return height; } /** Representation of the state of the JVM stack machine at some program point. */ public class MachineState extends AbstractVariable<MachineState> { private int[] stack; private int[] locals; // NOTE: stackHeight == -1 is a special code meaning "this variable is TOP" private int stackHeight; private final BasicBlock bb; /** * I'm not using clone because I don't want to necessarily inherit the AbstractVariable state * from the superclass */ public MachineState duplicate() { MachineState result = new MachineState(bb); result.copyState(this); return result; } public MachineState(BasicBlock bb) { setTOP(); this.bb = bb; } public BasicBlock getBasicBlock() { return bb; } void setTOP() { stackHeight = -1; } // public void push(int i) { // if (stack == null) // allocateStack(); // stack[stackHeight++] = i; // } // public int pop() { // if (stackHeight <= 0) { // assert stackHeight > 0 : "can't pop stack of height " + stackHeight; // } // stackHeight -= 1; // return stack[stackHeight]; // } // public int peek() { // return stack[stackHeight - 1]; // } // public void swap() { // int temp = stack[stackHeight - 1]; // stack[stackHeight - 1] = stack[stackHeight - 2]; // stack[stackHeight - 2] = temp; // } // private void allocateStack() { // stack = new int[maxStackHeight + 1]; // stackHeight = 0; // } public void allocateLocals() { locals = allocateNewLocalsArray(); } // public void clearStack() { // stackHeight = 0; // } /** set the value of local i to symbol j */ public void setLocal(int i, int j) { if (locals == null) { if (OPTIMISTIC && (j == TOP)) { return; } else { allocateLocals(); } } locals[i] = j; } /** @return the number of the symbol corresponding to local i */ public int getLocal(int i) { if (locals == null) { if (OPTIMISTIC) { return TOP; } else { return BOTTOM; } } else { return locals[i]; } } public void replaceValue(int from, int to) { if (stack != null) for (int i = 0; i < stackHeight; i++) if (stack[i] == from) stack[i] = to; if (locals != null) for (int i = 0; i < maxLocals; i++) if (locals[i] == from) locals[i] = to; } public boolean hasValue(int val) { if (stack != null) for (int i = 0; i < stackHeight; i++) if (stack[i] == val) return true; if (locals != null) for (int i = 0; i < maxLocals; i++) if (locals[i] == val) return true; return false; } @Override public String toString() { // TODO return "Some machine state..."; // if (isTOP()) { // return "<TOP>@" + System.identityHashCode(this); // } // StringBuffer result = new StringBuilder("<"); // result.append("S"); // if (stackHeight == 0) { // result.append("[empty]"); // } else { // result.append(array2StringBuffer(stack, stackHeight)); // } // result.append("L"); // result.append(array2StringBuffer(locals, maxLocals)); // result.append(">"); // return result.toString(); } // private StringBuffer array2StringBuffer(int[] array, int n) { // StringBuffer result = new StringBuilder("["); // if (array == null) { // result.append(OPTIMISTIC ? "TOP" : "BOTTOM"); // } else { // for (int i = 0; i < n - 1; i++) { // result.append(array[i]).append(","); // } // result.append(array[n - 1]); // } // result.append("]"); // return result; // } @Override public void copyState(MachineState other) { stack = other.stack == null ? null : other.stack.clone(); locals = other.locals == null ? null : other.locals.clone(); stackHeight = other.stackHeight; } boolean stateEquals(MachineState exit) { if (stackHeight != exit.stackHeight) return false; if (locals == null) { if (exit.locals != null) return false; } else { if (exit.locals == null) return false; else if (locals.length != exit.locals.length) return false; } for (int i = 0; i < stackHeight; i++) { if (stack[i] != exit.stack[i]) return false; } if (locals != null) { for (int i = 0; i < locals.length; i++) { if (locals[i] == TOP) { if (exit.locals[i] != TOP) return false; } if (locals[i] != exit.locals[i]) return false; } } return true; } /** * Returns the stackHeight. * * @return int */ public int getStackHeight() { return stackHeight; } /** Use with care. */ public int[] getLocals() { return locals; } } public int[] allocateNewLocalsArray() { int[] result = new int[maxLocals]; Arrays.fill(result, OPTIMISTIC ? TOP : BOTTOM); return result; } /** Interface which defines a flow function for a basic block */ public interface FlowProvider { boolean needsNodeFlow(); boolean needsEdgeFlow(); /** * Compute the MachineState at the exit of a basic block, given a MachineState at the block's * entry. */ MachineState flow(MachineState entry, BasicBlock basicBlock); /** * Compute the MachineState at the end of an edge, given a MachineState at the edges's entry. */ MachineState flow(MachineState entry, BasicBlock from, BasicBlock to); } /** * This gives some basic facilities for shoving things around on the stack. Client analyses should * subclass this as needed. */ protected abstract static class BasicRegisterFlowProvider implements FlowProvider, DexConstants { private final DexCFG cfg; protected MachineState workingState; private BasicRegisterMachineVisitor visitor; private Visitor edgeVisitor; private int currentInstructionIndex = 0; private BasicBlock currentBlock; private BasicBlock currentSuccessorBlock; /** Only subclasses can instantiate */ protected BasicRegisterFlowProvider(DexCFG cfg) { this.cfg = cfg; } /** Initialize the visitors used to perform the flow functions */ protected void init(BasicRegisterMachineVisitor v, Visitor ev) { this.visitor = v; this.edgeVisitor = ev; } @Override public boolean needsNodeFlow() { return true; } @Override public boolean needsEdgeFlow() { return false; } @Override public MachineState flow(MachineState entry, BasicBlock basicBlock) { workingState = entry.duplicate(); currentBlock = basicBlock; currentSuccessorBlock = null; Instruction[] instructions = getInstructions(); if (DEBUG) { System.err.println("Entry to BB" + cfg.getNumber(basicBlock) + ' ' + workingState); } for (int i = basicBlock.getFirstInstructionIndex(); i <= basicBlock.getLastInstructionIndex(); i++) { currentInstructionIndex = i; instructions[i].visit(visitor); if (DEBUG) {} } return workingState; } @Override public MachineState flow(MachineState entry, BasicBlock from, BasicBlock to) { workingState = entry.duplicate(); currentBlock = from; currentSuccessorBlock = to; Instruction[] instructions = getInstructions(); if (DEBUG) { System.err.println("Entry to BB" + cfg.getNumber(from) + ' ' + workingState); } for (int i = from.getFirstInstructionIndex(); i <= from.getLastInstructionIndex(); i++) { currentInstructionIndex = i; instructions[i].visit(edgeVisitor); if (DEBUG) {} } return workingState; } protected int getCurrentInstructionIndex() { return currentInstructionIndex; } protected int getCurrentProgramCounter() { return cfg.getProgramCounter(currentInstructionIndex); } protected BasicBlock getCurrentBlock() { return currentBlock; } protected BasicBlock getCurrentSuccessor() { return currentSuccessorBlock; } public abstract Instruction[] getInstructions(); /** Update the machine state to account for an instruction */ protected static class BasicRegisterMachineVisitor extends Visitor { /** * @see * com.ibm.wala.shrike.shrikeBT.IInstruction.Visitor#visitArrayLength(ArrayLengthInstruction) */ @Override public void visitArrayLength(ArrayLength instruction) { // TODO // workingState.pop(); // workingState.push(UNANALYZED); throw new UnimplementedError(); } /** * @see * com.ibm.wala.shrike.shrikeBT.IInstruction.Visitor#visitArrayLoad(IArrayLoadInstruction) */ @Override public void visitArrayGet(ArrayGet instruction) { // TODO // workingState.pop(); // workingState.pop(); // workingState.push(UNANALYZED); throw new UnimplementedError(); } /** * @see * com.ibm.wala.shrike.shrikeBT.IInstruction.Visitor#visitArrayStore(IArrayStoreInstruction) */ @Override public void visitArrayPut(ArrayPut instruction) { // TODO // workingState.pop(); // workingState.pop(); // workingState.pop(); throw new UnimplementedError(); } /** * @see com.ibm.wala.shrike.shrikeBT.IInstruction.Visitor#visitBinaryOp(IBinaryOpInstruction) */ @Override public void visitBinaryOperation(BinaryOperation instruction) { // TODO // workingState.pop(); throw new UnimplementedError(); } // @Override // public void visitComparison(IComparisonInstruction instruction) { // workingState.pop(); // workingState.pop(); // workingState.push(UNANALYZED); // } @Override public void visitBranch(Branch instruction) { // TODO // workingState.pop(); // workingState.pop(); throw new UnimplementedError(); } /** * @see com.ibm.wala.shrike.shrikeBT.IInstruction.Visitor#visitConstant(ConstantInstruction) */ @Override public void visitConstant(Constant instruction) { // TODO // workingState.push(UNANALYZED); throw new UnimplementedError(); } // @Override // public void visitConversion(IConversionInstruction instruction) { // workingState.pop(); // workingState.push(UNANALYZED); // } // @Override // public void visitDup(DupInstruction instruction) { // // int size = instruction.getSize(); // int delta = instruction.getDelta(); // assert size == 1 || size == 2; // assert delta == 0 || delta == 1 || delta == 2; // int toPop = size + delta; // int v1 = workingState.pop(); // int v2 = (toPop > 1) ? workingState.pop() : IGNORE; // int v3 = (toPop > 2) ? workingState.pop() : IGNORE; // int v4 = (toPop > 3) ? workingState.pop() : IGNORE; // // if (size > 1) { // workingState.push(v2); // } // workingState.push(v1); // if (v4 != IGNORE) { // workingState.push(v4); // } // if (v3 != IGNORE) { // workingState.push(v3); // } // if (v2 != IGNORE) { // workingState.push(v2); // } // workingState.push(v1); // // } /** @see com.ibm.wala.shrike.shrikeBT.IInstruction.Visitor#visitGet(IGetInstruction) */ @Override public void visitGetField(GetField instruction) { // TODO // popN(instruction); // workingState.push(UNANALYZED); throw new UnimplementedError(); } // protected void popN(IInstruction instruction) { // for (int i = 0; i < instruction.getPoppedCount(); i++) { // workingState.pop(); // } // } /** @see com.ibm.wala.shrike.shrikeBT.IInstruction.Visitor#visitInstanceof */ @Override public void visitInstanceof(InstanceOf instruction) { // TODO // workingState.pop(); // workingState.push(UNANALYZED); throw new UnimplementedError(); } /** @see com.ibm.wala.shrike.shrikeBT.IInstruction.Visitor#visitInvoke(IInvokeInstruction) */ @Override public void visitInvoke(Invoke instruction) { // TODO throw new UnimplementedError(); // popN(instruction); // ClassLoaderReference loader = // cfg.getMethod().getDeclaringClass().getClassLoader().getReference(); // TypeReference returnType = ShrikeUtil.makeTypeReference(loader, // Util.getReturnType(instruction.getMethodSignature())); // if (!returnType.equals(TypeReference.Void)) { // workingState.push(UNANALYZED); // } } /** @see com.ibm.wala.shrike.shrikeBT.IInstruction.Visitor#visitMonitor(MonitorInstruction) */ @Override public void visitMonitor(Monitor instruction) { // TODO // workingState.pop(); throw new UnimplementedError(); } // @Override // public void visitLocalLoad(ILoadInstruction instruction) { // int t = workingState.getLocal(instruction.getVarIndex()); // workingState.push(t); // } // @Override // public void visitLocalStore(IStoreInstruction instruction) { // int index = instruction.getVarIndex(); // workingState.setLocal(index, workingState.pop()); // } /** @see com.ibm.wala.shrike.shrikeBT.IInstruction.Visitor#visitNew(NewInstruction) */ @Override public void visitNew(New instruction) { // TODO // popN(instruction); // workingState.push(UNANALYZED); throw new UnimplementedError(); } // @Override // public void visitPop(PopInstruction instruction) { // if (instruction.getPoppedCount() > 0) { // workingState.pop(); // } // } /** @see com.ibm.wala.shrike.shrikeBT.IInstruction.Visitor#visitPut(IPutInstruction) */ @Override public void visitPutField(PutField instruction) { // TODO // popN(instruction); throw new UnimplementedError(); } // @Override // public void visitShift(IShiftInstruction instruction) { // workingState.pop(); // } // @Override // public void visitSwap(SwapInstruction instruction) { // workingState.swap(); // } /** @see com.ibm.wala.shrike.shrikeBT.IInstruction.Visitor#visitSwitch(SwitchInstruction) */ @Override public void visitSwitch(Switch instruction) { // TODO // workingState.pop(); throw new UnimplementedError(); } /** @see com.ibm.wala.shrike.shrikeBT.IInstruction.Visitor#visitThrow(ThrowInstruction) */ @Override public void visitThrow(Throw instruction) { // TODO // int exceptionType = workingState.pop(); // workingState.clearStack(); // workingState.push(exceptionType); throw new UnimplementedError(); } /** * @see com.ibm.wala.shrike.shrikeBT.IInstruction.Visitor#visitUnaryOp(IUnaryOpInstruction) */ @Override public void visitUnaryOperation(UnaryOperation instruction) { // TODO // treated as a no-op in basic scheme throw new UnimplementedError(); } } } }
35,032
31.110907
103
java
WALA
WALA-master/dalvik/src/main/java/com/ibm/wala/dalvik/ssa/DexSSABuilder.java
/* * Copyright (c) 2002 - 2006 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation * Adam Fuchs, Avik Chaudhuri, Steve Suh - Modified from stack to registers */ package com.ibm.wala.dalvik.ssa; import com.ibm.wala.cfg.IBasicBlock; import com.ibm.wala.classLoader.CallSiteReference; import com.ibm.wala.classLoader.Language; import com.ibm.wala.dalvik.classLoader.DexCFG; import com.ibm.wala.dalvik.classLoader.DexCFG.BasicBlock; import com.ibm.wala.dalvik.classLoader.DexIMethod; import com.ibm.wala.dalvik.classLoader.Literal; import com.ibm.wala.dalvik.dex.instructions.ArrayFill; import com.ibm.wala.dalvik.dex.instructions.ArrayGet; import com.ibm.wala.dalvik.dex.instructions.ArrayLength; import com.ibm.wala.dalvik.dex.instructions.ArrayPut; import com.ibm.wala.dalvik.dex.instructions.BinaryLiteralOperation; import com.ibm.wala.dalvik.dex.instructions.BinaryOperation; import com.ibm.wala.dalvik.dex.instructions.Branch; import com.ibm.wala.dalvik.dex.instructions.CheckCast; import com.ibm.wala.dalvik.dex.instructions.Constant; import com.ibm.wala.dalvik.dex.instructions.GetField; import com.ibm.wala.dalvik.dex.instructions.Goto; import com.ibm.wala.dalvik.dex.instructions.InstanceOf; import com.ibm.wala.dalvik.dex.instructions.Instruction; import com.ibm.wala.dalvik.dex.instructions.Instruction.Visitor; import com.ibm.wala.dalvik.dex.instructions.Invoke; import com.ibm.wala.dalvik.dex.instructions.Monitor; import com.ibm.wala.dalvik.dex.instructions.New; import com.ibm.wala.dalvik.dex.instructions.NewArray; import com.ibm.wala.dalvik.dex.instructions.NewArrayFilled; import com.ibm.wala.dalvik.dex.instructions.PutField; import com.ibm.wala.dalvik.dex.instructions.Return; import com.ibm.wala.dalvik.dex.instructions.Switch; import com.ibm.wala.dalvik.dex.instructions.Throw; import com.ibm.wala.dalvik.dex.instructions.UnaryOperation; import com.ibm.wala.shrike.shrikeBT.ArrayLengthInstruction; import com.ibm.wala.shrike.shrikeBT.ConstantInstruction; import com.ibm.wala.shrike.shrikeBT.GotoInstruction; import com.ibm.wala.shrike.shrikeBT.IArrayLoadInstruction; import com.ibm.wala.shrike.shrikeBT.IArrayStoreInstruction; import com.ibm.wala.shrike.shrikeBT.IBinaryOpInstruction; import com.ibm.wala.shrike.shrikeBT.IGetInstruction; import com.ibm.wala.shrike.shrikeBT.IInvokeInstruction; import com.ibm.wala.shrike.shrikeBT.IUnaryOpInstruction; import com.ibm.wala.shrike.shrikeBT.MonitorInstruction; import com.ibm.wala.shrike.shrikeBT.NewInstruction; import com.ibm.wala.shrike.shrikeBT.ReturnInstruction; import com.ibm.wala.shrike.shrikeBT.SwitchInstruction; import com.ibm.wala.shrike.shrikeBT.ThrowInstruction; import com.ibm.wala.ssa.IR; import com.ibm.wala.ssa.ISSABasicBlock; import com.ibm.wala.ssa.PhiValue; import com.ibm.wala.ssa.SSAAbstractInvokeInstruction; import com.ibm.wala.ssa.SSACFG; import com.ibm.wala.ssa.SSACFG.ExceptionHandlerBasicBlock; import com.ibm.wala.ssa.SSAConditionalBranchInstruction; import com.ibm.wala.ssa.SSAGetCaughtExceptionInstruction; import com.ibm.wala.ssa.SSAInstruction; import com.ibm.wala.ssa.SSAInstructionFactory; import com.ibm.wala.ssa.SSAInvokeInstruction; import com.ibm.wala.ssa.SSALoadMetadataInstruction; import com.ibm.wala.ssa.SSAPhiInstruction; import com.ibm.wala.ssa.SSAPiInstruction; import com.ibm.wala.ssa.SSAPiNodePolicy; import com.ibm.wala.ssa.ShrikeIndirectionData; import com.ibm.wala.ssa.SymbolTable; import com.ibm.wala.types.ClassLoaderReference; import com.ibm.wala.types.FieldReference; import com.ibm.wala.types.MethodReference; import com.ibm.wala.types.TypeReference; import com.ibm.wala.util.collections.Pair; import com.ibm.wala.util.debug.Assertions; import com.ibm.wala.util.graph.dominators.Dominators; import com.ibm.wala.util.intset.IntPair; import java.util.Arrays; import java.util.Iterator; /** * This class constructs an SSA {@link IR} from a backing ShrikeBT instruction stream. * * <p>The basic algorithm here is an abstract interpretation over the Java bytecode to determine * types of stack locations and local variables. As a side effect, the flow functions of the * abstract interpretation emit instructions, eliminating the stack abstraction and moving to a * register-transfer language in SSA form. */ public class DexSSABuilder extends AbstractIntRegisterMachine { public static DexSSABuilder make( DexIMethod method, SSACFG cfg, DexCFG scfg, SSAInstruction[] instructions, SymbolTable symbolTable, boolean buildLocalMap, SSAPiNodePolicy piNodePolicy) throws IllegalArgumentException { if (scfg == null) { throw new IllegalArgumentException("scfg == null"); } return new DexSSABuilder( method, cfg, scfg, instructions, symbolTable, buildLocalMap, piNodePolicy); } /** A wrapper around the method being analyzed. */ private final DexIMethod method; /** Governing symbol table */ private final SymbolTable symbolTable; /** * A logical mapping from &lt;bcIndex, valueNumber&gt; -&gt; local number if null, don't build it. */ private final SSA2LocalMap localMap; /** a factory to create concrete instructions */ private final SSAInstructionFactory insts; /** information about indirect use of local variables in the bytecode */ // private final IndirectionData bytecodeIndirections; private final ShrikeIndirectionData shrikeIndirections; private DexSSABuilder( DexIMethod method, SSACFG cfg, DexCFG scfg, SSAInstruction[] instructions, SymbolTable symbolTable, boolean buildLocalMap, SSAPiNodePolicy piNodePolicy) { super(scfg); localMap = buildLocalMap ? new SSA2LocalMap( scfg, instructions.length, cfg.getNumberOfNodes(), method.getMaxLocals()) : null; init( new SymbolTableMeeter(cfg, scfg), new SymbolicPropagator(scfg, instructions, cfg, piNodePolicy)); this.method = method; this.symbolTable = symbolTable; this.insts = method.getDeclaringClass().getClassLoader().getInstructionFactory(); // this.bytecodeIndirections = method.getIndirectionData(); this.shrikeIndirections = new ShrikeIndirectionData(instructions.length); assert cfg != null : "Null CFG"; } private class SymbolTableMeeter implements Meeter { final SSACFG cfg; final DexCFG dexCFG; SymbolTableMeeter(SSACFG cfg, DexCFG dexCFG) { this.cfg = cfg; // this.instructions = instructions; this.dexCFG = dexCFG; } // public int meetStack(int slot, int[] rhs, IBasicBlock<Instruction> bb) { // // assert bb != null : "null basic block"; // // if (bb.isExitBlock()) { // return TOP; // } // // if (allTheSame(rhs)) { // for (int i = 0; i < rhs.length; i++) { // if (rhs[i] != TOP) { // return rhs[i]; // } // } // // didn't find anything but TOP // return TOP; // } else { // SSACFG.BasicBlock newBB = cfg.getNode(dexCFG.getNumber(bb)); // // if we already have a phi for this stack location // SSAPhiInstruction phi = newBB.getPhiForStackSlot(slot); // int result; // if (phi == null) { // // no phi already exists. create one. // result = symbolTable.newPhi(rhs); // PhiValue v = symbolTable.getPhiValue(result); // phi = v.getPhiInstruction(); // newBB.addPhiForStackSlot(slot, phi); // } else { // // already created a phi. update it to account for the // // new merge. // result = phi.getDef(); // phi.setValues(rhs.clone()); // } // return result; // } // } @Override public int meetLocal(int n, int[] rhs, DexCFG.BasicBlock bb) { if (allTheSame(rhs)) { for (int rh : rhs) { if (rh != TOP) { return rh; } } // didn't find anything but TOP return TOP; } else { SSACFG.BasicBlock newBB = cfg.getNode(dexCFG.getNumber(bb)); if (bb.isExitBlock()) { // no phis in exit block please return TOP; } // if we already have a phi for this local SSAPhiInstruction phi = newBB.getPhiForLocal(n); int result; if (phi == null) { // no phi already exists. create one. result = symbolTable.newPhi(rhs); PhiValue v = symbolTable.getPhiValue(result); phi = v.getPhiInstruction(); newBB.addPhiForLocal(n, phi); } else { // already created a phi. update it to account for the // new merge. result = phi.getDef(); phi.setValues(rhs.clone()); } return result; } } /** * Are all rhs values all the same? Note, we consider TOP (-1) to be same as everything else. * * @return boolean */ private boolean allTheSame(int[] rhs) { int x = -1; // set x := the first non-TOP value int i = 0; for (i = 0; i < rhs.length; i++) { if (rhs[i] != TOP) { x = rhs[i]; break; } } // check the remaining values for (i++; i < rhs.length; i++) { if (rhs[i] != x && rhs[i] != TOP) return false; } return true; } } @Override protected void initializeVariables() { MachineState entryState = getEntryState(); int parameterNumber = 0; // added -2 to account for the return and exception register // int local = method.getMaxLocals() - method.getNumberOfParameters() - 1 - 2; // can't use just getNumberOfParameters because it does not account for Long/Wide variables // which take up 2 registers // as the parameter int local = method.getMaxLocals() - method.getNumberOfParameterRegisters() - 1 - 2; // MyLogger.log(LogLevel.DEBUG, "DexSSABuilder - initializeVariables() - local: " + local); // initialize the "this" parameter if it needs to be set. // the "this" parameter will be symbol number 1 in a virtual method. // if (method.getMaxLocals() - method.getNumberOfParameters() - 2 > 0) // entryState.setLocal(local, 1); // System.out.println("visiting initalizeVartiables()"); // if (method.isStatic()) // System.out.println("Static"); // if (method.isClinit()) // System.out.println("Clinit"); // System.out.println("GetNumberOfParameter: " + method.getNumberOfParameterRegisters()); // System.out.println("Total Registers: " + (method.getMaxLocals()-2)); // System.out.println("local: " + local); // if (local >= 0) { // System.out.println("Max Registers: " + (int)(method.getMaxLocals() - 2)); // System.out.println("Parameters: " + method.getNumberOfParameters()); // System.out.println("Setting Entry State, local:"+ local + " with 1"); // entryState.setLocal(local, 1); // } // System.out.println("Max Registers: " + (int)(method.getMaxLocals() - 2)); // System.out.println("Parameters: " + method.getNumberOfParameters()); entryState.allocateLocals(); for (int i = 0; i < method.getNumberOfParameters(); i++) { local++; TypeReference t = method.getParameterType(i); if (t != null) { int symbol = symbolTable.getParameter(parameterNumber++); entryState.setLocal(local, symbol); if (t.equals(TypeReference.Double) || t.equals(TypeReference.Long)) { local++; entryState.setLocal(local, symbol); } } } // MyLogger.log(LogLevel.DEBUG, "DexSSABuilder - initializeVariables() - local: " + local); // This useless value ensures that the state cannot be empty, even // for a static method with no arguments in blocks with an empty stack // and no locals being used. This ensures that propagation of the // state thru the CFGSystem will always show changes the first time // it reaches a block, and thus no piece of the CFG will be skipped. // // (note that this bizarre state really happened, in java_cup) // // SJF: I don't understand how this is supposed to work. It // causes a bug right now in normal cases, so I'm commenting it out // for now. If there's a problem, let's add a regression test // to catch it. // // TODO: if there's no stack do we need this? // entryState.push(symbolTable.newSymbol()); } /** * This class defines the type abstractions for this analysis and the flow function for each * instruction in the ShrikeBT IR. */ private class SymbolicPropagator extends BasicRegisterFlowProvider { final SSAInstruction[] instructions; final DexCFG dexCFG; final SSACFG cfg; final ClassLoaderReference loader; /** creators[i] holds the instruction that defs value number i */ private SSAInstruction[] creators; // final SSA2LocalMap localMap; final SSAPiNodePolicy piNodePolicy; public SymbolicPropagator( DexCFG dexCFG, SSAInstruction[] instructions, SSACFG cfg, SSAPiNodePolicy piNodePolicy) { super(dexCFG); this.piNodePolicy = piNodePolicy; this.cfg = cfg; this.creators = new SSAInstruction[0]; this.dexCFG = dexCFG; this.instructions = instructions; this.loader = dexCFG.getMethod().getDeclaringClass().getClassLoader().getReference(); // this.localMap = localMap; init(this.new NodeVisitor(cfg), this.new EdgeVisitor()); } @Override public boolean needsEdgeFlow() { return piNodePolicy != null; } private void emitInstruction(SSAInstruction s) { instructions[getCurrentInstructionIndex()] = s; for (int i = 0; i < s.getNumberOfDefs(); i++) { if (creators.length < (s.getDef(i) + 1)) { creators = Arrays.copyOf(creators, 2 * s.getDef(i)); } assert s.getDef(i) != -1 : "invalid def " + i + " for " + s; creators[s.getDef(i)] = s; } } private SSAInstruction getCurrentInstruction() { return instructions[getCurrentInstructionIndex()]; } /** * If we've already created the current instruction, return the value number def'ed by the * current instruction. Else, create a new symbol. */ private int reuseOrCreateDef() { if (getCurrentInstruction() == null || !getCurrentInstruction().hasDef()) { return symbolTable.newSymbol(); } else { return getCurrentInstruction().getDef(); } } /** * If we've already created the current instruction, return the value number representing the * exception the instruction may throw. Else, create a new symbol */ private int reuseOrCreateException() { if (getCurrentInstruction() != null) { assert getCurrentInstruction() instanceof SSAInvokeInstruction; } if (getCurrentInstruction() == null) { return symbolTable.newSymbol(); } else { SSAInvokeInstruction s = (SSAInvokeInstruction) getCurrentInstruction(); return s.getException(); } } /** Update the machine state to account for an instruction */ class NodeVisitor extends BasicRegisterMachineVisitor { private final SSACFG cfg; public NodeVisitor(SSACFG cfg) { this.cfg = cfg; } // TODO: make sure all visit functions are overridden /** * @see * com.ibm.wala.shrike.shrikeBT.IInstruction.Visitor#visitArrayLength(ArrayLengthInstruction) */ @Override public void visitArrayLength(ArrayLength instruction) { int arrayRef = workingState.getLocal(instruction.source); int dest = instruction.destination; int length = reuseOrCreateDef(); setLocal(dest, length); emitInstruction( insts.ArrayLengthInstruction(getCurrentInstructionIndex(), length, arrayRef)); } /** * @see * com.ibm.wala.shrike.shrikeBT.IInstruction.Visitor#visitArrayLoad(IArrayLoadInstruction) */ @Override public void visitArrayGet(ArrayGet instruction) { int index = workingState.getLocal(instruction.offset); int arrayRef = workingState.getLocal(instruction.array); int dest = instruction.destination; // int index = workingState.pop(); // int arrayRef = workingState.pop(); int result = reuseOrCreateDef(); setLocal(dest, result); // workingState.push(result); TypeReference t = instruction.getType(); // if (instruction.isAddressOf()) { // emitInstruction(insts.AddressOfInstruction(result, arrayRef, index, t)); // } else { emitInstruction( insts.ArrayLoadInstruction(getCurrentInstructionIndex(), result, arrayRef, index, t)); // } } /** * @see * com.ibm.wala.shrike.shrikeBT.IInstruction.Visitor#visitArrayStore(IArrayStoreInstruction) */ @Override public void visitArrayPut(ArrayPut instruction) { int value = workingState.getLocal(instruction.source); int index = workingState.getLocal(instruction.offset); int arrayRef = workingState.getLocal(instruction.array); TypeReference t = instruction.getType(); // System.out.println(t.getName().toString()); // int value = workingState.pop(); // int index = workingState.pop(); // int arrayRef = workingState.pop(); // TypeReference t = ShrikeUtil.makeTypeReference(loader, // instruction.getType()); emitInstruction( insts.ArrayStoreInstruction(getCurrentInstructionIndex(), arrayRef, index, value, t)); } @Override public void visitArrayFill(ArrayFill instruction) { Iterator<Number> iae = instruction.getTable().getArrayElements().iterator(); int i = 0; while (iae.hasNext()) { Number ae = iae.next(); int index = symbolTable.getConstant(i); int arrayRef = workingState.getLocal(instruction.array); TypeReference t = instruction.getType(); // System.out.println(t.getName().toString()); int value; // // System.out.println("Index: " + ae.bufferIndex + ", Width: " + // ae.elementWidth + ", Value: " + byte_buffer.getSomethingDependingonType ); // okay to call the getConstant(String) for a char? if (t.equals(TypeReference.Char)) value = symbolTable.getConstant((char) ae.intValue()); else if (t.equals(TypeReference.Byte)) value = symbolTable.getConstant(ae.byteValue()); else if (t.equals(TypeReference.Short)) value = symbolTable.getConstant(ae.shortValue()); else if (t.equals(TypeReference.Int)) value = symbolTable.getConstant(ae.intValue()); else if (t.equals(TypeReference.Long)) value = symbolTable.getConstant(ae.longValue()); else if (t.equals(TypeReference.Float)) value = symbolTable.getConstant(ae.floatValue()); else if (t.equals(TypeReference.Double)) value = symbolTable.getConstant(ae.doubleValue()); else if (t.equals(TypeReference.Boolean)) value = symbolTable.getConstant(ae.intValue() != 0); else { value = 0; } emitInstruction( insts.ArrayStoreInstruction(getCurrentInstructionIndex(), arrayRef, index, value, t)); // System.out.println("Index: " + t.bufferIndex + ", Value: " + // t.buffer[t.bufferIndex]); i++; } } /** * @see com.ibm.wala.shrike.shrikeBT.IInstruction.Visitor#visitBinaryOp(IBinaryOpInstruction) */ @Override public void visitBinaryOperation(BinaryOperation instruction) { int val2 = workingState.getLocal(instruction.oper2); int val1 = workingState.getLocal(instruction.oper1); int dest = instruction.destination; // int val2 = workingState.pop(); // int val1 = workingState.pop(); int result = reuseOrCreateDef(); setLocal(dest, result); // workingState.push(result); // boolean isFloat = instruction.getType().equals(TYPE_double) || // instruction.getType().equals(TYPE_float); emitInstruction( insts.BinaryOpInstruction( getCurrentInstructionIndex(), instruction.getOperator(), false, instruction.isUnsigned(), result, val1, val2, !instruction.isFloat())); } /** * @see com.ibm.wala.shrike.shrikeBT.IInstruction.Visitor#visitBinaryOp(IBinaryOpInstruction) */ @Override public void visitBinaryLiteral(BinaryLiteralOperation instruction) { // int val2 = workingState.getLocal(instruction.oper2); Literal lit = instruction.oper2; int val2; if (lit instanceof Literal.IntLiteral) val2 = symbolTable.getConstant(((Literal.IntLiteral) lit).value); else if (lit instanceof Literal.LongLiteral) val2 = symbolTable.getConstant(((Literal.LongLiteral) lit).value); else if (lit instanceof Literal.DoubleLiteral) val2 = symbolTable.getConstant(((Literal.DoubleLiteral) lit).value); else val2 = symbolTable.getConstant(((Literal.FloatLiteral) lit).value); int val1 = workingState.getLocal(instruction.oper1); int dest = instruction.destination; // int val2 = workingState.pop(); // int val1 = workingState.pop(); int result = reuseOrCreateDef(); setLocal(dest, result); // workingState.push(result); // boolean isFloat = instruction.getType().equals(TYPE_double) || // instruction.getType().equals(TYPE_float); try { if (instruction.isSub()) emitInstruction( insts.BinaryOpInstruction( getCurrentInstructionIndex(), instruction.getOperator(), false, instruction.isUnsigned(), result, val2, val1, !instruction.isFloat())); else emitInstruction( insts.BinaryOpInstruction( getCurrentInstructionIndex(), instruction.getOperator(), false, instruction.isUnsigned(), result, val1, val2, !instruction.isFloat())); } catch (AssertionError e) { System.err.println("When visiting Instuction " + instruction); throw e; } } protected void setLocal(int dest, int result) { assert result <= symbolTable.getMaxValueNumber(); workingState.setLocal(dest, result); } /** @see com.ibm.wala.shrike.shrikeBT.IInstruction.Visitor#visitCheckCast */ @Override public void visitCheckCast(CheckCast instruction) { int val = workingState.getLocal(instruction.object); // int val = workingState.pop(); // dex does not use this result, but we need it for the SSA CheckCastInstruction int result = reuseOrCreateDef(); workingState.setLocal(instruction.object, result); // workingState.push(result); // TypeReference t = instruction.getType(); emitInstruction( insts.CheckCastInstruction( getCurrentInstructionIndex(), result, val, instruction.type, instruction.isPEI())); } @Override public void visitBranch(Branch instruction) { if (instruction instanceof Branch.BinaryBranch) { Branch.BinaryBranch bbranch = (Branch.BinaryBranch) instruction; int val2 = workingState.getLocal(bbranch.oper2); int val1 = workingState.getLocal(bbranch.oper1); // int val2 = workingState.pop(); // int val1 = workingState.pop(); TypeReference t = TypeReference.Int; emitInstruction( insts.ConditionalBranchInstruction( getCurrentInstructionIndex(), instruction.getOperator(), t, val1, val2, -1)); } else if (instruction instanceof Branch.UnaryBranch) { Branch.UnaryBranch ubranch = (Branch.UnaryBranch) instruction; int val2 = symbolTable.getConstant(0); int val1 = workingState.getLocal(ubranch.oper1); TypeReference t = TypeReference.Int; emitInstruction( insts.ConditionalBranchInstruction( getCurrentInstructionIndex(), instruction.getOperator(), t, val1, val2, -1)); } else { throw new IllegalArgumentException("instruction is of an unknown subtype of Branch"); } } /** * @see com.ibm.wala.shrike.shrikeBT.IInstruction.Visitor#visitConstant(ConstantInstruction) */ @Override public void visitConstant(Constant instruction) { int dest = instruction.destination; int symbol = 0; if (instruction instanceof Constant.ClassConstant) { Constant.ClassConstant constInst = (Constant.ClassConstant) instruction; // TODO: change to a symbol that represents the given IClass // symbol = // symbolTable.getConstant(((Constant.ClassConstant)instruction).value); symbol = reuseOrCreateDef(); TypeReference typeRef = constInst.value; SSALoadMetadataInstruction s = insts.LoadMetadataInstruction( getCurrentInstructionIndex(), symbol, TypeReference.JavaLangClass, typeRef); emitInstruction(s); } else if (instruction instanceof Constant.IntConstant) { symbol = symbolTable.getConstant(((Constant.IntConstant) instruction).value); } else if (instruction instanceof Constant.LongConstant) { symbol = symbolTable.getConstant(((Constant.LongConstant) instruction).value); } else if (instruction instanceof Constant.StringConstant) { symbol = symbolTable.getConstant(((Constant.StringConstant) instruction).value); } else { Assertions.UNREACHABLE("unexpected constant instruction " + instruction); } setLocal(dest, symbol); // Language l = // cfg.getMethod().getDeclaringClass().getClassLoader().getLanguage(); // TypeReference type = l.getConstantType(instruction.getValue()); // int symbol = 0; // if (l.isNullType(type)) { // symbol = symbolTable.getNullConstant(); // } else if (l.isIntType(type)) { // Integer value = (Integer) instruction.getValue(); // symbol = symbolTable.getConstant(value.intValue()); // } else if (l.isLongType(type)) { // Long value = (Long) instruction.getValue(); // symbol = symbolTable.getConstant(value.longValue()); // } else if (l.isFloatType(type)) { // Float value = (Float) instruction.getValue(); // symbol = symbolTable.getConstant(value.floatValue()); // } else if (l.isDoubleType(type)) { // Double value = (Double) instruction.getValue(); // symbol = symbolTable.getConstant(value.doubleValue()); // } else if (l.isStringType(type)) { // String value = (String) instruction.getValue(); // symbol = symbolTable.getConstant(value); // } else if (l.isMetadataType(type)) { // Object rval = l.getMetadataToken(instruction.getValue()); // symbol = reuseOrCreateDef(); // emitInstruction(insts.LoadMetadataInstruction(symbol, type, rval)); // } else { // Assertions.UNREACHABLE("unexpected " + type); // } // workingState.push(symbol); } // TODO: is this just a unary operation? // @Override // public void visitConversion(IConversionInstruction instruction) { // // int val = workingState.pop(); // int result = reuseOrCreateDef(); // workingState.push(result); // // TypeReference fromType = ShrikeUtil.makeTypeReference(loader, // instruction.getFromType()); // TypeReference toType = ShrikeUtil.makeTypeReference(loader, // instruction.getToType()); // // emitInstruction(insts.ConversionInstruction(result, val, fromType, toType, // instruction.throwsExceptionOnOverflow())); // } /** @see com.ibm.wala.shrike.shrikeBT.IInstruction.Visitor#visitGet(IGetInstruction) */ @Override public void visitGetField(GetField instruction) { int dest = instruction.destination; int result = reuseOrCreateDef(); FieldReference f = FieldReference.findOrCreate( loader, instruction.clazzName, instruction.fieldName, instruction.fieldType); // TODO: what is isAddressOf()? // shouldn't matter, java doesn't allow isAddressOf() if (instruction instanceof GetField.GetInstanceField) { int instance = workingState.getLocal(((GetField.GetInstanceField) instruction).instance); emitInstruction(insts.GetInstruction(getCurrentInstructionIndex(), result, instance, f)); } else if (instruction instanceof GetField.GetStaticField) { emitInstruction(insts.GetInstruction(getCurrentInstructionIndex(), result, f)); } else { throw new IllegalArgumentException("unknown subclass of GetField: " + instruction); } // if (instruction.isAddressOf()) { // int ref = instruction.isStatic()? -1: workingState.pop(); // emitInstruction(insts.AddressOfInstruction(result, ref, f, // f.getFieldType())); // } else if (instruction.isStatic()) { // emitInstruction(insts.GetInstruction(result, f)); // } else { // int ref = workingState.pop(); // emitInstruction(insts.GetInstruction(result, ref, f)); // } setLocal(dest, result); // workingState.push(result); } /** @see com.ibm.wala.shrike.shrikeBT.IInstruction.Visitor#visitGoto(GotoInstruction) */ @Override public void visitGoto(Goto instruction) { emitInstruction( insts.GotoInstruction(getCurrentInstructionIndex(), instruction.destination)); } /** @see com.ibm.wala.shrike.shrikeBT.IInstruction.Visitor#visitInstanceof */ @Override public void visitInstanceof(InstanceOf instruction) { int ref = workingState.getLocal(instruction.source); int dest = instruction.destination; // int ref = workingState.pop(); int result = reuseOrCreateDef(); setLocal(dest, result); // workingState.push(result); // TypeReference t = ShrikeUtil.makeTypeReference(loader, // instruction.getType()); emitInstruction( insts.InstanceofInstruction( getCurrentInstructionIndex(), result, ref, instruction.type)); } /** @see com.ibm.wala.shrike.shrikeBT.IInstruction.Visitor#visitInvoke(IInvokeInstruction) */ @Override public void visitInvoke(Invoke instruction) { // TODO: can other methods do indirect reads from a dex method? // // doIndirectReads(bytecodeIndirections.indirectlyReadLocals(getCurrentInstructionIndex())); // int n = instruction.getPoppedCount(); // int n = instruction.args.length; // int[] params = new int[n]; // for (int i = n - 1; i >= 0; i--) { // params[i] = workingState.pop(); // } Language lang = dexCFG.getMethod().getDeclaringClass().getClassLoader().getLanguage(); // TODO: check that the signature needed by findOrCreate can use the descriptor MethodReference m = MethodReference.findOrCreate( lang, loader, instruction.clazzName, instruction.methodName, instruction.descriptor); // ((DexIClass)dexCFG.getDexMethod().getDeclaringClass()).getSuperclass().get // MethodReference m = // ((DexIClass)dexCFG.getDexMethod().getDeclaringClass()).loader.lookupClass(TypeName.findOrCreate(instruction.clazzName)). // this.myClass.loader.lookupClass(TypeName.findOrCreate(cname)), // ((Instruction21c)inst).getRegisterA())); IInvokeInstruction.IDispatch code = instruction.getInvocationCode(); CallSiteReference site = CallSiteReference.make(getCurrentProgramCounter(), m, code); int exc = reuseOrCreateException(); setLocal(dexCFG.getDexMethod().getExceptionReg(), exc); int n = instruction.args.length; for (int i = 0; i < m.getNumberOfParameters(); i++) if (m.getParameterType(i) == TypeReference.Double || m.getParameterType(i) == TypeReference.Long) n--; int[] params = new int[n]; int arg_i = 0; // there is no "this" parameter when calling this invoke call if (n == m.getNumberOfParameters()) { for (int i = 0; i < n; i++) { params[i] = workingState.getLocal(instruction.args[arg_i]); if (m.getParameterType(i) == TypeReference.Double || m.getParameterType(i) == TypeReference.Long) arg_i++; arg_i++; } } // there is a "this" parameter in this invoke call else if (n == m.getNumberOfParameters() + 1) { params[0] = workingState.getLocal(instruction.args[0]); arg_i = 1; for (int i = 0; i < (n - 1); i++) { params[i + 1] = workingState.getLocal(instruction.args[arg_i]); if (m.getParameterType(i) == TypeReference.Double || m.getParameterType(i) == TypeReference.Long) arg_i++; arg_i++; } } // this should not happen else throw new UnsupportedOperationException("visitInvoke DexSSABuilder, error"); if (m.getReturnType().equals(TypeReference.Void)) { SSAInstruction inst = insts.InvokeInstruction(getCurrentInstructionIndex(), params, exc, site, null); // System.out.println("Emitting(1) InvokeInstruction: "+inst); emitInstruction(inst); } else { int result = reuseOrCreateDef(); assert result != -1; // TODO: check that this return register is correct // I think it be registerCount() or registerCount()+1 // int dest = dexCFG.getDexMethod().regBank.getReturnReg().regID; int dest = dexCFG.getDexMethod().getReturnReg(); setLocal(dest, result); SSAInstruction inst = insts.InvokeInstruction( getCurrentInstructionIndex(), result, params, exc, site, null); // System.out.println("Emitting(2) InvokeInstruction: "+inst); emitInstruction(inst); } // if (instruction.getPushedWordSize() > 0) { // int result = reuseOrCreateDef(); // workingState.push(result); // emitInstruction(insts.InvokeInstruction(result, params, exc, site)); // } else { // emitInstruction(insts.InvokeInstruction(params, exc, site)); // } // TODO: can other methods do indirect writes to a dex method? // // doIndirectWrites(bytecodeIndirections.indirectlyWrittenLocals(getCurrentInstructionIndex()), -1); } // Dex doesn't have local load or store // @Override // public void visitLocalLoad(ILoadInstruction instruction) { // if (instruction.isAddressOf()) { // int result = reuseOrCreateDef(); // // int t = workingState.getLocal(instruction.getVarIndex()); // if (t == -1) { // doIndirectWrites(new int[]{instruction.getVarIndex()}, -1); // t = workingState.getLocal(instruction.getVarIndex()); // } // // TypeReference type = ShrikeUtil.makeTypeReference(loader, // instruction.getType()); // emitInstruction(insts.AddressOfInstruction(result, t, type)); // workingState.push(result); // } else { // super.visitLocalLoad(instruction); // } // } // // /* // * @see // com.ibm.wala.shrikeBT.IInstruction.Visitor#visitLocalStore(com.ibm.wala.shrikeBT.StoreInstruction) // */ // @Override // public void visitLocalStore(IStoreInstruction instruction) { // if (localMap != null) { // localMap.startRange(getCurrentInstructionIndex(), // instruction.getVarIndex(), workingState.peek()); // } // super.visitLocalStore(instruction); // } /** @see com.ibm.wala.shrike.shrikeBT.IInstruction.Visitor#visitMonitor(MonitorInstruction) */ @Override public void visitMonitor(Monitor instruction) { int ref = workingState.getLocal(instruction.object); // int ref = workingState.pop(); emitInstruction( insts.MonitorInstruction(getCurrentInstructionIndex(), ref, instruction.enter)); } /** @see com.ibm.wala.shrike.shrikeBT.IInstruction.Visitor#visitNew(NewInstruction) */ @Override public void visitNew(New instruction) { int dest = instruction.destination; int result = reuseOrCreateDef(); // TypeReference t = ShrikeUtil.makeTypeReference(loader, // instruction.getType()); // NewSiteReference ref = NewSiteReference.make(getCurrentProgramCounter(), t); // if (t.isArrayType()) { // int[] sizes = new int[instruction.getArrayBoundsCount()]; // for (int i = 0; i < instruction.getArrayBoundsCount(); i++) { // sizes[instruction.getArrayBoundsCount() - 1 - i] = // workingState.pop(); // } // emitInstruction(insts.NewInstruction(result, ref, sizes)); // } else { emitInstruction( insts.NewInstruction(getCurrentInstructionIndex(), result, instruction.newSiteRef)); // popN(instruction); // } setLocal(dest, result); // workingState.push(result); } @Override public void visitNewArray(NewArray instruction) { int dest = instruction.destination; int result = reuseOrCreateDef(); int[] sizes = new int[instruction.sizes.length]; for (int i = 0; i < instruction.sizes.length; i++) { sizes[i] = workingState.getLocal(instruction.sizes[i]); } emitInstruction( insts.NewInstruction( getCurrentInstructionIndex(), result, instruction.newSiteRef, sizes)); setLocal(dest, result); } @Override public void visitNewArrayFilled(NewArrayFilled instruction) { int dest = instruction.destination; int result = reuseOrCreateDef(); int[] sizes = new int[instruction.sizes.length]; for (int i = 0; i < instruction.sizes.length; i++) { sizes[i] = symbolTable.getConstant(instruction.sizes[i]); } emitInstruction( insts.NewInstruction( getCurrentInstructionIndex(), result, instruction.newSiteRef, sizes)); setLocal(dest, result); /* * we need to emit these instructions somehow, but for now this clobbers the emitInstruction mechanism * for (int i = 0; i < instruction.args.length; i++) { int value = workingState.getLocal(instruction.args[i]); int index = symbolTable.getConstant(i); int arrayRef = result; TypeReference t = instruction.myType; emitInstruction(insts.ArrayStoreInstruction(getCurrentInstructionIndex(), arrayRef, index, value, t)); } */ } /** @see com.ibm.wala.shrike.shrikeBT.IInstruction.Visitor#visitGet(IGetInstruction) */ @Override public void visitPutField(PutField instruction) { int value = workingState.getLocal(instruction.source); FieldReference f = FieldReference.findOrCreate( loader, instruction.clazzName, instruction.fieldName, instruction.fieldType); // int value = workingState.pop(); if (instruction instanceof PutField.PutStaticField) { // if (instruction.isStatic()) { emitInstruction(insts.PutInstruction(getCurrentInstructionIndex(), value, f)); } else if (instruction instanceof PutField.PutInstanceField) { // } else { int ref = workingState.getLocal(((PutField.PutInstanceField) instruction).instance); // int ref = workingState.pop(); emitInstruction(insts.PutInstruction(getCurrentInstructionIndex(), ref, value, f)); } else { throw new IllegalArgumentException("Unknown subclass of PutField: " + instruction); } } /** @see com.ibm.wala.shrike.shrikeBT.IInstruction.Visitor#visitReturn(ReturnInstruction) */ @Override public void visitReturn(Return instruction) { if (instruction instanceof Return.ReturnDouble) { // TODO: figure out how to return a double Return.ReturnDouble retD = (Return.ReturnDouble) instruction; int result = workingState.getLocal(retD.source1); // boolean isPrimitive = symbolTable.isLongConstant(result) || // symbolTable.isDoubleConstant(result); boolean isPrimitive = true; emitInstruction( insts.ReturnInstruction(getCurrentInstructionIndex(), result, isPrimitive)); // throw new UnsupportedOperationException("can't yet support returning // doubles"); } else if (instruction instanceof Return.ReturnSingle) { Return.ReturnSingle retS = (Return.ReturnSingle) instruction; int result = workingState.getLocal(retS.source); // TODO: figure out if this is primitive or not // boolean isPrimitive = false; boolean isPrimitive = retS.isPrimitive(); emitInstruction( insts.ReturnInstruction(getCurrentInstructionIndex(), result, isPrimitive)); } else if (instruction instanceof Return.ReturnVoid) { emitInstruction(insts.ReturnInstruction(getCurrentInstructionIndex())); } // if (instruction.getPoppedCount() == 1) { // int result = workingState.pop(); // TypeReference t = ShrikeUtil.makeTypeReference(loader, // instruction.getType()); // emitInstruction(insts.ReturnInstruction(result, t.isPrimitiveType())); // } else { // emitInstruction(insts.ReturnInstruction()); // } } // TODO: this is just a binary operation // @Override // public void visitShift(IShiftInstruction instruction) { // int val2 = workingState.pop(); // int val1 = workingState.pop(); // int result = reuseOrCreateDef(); // workingState.push(result); // emitInstruction(insts.BinaryOpInstruction(instruction.getOperator(), false, // instruction.isUnsigned(), result, val1, val2, // true)); // } /** @see com.ibm.wala.shrike.shrikeBT.IInstruction.Visitor#visitSwitch(SwitchInstruction) */ @Override public void visitSwitch(Switch instruction) { int val = workingState.getLocal(instruction.regA); // int val = workingState.pop(); // TODO: figure out if the switch offset should refer to a pc offset or an instruction id or // what emitInstruction( insts.SwitchInstruction( getCurrentInstructionIndex(), val, instruction.getDefaultLabel(), instruction.getCasesAndLabels())); } private Dominators<ISSABasicBlock> dom = null; @SuppressWarnings("unused") private int findRethrowException() { int index = getCurrentInstructionIndex(); SSACFG.BasicBlock bb = cfg.getBlockForInstruction(index); if (bb.isCatchBlock()) { SSACFG.ExceptionHandlerBasicBlock newBB = (SSACFG.ExceptionHandlerBasicBlock) bb; SSAGetCaughtExceptionInstruction s = newBB.getCatchInstruction(); return s.getDef(); } else { // TODO: should we really use dominators here? maybe it would be cleaner to propagate // the notion of 'current exception to rethrow' using the abstract interpreter. if (dom == null) { dom = Dominators.make(cfg, cfg.entry()); } ISSABasicBlock x = bb; while (x != null) { if (x.isCatchBlock()) { SSACFG.ExceptionHandlerBasicBlock newBB = (SSACFG.ExceptionHandlerBasicBlock) x; SSAGetCaughtExceptionInstruction s = newBB.getCatchInstruction(); return s.getDef(); } else { x = dom.getIdom(x); } } // assert false; return -1; } } /** @see com.ibm.wala.shrike.shrikeBT.IInstruction.Visitor#visitThrow(ThrowInstruction) */ @Override public void visitThrow(Throw instruction) { int throwable = workingState.getLocal(instruction.throwable); assert symbolTable.getMaxValueNumber() >= throwable; emitInstruction(insts.ThrowInstruction(getCurrentInstructionIndex(), throwable)); // if (instruction.isRethrow()) { // workingState.clearStack(); // emitInstruction(insts.ThrowInstruction(findRethrowException())); // } else { // int exception = workingState.pop(); // workingState.clearStack(); // workingState.push(exception); // emitInstruction(insts.ThrowInstruction(exception)); // } } /** * @see com.ibm.wala.shrike.shrikeBT.IInstruction.Visitor#visitUnaryOp(IUnaryOpInstruction) */ @Override public void visitUnaryOperation(UnaryOperation instruction) { if (instruction.op == UnaryOperation.OpID.MOVE_EXCEPTION) { int idx = getCurrentInstructionIndex(); int bbidx = dexCFG.getBlockForInstruction(idx).getNumber(); ExceptionHandlerBasicBlock newBB = (ExceptionHandlerBasicBlock) cfg.getBasicBlock(bbidx); SSAGetCaughtExceptionInstruction s = newBB.getCatchInstruction(); int exceptionValue; if (s == null) { exceptionValue = symbolTable.newSymbol(); s = insts.GetCaughtExceptionInstruction( newBB.getLastInstructionIndex(), bbidx, exceptionValue); newBB.setCatchInstruction(s); } else { exceptionValue = s.getException(); } setLocal(instruction.destination, exceptionValue); return; } // System.out.println("Instruction: " + getCurrentInstructionIndex()); int val = workingState.getLocal(instruction.source); // int val = workingState.pop(); // workingState.push(result); if (instruction.isConversion()) { TypeReference fromType, toType; boolean overflows = false; // TODO: figure out if any of these can overflow switch (instruction.op) { case DOUBLETOLONG: fromType = TypeReference.Double; toType = TypeReference.Long; break; case DOUBLETOFLOAT: fromType = TypeReference.Double; toType = TypeReference.Float; break; case INTTOBYTE: fromType = TypeReference.Int; toType = TypeReference.Byte; break; case INTTOCHAR: fromType = TypeReference.Int; toType = TypeReference.Char; break; case INTTOSHORT: fromType = TypeReference.Int; toType = TypeReference.Short; break; case DOUBLETOINT: fromType = TypeReference.Double; toType = TypeReference.Int; break; case FLOATTODOUBLE: fromType = TypeReference.Float; toType = TypeReference.Double; break; case FLOATTOLONG: fromType = TypeReference.Float; toType = TypeReference.Long; break; case FLOATTOINT: fromType = TypeReference.Float; toType = TypeReference.Int; break; case LONGTODOUBLE: fromType = TypeReference.Long; toType = TypeReference.Double; break; case LONGTOFLOAT: fromType = TypeReference.Long; toType = TypeReference.Float; break; case LONGTOINT: fromType = TypeReference.Long; toType = TypeReference.Int; break; case INTTODOUBLE: fromType = TypeReference.Int; toType = TypeReference.Double; break; case INTTOFLOAT: fromType = TypeReference.Int; toType = TypeReference.Float; break; case INTTOLONG: fromType = TypeReference.Int; toType = TypeReference.Long; break; default: throw new IllegalArgumentException( "unknown conversion type " + instruction.op + " in unary instruction: " + instruction); } int dest = instruction.destination; int result = reuseOrCreateDef(); setLocal(dest, result); emitInstruction( insts.ConversionInstruction( getCurrentInstructionIndex(), result, val, fromType, toType, overflows)); } else { if (instruction.op == UnaryOperation.OpID.MOVE) { setLocal(instruction.destination, workingState.getLocal(instruction.source)); } else if (instruction.op == UnaryOperation.OpID.MOVE_WIDE) { setLocal(instruction.destination, workingState.getLocal(instruction.source)); if (instruction.source == dexCFG.getDexMethod().getReturnReg()) setLocal(instruction.destination + 1, workingState.getLocal(instruction.source)); else setLocal(instruction.destination + 1, workingState.getLocal(instruction.source + 1)); } else { int dest = instruction.destination; int result = reuseOrCreateDef(); setLocal(dest, result); emitInstruction( insts.UnaryOpInstruction( getCurrentInstructionIndex(), instruction.getOperator(), result, val)); } } } // dex doesn't have indirect reads // private void doIndirectReads(int[] locals) { // for(int i = 0; i < locals.length; i++) { // ssaIndirections.setUse(getCurrentInstructionIndex(), new // ShrikeLocalName(locals[i]), workingState.getLocal(locals[i])); // } // } // dex doesn't have load or store, even with indirection // @Override // public void visitLoadIndirect(ILoadIndirectInstruction instruction) { // int addressVal = workingState.pop(); // int result = reuseOrCreateDef(); // // doIndirectReads(bytecodeIndirections.indirectlyReadLocals(getCurrentInstructionIndex())); // TypeReference t = ShrikeUtil.makeTypeReference(loader, // instruction.getPushedType(null)); // emitInstruction(insts.LoadIndirectInstruction(result, t, addressVal)); // workingState.push(result); // } // // private void doIndirectWrites(int[] locals, int rval) { // for(int i = 0; i < locals.length; i++) { // ShrikeLocalName name = new ShrikeLocalName(locals[i]); // int idx = getCurrentInstructionIndex(); // if (ssaIndirections.getDef(idx, name) == -1) { // ssaIndirections.setDef(idx, name, rval==-1? symbolTable.newSymbol(): // rval); // } // workingState.setLocal(locals[i], ssaIndirections.getDef(idx, name)); // } // } // // @Override // public void visitStoreIndirect(IStoreIndirectInstruction instruction) { // int val = workingState.pop(); // int addressVal = workingState.pop(); // // doIndirectWrites(bytecodeIndirections.indirectlyWrittenLocals(getCurrentInstructionIndex()), val); // TypeReference t = ShrikeUtil.makeTypeReference(loader, instruction.getType()); // emitInstruction(insts.StoreIndirectInstruction(addressVal, val, t)); // } } private void reuseOrCreatePi(SSAInstruction piCause, int ref) { int n = getCurrentInstructionIndex(); SSACFG.BasicBlock bb = cfg.getBlockForInstruction(n); BasicBlock path = getCurrentSuccessor(); int outNum = dexCFG.getNumber(path); SSAPiInstruction pi = bb.getPiForRefAndPath(ref, path); if (pi == null) { pi = insts.PiInstruction( getCurrentInstructionIndex(), symbolTable.newSymbol(), ref, bb.getNumber(), outNum, piCause); bb.addPiForRefAndPath(ref, path, pi); } workingState.replaceValue(ref, pi.getDef()); } // private void maybeInsertPi(int val) { // if ((addPiForFieldSelect) && (creators.length > val) && (creators[val] instanceof // SSAGetInstruction) // && !((SSAGetInstruction) creators[val]).isStatic()) { // reuseOrCreatePi(creators[val], val); // } else if ((addPiForDispatchSelect) // && (creators.length > val) // && (creators[val] instanceof SSAInvokeInstruction) // && (((SSAInvokeInstruction) creators[val]).getInvocationCode() == // IInvokeInstruction.Dispatch.VIRTUAL || // ((SSAInvokeInstruction) creators[val]) // .getInvocationCode() == IInvokeInstruction.Dispatch.INTERFACE)) { // reuseOrCreatePi(creators[val], val); // } // } private void maybeInsertPi(SSAAbstractInvokeInstruction call) { if (piNodePolicy != null) { Pair<Integer, SSAInstruction> pi = piNodePolicy.getPi(call, symbolTable); if (pi != null) { reuseOrCreatePi(pi.snd, pi.fst); } } } private void maybeInsertPi(SSAConditionalBranchInstruction cond) { if (piNodePolicy != null) { Pair<Integer, SSAInstruction> pi = piNodePolicy.getPi(cond, getDef(cond.getUse(0)), getDef(cond.getUse(1)), symbolTable); if (pi != null) { reuseOrCreatePi(pi.snd, pi.fst); } } } private SSAInstruction getDef(int vn) { if (vn < creators.length) { return creators[vn]; } else { return null; } } class EdgeVisitor extends Visitor { @Override public void visitInvoke(Invoke instruction) { maybeInsertPi((SSAAbstractInvokeInstruction) getCurrentInstruction()); } @Override public void visitBranch(Branch instruction) { maybeInsertPi((SSAConditionalBranchInstruction) getCurrentInstruction()); } } @Override public Instruction[] getInstructions() { return dexCFG.getDexMethod().getDexInstructions(); } } /** Build the IR */ public void build() { try { solve(); if (localMap != null) { localMap.finishLocalMap(this); } } catch (AssertionError e) { System.err.println("When handling method " + method.getReference()); e.printStackTrace(); // throw e; } } public SSA2LocalMap getLocalMap() { return localMap; } public ShrikeIndirectionData getIndirectionData() { return shrikeIndirections; } /** * A logical mapping from &lt;pc, valueNumber&gt; -&gt; local number Note: make sure this class * remains static: this persists as part of the IR!! */ private static class SSA2LocalMap implements com.ibm.wala.ssa.IR.SSA2LocalMap { private final DexCFG dexCFG; /** * Mapping Integer -&gt; IntPair where p maps to (vn,L) iff we've started a range at pc p where * value number vn corresponds to local L */ private final IntPair[] localStoreMap; /** * For each basic block i and local j, block2LocalState[i][j] gives the contents of local j at * the start of block i */ private final int[][] block2LocalState; /** maximum number of locals used at any program point */ private final int maxLocals; /** * @param nInstructions number of instructions in the bytecode for this method * @param nBlocks number of basic blocks in the CFG */ SSA2LocalMap(DexCFG dexCfg, int nInstructions, int nBlocks, int maxLocals) { dexCFG = dexCfg; localStoreMap = new IntPair[nInstructions]; block2LocalState = new int[nBlocks][]; this.maxLocals = maxLocals; } /** * Record the beginning of a new range, starting at the given program counter, in which a * particular value number corresponds to a particular local number */ @SuppressWarnings("unused") void startRange(int pc, int localNumber, int valueNumber) { int max = ((DexIMethod) dexCFG.getMethod()).getMaxLocals(); if (localNumber >= max) { assert false : "invalid local " + localNumber + '>' + max; } localStoreMap[pc] = new IntPair(valueNumber, localNumber); } /** Finish populating the map of local variable information */ private void finishLocalMap(DexSSABuilder builder) { for (BasicBlock bb : dexCFG) { MachineState S = builder.getIn(bb); int number = bb.getNumber(); block2LocalState[number] = S.getLocals(); } } /** * @param index - index into IR instruction array * @param vn - value number */ @Override public String[] getLocalNames(int index, int vn) { try { if (!dexCFG.getMethod().hasLocalVariableTable()) { return null; } else { int[] localNumbers = findLocalsForValueNumber(index, vn); if (localNumbers == null) { return null; } else { DexIMethod m = dexCFG.getDexMethod(); String[] result = new String[localNumbers.length]; for (int i = 0; i < localNumbers.length; i++) { result[i] = m.getLocalVariableName(m.getBytecodeIndex(index), localNumbers[i]); } return result; } } } catch (Exception e) { e.printStackTrace(); Assertions.UNREACHABLE(); return null; } } /** * @param pc a program counter (index into ShrikeBT instruction array) * @param vn a value number * @return if we know that immediately after the given program counter, v_vn corresponds to some * set of locals, then return an array of the local numbers. else return null. */ private int[] findLocalsForValueNumber(int pc, int vn) { IBasicBlock<Instruction> bb = dexCFG.getBlockForInstruction(pc); int firstInstruction = bb.getFirstInstructionIndex(); // walk forward from the first instruction to reconstruct the // state of the locals at this pc int[] locals = block2LocalState[bb.getNumber()]; if (locals == null) { locals = allocateNewLocalsArray(); } for (int i = firstInstruction; i <= pc; i++) { if (localStoreMap[i] != null) { IntPair p = localStoreMap[i]; locals[p.getY()] = p.getX(); } } return extractIndices(locals, vn); } public int[] allocateNewLocalsArray() { int[] result = new int[maxLocals]; for (int i = 0; i < maxLocals; i++) { result[i] = OPTIMISTIC ? TOP : BOTTOM; } return result; } /** @return the indices i s.t. x[i] == y, or null if none found. */ private static int[] extractIndices(int[] x, int y) { int count = 0; for (int element : x) { if (element == y) { count++; } } if (count == 0) { return null; } else { int[] result = new int[count]; int j = 0; for (int i = 0; i < x.length; i++) { if (x[i] == y) { result[j++] = i; } } return result; } } } }
64,076
40.286727
131
java
WALA
WALA-master/dalvik/src/main/java/com/ibm/wala/dalvik/util/AndroidAnalysisScope.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 under the terms listed below. * */ package com.ibm.wala.dalvik.util; import com.ibm.wala.classLoader.BinaryDirectoryTreeModule; import com.ibm.wala.classLoader.JarFileModule; import com.ibm.wala.core.util.config.AnalysisScopeReader; import com.ibm.wala.core.util.io.FileProvider; import com.ibm.wala.dalvik.classLoader.DexFileModule; import com.ibm.wala.ipa.callgraph.AnalysisScope; import com.ibm.wala.shrike.shrikeCT.InvalidClassFileException; import com.ibm.wala.types.ClassLoaderReference; import com.ibm.wala.util.config.FileOfClasses; import com.ibm.wala.util.debug.Assertions; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.util.jar.JarFile; import org.jf.dexlib2.DexFileFactory; import org.jf.dexlib2.Opcodes; import org.jf.dexlib2.dexbacked.DexBackedDexFile; import org.jf.dexlib2.iface.MultiDexContainer; public class AndroidAnalysisScope { private static final String BASIC_FILE = "primordial.txt"; /** * Creates an Android Analysis Scope * * @param codeFileName the name of a .oat|.apk|.dex file * @param exclusions the name of the exclusions file (nullable) * @param loader the classloader to use * @param androidLib an array of libraries (e.g. the Android SDK jar) to add to the scope * @return a {@link AnalysisScope} */ public static AnalysisScope setUpAndroidAnalysisScope( URI codeFileName, String exclusions, ClassLoader loader, URI... androidLib) throws IOException { return setUpAndroidAnalysisScope( codeFileName, DexFileModule.AUTO_INFER_API_LEVEL, exclusions, loader, androidLib); } public static AnalysisScope setUpAndroidAnalysisScope( URI codeFileName, int apiLevel, String exclusions, ClassLoader loader, URI... androidLib) throws IOException { AnalysisScope scope; File exclusionsFile = exclusions != null ? new File(exclusions) : null; if (androidLib == null || androidLib.length == 0) { scope = AnalysisScopeReader.instance.readJavaScope(BASIC_FILE, exclusionsFile, loader); } else { scope = AnalysisScope.createJavaAnalysisScope(); if (exclusionsFile != null) { try (final InputStream fs = exclusionsFile.exists() ? new FileInputStream(exclusionsFile) : FileProvider.class .getClassLoader() .getResourceAsStream(exclusionsFile.getName())) { scope.setExclusions(new FileOfClasses(fs)); } } scope.setLoaderImpl( ClassLoaderReference.Primordial, "com.ibm.wala.dalvik.classLoader.WDexClassLoaderImpl"); for (URI al : androidLib) { try { scope.addToScope(ClassLoaderReference.Primordial, DexFileModule.make(new File(al))); } catch (Exception e) { scope.addToScope( ClassLoaderReference.Primordial, new JarFileModule(new JarFile(new File(al)))); } } } scope.setLoaderImpl( ClassLoaderReference.Application, "com.ibm.wala.dalvik.classLoader.WDexClassLoaderImpl"); File codeFile = new File(codeFileName); boolean isContainerFile = codeFile.getName().endsWith(".oat") || codeFile.getName().endsWith(".apk"); if (isContainerFile) { MultiDexContainer<? extends DexBackedDexFile> multiDex = DexFileFactory.loadDexContainer( codeFile, apiLevel == DexFileModule.AUTO_INFER_API_LEVEL ? null : Opcodes.forApi(apiLevel)); for (String dexEntry : multiDex.getDexEntryNames()) { scope.addToScope( ClassLoaderReference.Application, new DexFileModule(codeFile, dexEntry, apiLevel)); } } else { scope.addToScope(ClassLoaderReference.Application, DexFileModule.make(codeFile, apiLevel)); } return scope; } /** Handle .apk file. */ public static void addClassPathToScope( String classPath, AnalysisScope scope, ClassLoaderReference loader) { if (classPath == null) { throw new IllegalArgumentException("null classPath"); } try { String[] paths = classPath.split(File.pathSeparator); for (String path : paths) { if (path.endsWith(".jar") || path.endsWith(".apk") || path.endsWith(".dex")) { // Handle android file. File f = new File(path); scope.addToScope(loader, DexFileModule.make(f)); } else { File f = new File(path); if (f.isDirectory()) { // handle directory FIXME not working // for .dex and .apk files into that // directory scope.addToScope(loader, new BinaryDirectoryTreeModule(f)); } else { // handle java class file. try { scope.addClassFileToScope(loader, f); } catch (InvalidClassFileException e) { throw new IllegalArgumentException("Invalid class file", e); } } } } } catch (IOException e) { Assertions.UNREACHABLE(e.toString()); } } }
5,359
35.216216
98
java
WALA
WALA-master/dalvik/src/main/java/com/ibm/wala/dalvik/util/AndroidComponent.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 under the terms listed below. * */ /* * Copyright (c) 2013, * Tobias Blaschke <code@tobiasblaschke.de> * All rights reserved. * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The names of the contributors may not be used to endorse or promote * products derived from this software without specific prior written * permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ package com.ibm.wala.dalvik.util; import com.ibm.wala.classLoader.IClass; import com.ibm.wala.classLoader.IMethod; import com.ibm.wala.core.util.strings.StringStuff; import com.ibm.wala.ipa.cha.IClassHierarchy; import com.ibm.wala.types.ClassLoaderReference; import com.ibm.wala.types.TypeName; import com.ibm.wala.types.TypeReference; /** * Android Components like Activity, Service, ... * * @author Tobias Blaschke &lt;code@tobiasblaschke.de&gt; * @since 2013-10-16 */ public enum AndroidComponent { APPLICATION(AndroidTypes.Application, "Application"), ACTIVITY(AndroidTypes.Activity, "Activity"), FRAGMENT(AndroidTypes.Fragment, "Fragment"), SERVICE(AndroidTypes.Service, "Service"), INTENT_SERVICE(AndroidTypes.IntentService, "IntentService"), ABSTRACT_INPUT_METHOD_SERVICE( AndroidTypes.AbstractInputMethodService, "AbstractInputMethodService"), ACCESSIBILITY_SERVICE(AndroidTypes.AccessibilityService, "AccessibilityService"), DREAM_SERVICE(AndroidTypes.DreamService, "DreamService"), HOST_APDU_SERVICE(AndroidTypes.HostApduService, "HostApduService"), MEDIA_ROUTE_PROVIDER_SERVICE(AndroidTypes.MediaRouteProviderService, "MediaRouteProviderService"), NOTIFICATION_LISTENER_SERVICE( AndroidTypes.NotificationListenerService, "NotificationListenerService"), OFF_HOST_APDU_SERVICE(AndroidTypes.OffHostApduService, "OffHostApduService"), PRINT_SERVICE(AndroidTypes.PrintService, "PrintService"), RECOGNITION_SERVICE(AndroidTypes.RecognitionService, "RecognitionService"), REMOTE_VIEWS_SERVICE(AndroidTypes.RemoteViewsService, "RemoteViewsService"), SETTING_INJECTOR_SERVICE(AndroidTypes.SettingInjectorService, "SettingInjectorService"), SPELL_CHECKER_SERVICE(AndroidTypes.SpellCheckerService, "SpellCheckerService"), TEXT_TO_SPEECH_SERVICE(AndroidTypes.TextToSpeechService, "TextToSpeechService"), VPN_SERVICE(AndroidTypes.VpnService, "VpnService"), WALLPAPER_SERVICE(AndroidTypes.WallpaperService, "WallpaperService"), INPUT_METHOD_SERVICE(AndroidTypes.InputMethodService, "InputMethodService"), PROVIDER(AndroidTypes.ContentProvider, "ContentProvider"), BROADCAST_RECEIVER(AndroidTypes.BroadcastReceiver, "BroadcastReceiver"), // Additional CallBacks: LOADER_CB("Landroid/app/LoaderManager/LoaderCallbacks", "CallBackFromLoader"), RESOLVER(AndroidTypes.ContentResolver, "ContentResolver"), CONTEXT(AndroidTypes.Context, "Context"), HTTP("Landroid/net/AndroidHttpClient", "AndroidHttpClient"), BINDER(AndroidTypes.IBinder, "IBinder"), LOCATION_MGR("Landroid/location/LocationManager", "LocationManager"), TELEPHONY("Landroid/telephony/TelephonyManager", "TelephonyManager"), SMS("Landroid/telephony/SmsManager", "SmsManager"), SMS_GSM("Landroid/telephony/gsm/SmsManager", "GsmSmsManager"), LOCATION_LISTENER("Landroid/location/LocationListener", "LocationListener"), GPS_LISTENER("Landroid/location/GpsStatus$Listener", "GpsStatusListener"), GPS_NMEA_LISTENER("Landroid/location/GpsStatus$NmeaListener", "GpsNmeaListener"), UNKNOWN((String) null, "NULL"); private TypeReference tRef; private final TypeName type; private final String prettyName; AndroidComponent(TypeReference type, final String prettyName) { this.tRef = type; this.type = type.getName(); this.prettyName = prettyName; } AndroidComponent(final String type, final String prettyName) { if (prettyName.contains(".") || prettyName.contains("/") || prettyName.contains("$") || prettyName.contains(" ") || prettyName.contains("\t")) { throw new IllegalArgumentException( "The prettyName may not contain one of the reserved characters " + "., /, $ or whitespace. The given name was " + prettyName); } this.tRef = null; this.prettyName = prettyName; if (type != null) { this.type = TypeName.findOrCreate(type); } else { this.type = null; } } public static boolean isAndroidComponent(final TypeReference T, final IClassHierarchy cha) { for (final AndroidComponent candid : AndroidComponent.values()) { if (candid == AndroidComponent.UNKNOWN) continue; if (candid.getName().equals(T.getName())) { return true; } final IClass iT = cha.lookupClass(T); final IClass iCand = cha.lookupClass(candid.toReference()); if (iT == null) { return false; // TODO } if (iCand == null) { return false; // ???!!! } if (cha.isAssignableFrom(iCand, iT)) { return true; } } return false; } /** * A name usable for display-output. * * <p>The name returned by this function may not necessarily as 'basename' for the class. */ public String getPrettyName() { return this.prettyName; } /** The TypeName associated to the component. */ public TypeName getName() { return this.type; } /** Generates a TypeReference for the component. */ /* package private */ TypeReference toReference() { if (this.tRef != null) { return this.tRef; } else if (this.type == null) { return null; } else { this.tRef = TypeReference.find(ClassLoaderReference.Primordial, this.type); if (this.tRef == null) { /* { DEBUG System.out.println("AndroidComponent WARNING: TypeReference.find did not resolve " + this.type.toString()); } // */ this.tRef = TypeReference.findOrCreate(ClassLoaderReference.Primordial, this.type); } if (this.tRef == null) { throw new IllegalStateException( "Unable to resolve " + this.type.toString() + " in Primordial-Loader. " + "Perhaps the Android-Stubs used are the wrong ones: The analysis needs a view more functions, " + "than the Vanilla-Stubs offer. A script 'stubsBuilder.sh' should have been bundled to generate " + "these."); } return this.tRef; } } /** * Returns the Element the type matches exactly the given type. * * @return The Element if found or AndroidComponent.UNKNOWN if not */ public static AndroidComponent explicit(final TypeName type) { for (AndroidComponent test : AndroidComponent.values()) { if (type.equals(test.type)) { return test; } } return UNKNOWN; } /** * Returns the Element the type matches exactly the given type. * * @return The Element if found or AndroidComponent.UNKNOWN if not */ public static AndroidComponent explicit(final TypeReference type) { return explicit(type.getName()); } /** * Returns the Element the type matches exactly the given type. * * @return The Element if found or AndroidComponent.UNKNOWN if not */ public static AndroidComponent explicit(String type) { if (!(type.startsWith("L") || type.contains("/"))) { type = StringStuff.deployment2CanonicalTypeString(type); } return explicit(TypeName.findOrCreate(type)); } /** * Return the Item that is a matching superclass. * * <p>For example returns AndroidComponent.ACTIVITY for 'LauncherActivity' * * @return the corresponding Enum-Element or AndroidComponent.UNKNOWN */ public static AndroidComponent from(final IClass type, final IClassHierarchy cha) { for (AndroidComponent test : AndroidComponent.values()) { if (type.getReference().equals(test.toReference()) || cha.isSubclassOf(type, cha.lookupClass(test.toReference()))) { return test; } } return UNKNOWN; } /** * Returns the AndroidComponent the method is declared in. * * @return the corresponding Enum-Element or AndroidComponent.UNKNOWN */ public static AndroidComponent from(final IMethod method, final IClassHierarchy cha) { if (method == null) return AndroidComponent.UNKNOWN; IClass type = method.getDeclaringClass(); if (type == null) { throw new IllegalStateException("Unable to retreive the declaring class of " + method); } for (AndroidComponent test : AndroidComponent.values()) { if (test.equals(AndroidComponent.UNKNOWN)) continue; final TypeReference testRef = test.toReference(); if (testRef == null) { continue; // Happens when the Android-Stubs are to old } final IClass testClass = cha.lookupClass(testRef); if (testClass == null) { continue; // Happens when the Android-Stubs are to old } if (testClass.isInterface()) { if (cha.isAssignableFrom(testClass, type)) { if (testClass.getMethod(method.getSelector()) != null) { return test; } } } else { if (cha.isSubclassOf(type, testClass)) { if (testClass.getMethod(method.getSelector()) != null) { return test; } } } } return UNKNOWN; } }
10,804
36.912281
119
java
WALA
WALA-master/dalvik/src/main/java/com/ibm/wala/dalvik/util/AndroidEntryPointLocator.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 under the terms listed below. * */ /* * Copyright (c) 2013, * Tobias Blaschke <code@tobiasblaschke.de> * All rights reserved. * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The names of the contributors may not be used to endorse or promote * products derived from this software without specific prior written * permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ package com.ibm.wala.dalvik.util; import com.ibm.wala.classLoader.IClass; import com.ibm.wala.classLoader.IClassLoader; import com.ibm.wala.classLoader.IMethod; import com.ibm.wala.dalvik.ipa.callgraph.impl.AndroidEntryPoint; import com.ibm.wala.dalvik.ipa.callgraph.impl.AndroidEntryPoint.ExecutionOrder; import com.ibm.wala.dalvik.util.androidEntryPoints.ActivityEP; import com.ibm.wala.dalvik.util.androidEntryPoints.ApplicationEP; import com.ibm.wala.dalvik.util.androidEntryPoints.LoaderCB; import com.ibm.wala.dalvik.util.androidEntryPoints.LocationEP; import com.ibm.wala.dalvik.util.androidEntryPoints.ProviderEP; import com.ibm.wala.dalvik.util.androidEntryPoints.ServiceEP; import com.ibm.wala.ipa.callgraph.AnalysisScope; import com.ibm.wala.ipa.cha.IClassHierarchy; import com.ibm.wala.types.ClassLoaderReference; import com.ibm.wala.types.TypeReference; import com.ibm.wala.util.MonitorUtil.IProgressMonitor; import com.ibm.wala.util.collections.HashSetFactory; import com.ibm.wala.util.config.SetOfClasses; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Comparator; import java.util.EnumSet; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Objects; import java.util.Set; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Searches an Android application for its EntryPoints. * * <p>Iterates the ClassHierarchy matching its elements to a set of hardcoded * entrypoint-specifications. Then optionally uses heuristics to select further entrypoints. * * @author Tobias Blaschke &lt;code@tobiasblaschke.de&gt; */ public final class AndroidEntryPointLocator { private static final Logger logger = LoggerFactory.getLogger(AndroidEntryPointLocator.class); private final IProgressMonitor mon; /** Used to control the search mechanisms of AndroidEntryPointLocator. */ public enum LocatorFlags { /** * If this flag is not set only functions of actual Android-Components are returned. * * <p>If it's enabled additional call-backs are handled as an entrypoint. */ INCLUDE_CALLBACKS, /** Additionally select all functions that override a function of an AndroidComponent. */ EP_HEURISTIC, /** Additionally select all functions that override a function of the Android stubs. */ CB_HEURISTIC, /** Add the constructor of detected components to the entrypoints. */ WITH_CTOR, /** * If a class does not override a method of a component, add a call to the method in the * super-class to the entriepoints. */ WITH_SUPER, /** * This will pull in components defined in the Android-API. In most cases this is not wanted. */ WITH_ANDROID } private static final List<AndroidPossibleEntryPoint> possibleEntryPoints = new ArrayList<>(); private final Set<LocatorFlags> flags; private static Set<LocatorFlags> defaultFlags() { Set<LocatorFlags> flags = HashSetFactory.make(); flags.add(LocatorFlags.INCLUDE_CALLBACKS); flags.add(LocatorFlags.EP_HEURISTIC); flags.add(LocatorFlags.CB_HEURISTIC); return flags; } public AndroidEntryPointLocator() { this(defaultFlags()); } public AndroidEntryPointLocator(final Set<LocatorFlags> flags) { this.flags = Objects.requireNonNullElseGet(flags, () -> EnumSet.noneOf(LocatorFlags.class)); this.mon = AndroidEntryPointManager.MANAGER.getProgressMonitor(); populatePossibleEntryPoints(); } /** * Searches a ClassHierarchy for EntryPoints by their method-signature (optionally with * heuristics). * * <p>Matches the hardcoded signatures against the methods in cha. Uses heuristics depending on * the LocatorFlags given to the constructor . * * @param cha The ClassHierarchy to be searched * @return partially sorted list of applicable EntryPoints */ public List<AndroidEntryPoint> getEntryPoints(final IClassHierarchy cha) { if (cha == null) { throw new IllegalArgumentException("I need a ClassHierarchy to search"); } Set<AndroidEntryPoint> entryPoints = new HashSet<>(); mon.beginTask("Locating Entrypoints", IProgressMonitor.UNKNOWN); int dummy = 0; // for the progress monitor for (IClass cls : cha) { mon.worked(dummy++); if (cls.getName().toString().contains("MainActivity")) { System.err.println("got here"); } if (isExcluded(cls)) continue; if (!cls.isInterface() && !cls.isAbstract() && !(cls.getClassLoader().getName().equals(AnalysisScope.PRIMORDIAL) || cls.getClassLoader().getName().equals(AnalysisScope.EXTENSION))) { nextMethod: for (final IMethod m : cls.getDeclaredMethods()) { if (cls.getName().toString().contains("MainActivity")) { System.err.println("got here: " + m); } // If there is a Method signature in the possible entry points use thatone for (AndroidPossibleEntryPoint e : possibleEntryPoints) { if (e.name.equals(m.getName().toString())) { if (this.flags.contains(LocatorFlags.WITH_ANDROID)) { entryPoints.add(new AndroidEntryPoint(e, m, cha)); } else if (!isAPIComponent(m)) { entryPoints.add(new AndroidEntryPoint(e, m, cha)); } continue nextMethod; } } } // for IMethod m } } // for IClass : cha if (this.flags.contains(LocatorFlags.EP_HEURISTIC) || this.flags.contains(LocatorFlags.CB_HEURISTIC)) { final Set<TypeReference> bases = new HashSet<>(); if (this.flags.contains(LocatorFlags.EP_HEURISTIC)) { // Add bases for EP-Heuristic if (this.flags.contains(LocatorFlags.INCLUDE_CALLBACKS)) { for (final AndroidComponent compo : AndroidComponent.values()) { if (compo == AndroidComponent.UNKNOWN) continue; if (compo.toReference() == null) { logger.error("Null-Reference for " + compo); } else { bases.add(compo.toReference()); } } } else { // Restrict the set bases.add(AndroidTypes.Application); bases.add(AndroidTypes.Activity); // TODO: add Fragments in getEntryPoints // bases.add(AndroidTypes.Fragment); bases.add(AndroidTypes.Service); bases.add(AndroidTypes.ContentProvider); bases.add(AndroidTypes.BroadcastReceiver); } heuristicScan(bases, entryPoints, cha); } if (this.flags.contains(LocatorFlags.CB_HEURISTIC)) { heuristicAnyAndroid(entryPoints, cha); } } List<AndroidEntryPoint> ret = new ArrayList<>(entryPoints); ret.sort(new AndroidEntryPoint.ExecutionOrderComperator()); mon.done(); return ret; } /** * Select all methods that override a method in base. * * <p>If the heuristic selects a method it is added to the eps-argument. * * @param bases classes to search * @param eps The set of detected entrypoints to add to * @param cha The ClassHierarchy to search */ private void heuristicScan( Collection<? extends TypeReference> bases, Set<? super AndroidEntryPoint> eps, IClassHierarchy cha) { for (final TypeReference base : bases) { final IClass baseClass = cha.lookupClass(base); this.mon.subTask("Heuristic scan in " + base); final Collection<IClass> candids; try { candids = cha.computeSubClasses(base); } catch (IllegalArgumentException e) { // Pretty agan :( logger.error(e.getMessage()); continue; } for (final IClass candid : candids) { if (isExcluded(candid)) continue; if (!this.flags.contains(LocatorFlags.WITH_ANDROID) && isAPIComponent(candid)) { // Don't consider internal overrides continue; } final Collection<? extends IMethod> methods = candid.getDeclaredMethods(); for (final IMethod method : methods) { if ((method.isInit() || method.isClinit()) && !this.flags.contains(LocatorFlags.WITH_CTOR)) { logger.debug("Skipping constructor of {}", method); continue; } if (baseClass.getMethod(method.getSelector()) != null) { final AndroidEntryPoint ep = makeEntryPointForHeuristic(method, cha); if (eps.add(ep)) { // Just to be sure that a previous element stays as-is logger.debug("Heuristic 1: selecting {} for base {}", method, base); } } } } } } // private boolean isInnerClass(final TypeReference test) { // return test.getName().toString().contains("$"); // PRETTY! // } private static AndroidEntryPoint makeEntryPointForHeuristic( final IMethod method, final IClassHierarchy cha) { AndroidComponent compo; { // Guess component compo = AndroidComponent.from(method, cha); if (compo == AndroidComponent.UNKNOWN) {} } final AndroidEntryPoint ep = new AndroidEntryPoint(selectPositionForHeuristic(), method, cha, compo); return ep; } /** * Select all methods that override or implement any method from the andoidPackage. * * <p>Like heuristicScan but with an other restriction: instead of methods overriding methods in * base select methods whose super-class starts with "Landroid". * * @param eps The set of detected entrypoints to add to */ private void heuristicAnyAndroid(Set<AndroidEntryPoint> eps, IClassHierarchy cha) { final IClassLoader appLoader = cha.getLoader(ClassLoaderReference.Application); final Iterator<IClass> appIt = appLoader.iterateAllClasses(); for (IClass appClass = (appIt.hasNext() ? appIt.next() : null); appIt.hasNext(); appClass = appIt.next()) { IClass androidClass = appClass; // .getSuperclass(); Override on new { // Only for android-classes boolean isAndroidClass = false; while (androidClass != null) { if (isAPIComponent(androidClass)) { isAndroidClass = true; break; } logger.trace( "Heuristic: \t {} is {}", appClass.getName().toString(), androidClass.getName().toString()); for (IClass iface : appClass.getAllImplementedInterfaces()) { logger.trace("Heuristic: \t implements {}", iface.getName().toString()); if (isAPIComponent(iface)) { isAndroidClass = true; break; } } if (isAndroidClass) break; androidClass = androidClass.getSuperclass(); } if (!isAndroidClass) { logger.trace("Heuristic: Skipping non andoid {}", appClass.getName().toString()); continue; // continue appClass; } } logger.debug("Heuristic: Scanning methods of {}", appClass.getName().toString()); { // Overridden methods if (isAPIComponent(appClass)) continue; if (isExcluded(appClass)) continue; final Collection<? extends IMethod> methods = appClass.getDeclaredMethods(); for (final IMethod method : methods) { if ((method.isInit() || method.isClinit()) && !this.flags.contains(LocatorFlags.WITH_CTOR)) { logger.debug("Skipping constructor of {}", method); continue; } assert (method.getSelector() != null) : "Method has no selector: " + method; assert (androidClass != null) : "androidClass is null"; if (androidClass.getMethod(method.getSelector()) != null) { final AndroidEntryPoint ep = makeEntryPointForHeuristic(method, cha); if (eps.add(ep)) { // Just to be sure that a previous element stays as-is logger.debug("Heuristic 2a: selecting {}", method); } else { logger.debug("Heuristic 2a: already selected {}", method); } } } } { // Implemented interfaces final Collection<IClass> iFaces = appClass.getAllImplementedInterfaces(); for (final IClass iFace : iFaces) { if (isAPIComponent(iFace)) { logger.debug("Skipping iFace: {}", iFace); continue; } if (isExcluded(iFace)) continue; logger.debug("Searching Interface {}", iFace); final Collection<? extends IMethod> ifMethods = iFace.getDeclaredMethods(); for (final IMethod ifMethod : ifMethods) { final IMethod method = appClass.getMethod(ifMethod.getSelector()); if (method != null && method .getDeclaringClass() .getClassLoader() .getReference() .equals(ClassLoaderReference.Application)) { // The function is overridden final AndroidEntryPoint ep = new AndroidEntryPoint(selectPositionForHeuristic(), method, cha); if (eps.add(ep)) { // Just to be sure that a previous element stays as-is logger.debug("Heuristic 2b: selecting {}", method); } } else if (method != null) { // The function is taken from the super-class if (this.flags.contains(LocatorFlags.WITH_SUPER)) { final AndroidEntryPoint ep = makeEntryPointForHeuristic(method, cha); if (eps.contains(ep) && !method.isStatic()) { // eps.get(ep) ... suuuuuper! for (final AndroidEntryPoint eps_ep : eps) { if (eps_ep.equals(ep)) { final TypeReference[] oldTypes = eps_ep.getParameterTypes(0); final TypeReference[] newTypes = Arrays.copyOf(oldTypes, oldTypes.length + 1); newTypes[oldTypes.length] = appClass.getReference(); eps_ep.setParameterTypes(0, newTypes); logger.debug( "New This-Types for {} are {}", method.getSelector(), Arrays.toString(newTypes)); } } } else { if (!method.isStatic()) { ep.setParameterTypes(0, new TypeReference[] {appClass.getReference()}); } eps.add(ep); logger.debug("Heuristic 2b: selecting from super {}", method); } } else { logger.debug("Heuristic 2b: Skipping {}", method); } } } } } // Of 'Implemented interfaces' } } private static boolean isAPIComponent(final IMethod method) { return isAPIComponent(method.getDeclaringClass()); } private static boolean isAPIComponent(final IClass cls) { ClassLoaderReference clr = cls.getClassLoader().getReference(); if (!(clr.equals(ClassLoaderReference.Primordial) || clr.equals(ClassLoaderReference.Extension))) { if (cls.getName().toString().startsWith("Landroid/")) { return true; } return false; } else { return true; } } private static boolean isExcluded(final IClass cls) { final SetOfClasses set = cls.getClassHierarchy().getScope().getExclusions(); if (set == null) { return false; // exclusions null ==> no exclusions ==> no class is excluded } else { final String clsName = cls.getReference().getName().toString().substring(1); return set.contains(clsName); } } /** * The position to place entrypoints selected by a heuristic at. * * <p>Currently all methods are placed at ExecutionOrder.MULTIPLE_TIMES_IN_LOOP. */ private static ExecutionOrder selectPositionForHeuristic() { return ExecutionOrder.MULTIPLE_TIMES_IN_LOOP; } /** * A definition of an Entrypoint functions o the App are matched against. * * <p>To locate the Entrypoints of the analyzed Application all their Methods are matched against * a set of hardcoded definitions. This set consists of AndroidPossibleEntryPoints. An * AndroidPossibleEntryPoint is rather useless as you can build an actual AndroidEntryPoint * without having a AndroidPossibleEntryPoint. * * <p>To extend the set of known definitions have a look at the classes ActivityEP, ServiceEP, ... */ public static class AndroidPossibleEntryPoint implements AndroidEntryPoint.IExecutionOrder { // private final AndroidComponent cls; private final String name; public final AndroidEntryPoint.ExecutionOrder order; public AndroidPossibleEntryPoint(String n, ExecutionOrder o) { // cls = c; name = n; order = o; } public AndroidPossibleEntryPoint(String n, AndroidPossibleEntryPoint o) { // cls = c; name = n; order = o.order; } @Override public int getOrderValue() { return order.getOrderValue(); } @Override public int compareTo(AndroidEntryPoint.IExecutionOrder o) { return order.compareTo(o); } @Override public AndroidEntryPoint.ExecutionOrder getSection() { return order.getSection(); } public static class ExecutionOrderComperator implements Comparator<AndroidPossibleEntryPoint> { @Override public int compare(AndroidPossibleEntryPoint a, AndroidPossibleEntryPoint b) { return a.order.compareTo(b.order); } } } /** * Read in the hardcoded entrypoint-specifications. * * <p>Builds a list of possible EntryPoints in a typical Android application and produces * information on the order in which they should be modeled. */ private void populatePossibleEntryPoints() { // Populate the list of possible EntryPoints if (possibleEntryPoints.size() > 0) { // already populated return; } ApplicationEP.populate(possibleEntryPoints); ActivityEP.populate(possibleEntryPoints); ServiceEP.populate(possibleEntryPoints); ProviderEP.populate(possibleEntryPoints); if (this.flags.contains(LocatorFlags.INCLUDE_CALLBACKS)) { LocationEP.populate(possibleEntryPoints); LoaderCB.populate(possibleEntryPoints); } possibleEntryPoints.sort(new AndroidPossibleEntryPoint.ExecutionOrderComperator()); } public static void debugDumpEntryPoints(List<AndroidPossibleEntryPoint> eps) { int dfa = 0; int indent = 0; for (AndroidPossibleEntryPoint ep : eps) { if (dfa == 0) { System.out.println("AT_FIRST:"); indent = 1; dfa++; } if ((dfa == 1) && (ep.getOrderValue() >= ExecutionOrder.BEFORE_LOOP.getOrderValue())) { System.out.println("BEFORE_LOOP:"); dfa++; } if ((dfa == 2) && (ep.getOrderValue() >= ExecutionOrder.START_OF_LOOP.getOrderValue())) { System.out.println("START_OF_LOOP:"); indent = 2; dfa++; } if ((dfa == 3) && (ep.getOrderValue() >= ExecutionOrder.MIDDLE_OF_LOOP.getOrderValue())) { System.out.println("MIDDLE_OF_LOOP:"); dfa++; } if ((dfa == 4) && (ep.getOrderValue() >= ExecutionOrder.MULTIPLE_TIMES_IN_LOOP.getOrderValue())) { System.out.println("MULTIPLE_TIMES_IN_LOOP:"); indent = 3; dfa++; } if ((dfa == 5) && (ep.getOrderValue() >= ExecutionOrder.END_OF_LOOP.getOrderValue())) { System.out.println("END_OF_LOOP:"); indent = 2; dfa++; } if ((dfa == 6) && (ep.getOrderValue() >= ExecutionOrder.AFTER_LOOP.getOrderValue())) { System.out.println("AFTER_LOOP:"); indent = 1; dfa++; } if ((dfa == 7) && (ep.getOrderValue() >= ExecutionOrder.AT_LAST.getOrderValue())) { System.out.println("AT_LAST:"); indent = 1; dfa++; } for (int i = 0; i < indent; i++) System.out.print("\t"); System.out.println(ep.name + " metric: " + ep.getOrderValue()); } } }
22,082
37.205882
100
java
WALA
WALA-master/dalvik/src/main/java/com/ibm/wala/dalvik/util/AndroidEntryPointManager.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 under the terms listed below. * */ /* * Copyright (c) 2013, * Tobias Blaschke <code@tobiasblaschke.de> * All rights reserved. * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The names of the contributors may not be used to endorse or promote * products derived from this software without specific prior written * permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ package com.ibm.wala.dalvik.util; import com.ibm.wala.classLoader.CallSiteReference; import com.ibm.wala.core.util.ssa.SSAValueManager; import com.ibm.wala.core.util.ssa.TypeSafeInstructionFactory; import com.ibm.wala.core.util.strings.StringStuff; import com.ibm.wala.dalvik.ipa.callgraph.androidModel.parameters.DefaultInstantiationBehavior; import com.ibm.wala.dalvik.ipa.callgraph.androidModel.parameters.IInstantiationBehavior; import com.ibm.wala.dalvik.ipa.callgraph.androidModel.structure.AbstractAndroidModel; import com.ibm.wala.dalvik.ipa.callgraph.androidModel.structure.LoopAndroidModel; import com.ibm.wala.dalvik.ipa.callgraph.impl.AndroidEntryPoint; import com.ibm.wala.dalvik.ipa.callgraph.propagation.cfa.Intent; import com.ibm.wala.ipa.callgraph.Entrypoint; import com.ibm.wala.ipa.cha.IClassHierarchy; import com.ibm.wala.ipa.summaries.VolatileMethodSummary; import com.ibm.wala.types.TypeName; import com.ibm.wala.types.TypeReference; import com.ibm.wala.util.MonitorUtil.IProgressMonitor; import com.ibm.wala.util.NullProgressMonitor; import com.ibm.wala.util.collections.HashMapFactory; import java.io.Serializable; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Set; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Model configuration and Global list of entrypoints. * * <p>See the single settings for further description. * * @author Tobias Blaschke &lt;code@tobiasblaschke.de&gt; */ public final /* singleton */ class AndroidEntryPointManager implements Serializable { private static final Logger logger = LoggerFactory.getLogger(AndroidEntryPointManager.class); public static AndroidEntryPointManager MANAGER = new AndroidEntryPointManager(); public static List<AndroidEntryPoint> ENTRIES = new ArrayList<>(); /** This is TRANSIENT! */ private transient IInstantiationBehavior instantiation = null; // // EntryPoint stuff // /** Determines if any EntryPoint extends the specified component. */ public static boolean EPContainAny(AndroidComponent compo) { for (AndroidEntryPoint ep : ENTRIES) { if (ep.belongsTo(compo)) { return true; } } return false; } private AndroidEntryPointManager() {} public static void reset() { ENTRIES = new ArrayList<>(); MANAGER = new AndroidEntryPointManager(); } public static Set<TypeReference> getComponents() { if (ENTRIES.isEmpty()) { throw new IllegalStateException("No entrypoints loaded yet."); } final Set<TypeReference> ret = new HashSet<>(); for (final AndroidEntryPoint ep : ENTRIES) { final TypeReference epClass = ep.getMethod().getDeclaringClass().getReference(); if (AndroidComponent.isAndroidComponent(epClass, ep.getClassHierarchy())) { ret.add(epClass); } } return ret; } // // General settings // private boolean flatComponents = false; /** * Controlls the initialization of Components. * * <p>See {@link #setDoFlatComponents(boolean)}. */ public boolean doFlatComponents() { return flatComponents; } /** * Controlls the initialization of Components. * * <p>If flatComponents is active an Instance of each Component of the application is generated in * the AndroidModelClass. Whenever the model requires a new instance of a component this * "globalone" is used. * * <p>This resembles the seldomly used Flat-Setting of the start of components in Android. * Activating this generates a more conservative model. * * <p>The default is to deactivate this behavior. * * @return previous setting */ public boolean setDoFlatComponents(boolean flatComponents) { boolean pre = this.flatComponents; this.flatComponents = flatComponents; return pre; } /** * Controls the instantiation of variables in the model. * * <p>See {@link #setInstantiationBehavior(IInstantiationBehavior)}. * * @param cha Optional parameter given to the IInstantiationBehavior * @return DefaultInstantiationBehavior if no other behavior has been set */ public IInstantiationBehavior getInstantiationBehavior(IClassHierarchy cha) { if (this.instantiation == null) { this.instantiation = new DefaultInstantiationBehavior(cha); } return this.instantiation; } /** * Controls the instantiation of variables in the model. * * <p>Controlls on which occasions a new instance to a given type shall be generated and when to * reuse an existing instance. * * <p>This also changes the parameters to the later model. * * <p>The default is DefaultInstantiationBehavior. * * <p>See {@link #setDoFlatComponents(boolean)} for more instantiation settings that affect * components * * @see com.ibm.wala.dalvik.ipa.callgraph.androidModel.parameters.IInstantiationBehavior for more * information * @return the previous IInstantiationBehavior */ public IInstantiationBehavior setInstantiationBehavior(IInstantiationBehavior instantiation) { final IInstantiationBehavior prev = this.instantiation; this.instantiation = instantiation; return prev; } private transient IProgressMonitor progressMonitor = null; /** * Can be used to indicate the progress or to cancel operations. * * @return a NullProgressMonitor or the one set before. */ public IProgressMonitor getProgressMonitor() { return Objects.requireNonNullElseGet(progressMonitor, NullProgressMonitor::new); } /** Set the monitor returned by {@link #getProgressMonitor()}. */ public IProgressMonitor setProgressMonitor(IProgressMonitor monitor) { IProgressMonitor prev = this.progressMonitor; this.progressMonitor = monitor; return prev; } private boolean doBootSequence = true; /** * Whether to generate a global android environment. * * <p>See the {@link #setDoBootSequence} documentation. * * @return the setting, defaults to true */ public boolean getDoBootSequence() { return this.doBootSequence; } /** * Whether to generate a global android environment. * * <p>Inserts some code ath the start of the model to attach some Android-context. This is mainly * interesting for inter-application communication. * * <p>It's possible to analyze android-applications without creating these structures and save * some memory. In this case some calls to the OS (like getting the Activity-manager or so) will * not be able to be resolved. * * <p>It is to be noted that the generated information is far from beeing complete. * * <p>The default is to insert the code. * * @return the previous setting of doBootSequence */ public boolean setDoBootSequence(boolean doBootSequence) { boolean prev = this.doBootSequence; this.doBootSequence = doBootSequence; return prev; } private Class<? extends AbstractAndroidModel> abstractAndroidModel = LoopAndroidModel.class; /** * What special handling to insert into the model. * * <p>At given points in the model (called labels) special code is inserted into it (like loops). * This setting controls what code is inserted there. * * @see com.ibm.wala.dalvik.ipa.callgraph.androidModel.structure.AbstractAndroidModel * @see com.ibm.wala.dalvik.ipa.callgraph.androidModel.structure.SequentialAndroidModel * @see com.ibm.wala.dalvik.ipa.callgraph.androidModel.structure.LoopAndroidModel * @return An object that handles "events" that occur while generating the model. * @throws IllegalStateException if initialization fails */ public AbstractAndroidModel makeModelBehavior( VolatileMethodSummary body, TypeSafeInstructionFactory insts, SSAValueManager paramManager, Iterable<? extends Entrypoint> entryPoints) { if (abstractAndroidModel == null) { return new LoopAndroidModel(body, insts, paramManager, entryPoints); } else { try { final Constructor<? extends AbstractAndroidModel> ctor = this.abstractAndroidModel.getDeclaredConstructor( VolatileMethodSummary.class, TypeSafeInstructionFactory.class, SSAValueManager.class, Iterable.class); if (ctor == null) { throw new IllegalStateException( "Canot find the constructor of " + this.abstractAndroidModel); } return ctor.newInstance(body, insts, paramManager, entryPoints); } catch (InstantiationException | NoSuchMethodException | InvocationTargetException | IllegalAccessException e) { throw new IllegalStateException(e); } } } /** * The behavior set using setModelBehavior(Class). * * <p>Use {@link #makeModelBehavior} to retrieve an instance of this class. * * <p>If no class was set it returns null, makeModelBehavior will generate a LoopAndroidModel by * default. * * @return null or the class set using setModelBehavior */ public Class<? extends AbstractAndroidModel> getModelBehavior() { return this.abstractAndroidModel; } /** * Set the class instantiated by makeModelBehavior. * * @throws IllegalArgumentException if the abstractAndroidModel is null */ public void setModelBehavior(Class<? extends AbstractAndroidModel> abstractAndroidModel) { if (abstractAndroidModel == null) { throw new IllegalArgumentException( "abstractAndroidModel may not be null. Use SequentialAndroidModel " + "if no special handling shall be inserted."); } this.abstractAndroidModel = abstractAndroidModel; } // // Propertys of the analyzed app // private transient String pack = null; /** * Set the package of the analyzed application. * * <p>Setting the package of the application is completely optional. However if you do it it helps * determining whether an Intent has an internal target. * * <p>If a AndroidManifest.xml is read this getts set automaticly. * * @param pack The package of the analyzed application * @throws IllegalArgumentException if the package has already been set and the value of the * packages differ. Or if the given package is null. */ public void setPackage(String pack) { if (pack == null) { throw new IllegalArgumentException("Setting the package to null is disallowed."); } if ((!pack.startsWith("L") || pack.contains("."))) { pack = StringStuff.deployment2CanonicalTypeString(pack); } if (this.pack == null) { logger.info("Setting the package to {}", pack); this.pack = pack; } else if (!this.pack.equals(pack)) { throw new IllegalArgumentException( "The already set package " + this.pack + " and " + pack + " differ. You can only set pack once."); } } /** * Return the package of the analyzed app. * * <p>This only returns a value other than null if the package has explicitly been set using * setPackage (which is for example called when reading in the Manifest). * * <p>If you didn't read the manifest you can still try and retrieve the package name using * guessPackage(). * * <p>See: {@link #setPackage(String)} * * @return The package or null if it was indeterminable. * @see #guessPackage() */ public String getPackage() { if (this.pack == null) { logger.warn("Returning null as package"); return null; } else { return this.pack; } } /** * Get the package of the analyzed app. * * <p>If the package has been set using setPackage() return this value. Else try and determine the * package based on the first entrypoint. * * @return The package or null if it was indeterminable. * @see #getPackage() */ public String guessPackage() { if (this.pack != null) { return this.pack; } else { if (ENTRIES.isEmpty()) { logger.error("guessPackage() called when no entrypoints had been set"); return null; } final String first = ENTRIES .get(0) .getMethod() .getReference() .getDeclaringClass() .getName() .getPackage() .toString(); // TODO: Iterate all? return first; } } // // Intent stuff // /** * Overrides Intents. * * @see com.ibm.wala.dalvik.ipa.callgraph.propagation.cfa.Intent * @see com.ibm.wala.dalvik.ipa.callgraph.propagation.cfa.IntentContextInterpreter */ public final Map<Intent, Intent> overrideIntents = HashMapFactory.make(); /** * Set more information to an Intent. * * <p>You can call this method multiple times on the same Intent as long as you don't lower the * associated information. So if you only want to change a specific value of it it is more safe to * retrieve the Intent first and union it yourself before registering it. * * @param intent An Intent with more or the same information as known to the system before. * @throws IllegalArgumentException if you lower the information on an already registered Intent * or the information is incompatible. * @see #registerIntentForce */ public void registerIntent(Intent intent) { if (overrideIntents.containsKey(intent)) { final Intent original = overrideIntents.get(intent); final Intent.IntentType oriType = original.getType(); final Intent.IntentType newType = intent.getType(); if ((newType == Intent.IntentType.UNKNOWN_TARGET) && (oriType != Intent.IntentType.UNKNOWN_TARGET)) { throw new IllegalArgumentException( "You are lowering information on the Intent-Target of the " + "Intent " + original + " from " + oriType + " to " + newType + ". Use registerIntentForce()" + "If you are sure you want to do this!"); } else if (oriType != newType) { throw new IllegalArgumentException( "You are changing the Intents target to a contradicting one! " + newType + "(new) is incompatible to " + oriType + "(before). On Intent " + intent + ". Use registerIntentForce() if you are sure you want to do this!"); } // TODO: Add actual target to the Intent and compare these? } registerIntentForce(intent); } /** * Set intent possibly overwriting more specific information. * * <p>If you are sure that you want to override an existing registered Intent with information * that is possibly incompatible with the information originally set. */ public void registerIntentForce(Intent intent) { if (intent == null) { throw new IllegalArgumentException("The given Intent is null"); } logger.info("Register Intent {}", intent); // Looks a bit weired but works as Intents are only matched based on their action and uri overrideIntents.put(intent, intent); } /** * Override target of an Intent (or add an alias). * * <p>Use this for example to add an internal target to an implicit Intent, add an alias to an * Intent, resolve a System-name to an internal Intent, do weird stuff... * * <p>None of the Intents have to be registered before. However if the source is registered you * may not lower information on it. * * <p>Currently only one target to an Intent is supported! If you want to emulate multiple Targets * you may have to add a synthetic class and register it as an Intent. If the target is not set to * Internal multiple targets may implicitly emulated. See the Documentation for these targets for * detail. * * <p>If you only intend to make an Intent known see {@link #registerIntent(Intent)}. * * @param from the Intent to override * @param to the new Intent to resolve once 'from' is seen * @see #setOverrideForce * @throws IllegalArgumentException if you override an Intent with itself */ public void setOverride(Intent from, Intent to) { if (from == null) { throw new IllegalArgumentException("The Intent given as 'from' is null"); } if (to == null) { throw new IllegalArgumentException("The Intent given as 'to' is null"); } if (from.equals(to)) { throw new IllegalArgumentException( "You cannot override an Intent with itself! If you want to " + "alter Information on an Intent use registerIntent (you may register it multiple times)."); } if (overrideIntents.containsKey(from)) { final Intent ori = overrideIntents.get(from); final Intent source; if (ori == from) { // The Intent has been registered before. Set the registered variant as source so // Information // that may have been altered is not lost. Not that it would matter now... final Intent.IntentType oriType = ori.getType(); final Intent.IntentType newType = from.getType(); if ((newType == Intent.IntentType.UNKNOWN_TARGET) && (oriType != Intent.IntentType.UNKNOWN_TARGET)) { // TODO: Test target resolvability source = ori; } else { source = from; } } else { source = from; } // Make sure the new target is not less specific than a known override final Intent original = overrideIntents.get(to); final Intent.IntentType oriType = original.getType(); final Intent.IntentType newType = to.getType(); if ((newType == Intent.IntentType.UNKNOWN_TARGET) && (oriType != Intent.IntentType.UNKNOWN_TARGET)) { throw new IllegalArgumentException( "You are lowering information on the Intent-Target of the " + "Intent " + original + " from " + oriType + " to " + newType + ". Use setOverrideForce()" + "If you are sure you want to do this!"); } else if (oriType != newType) { throw new IllegalArgumentException( "You are changing the Intents target to a contradicting one! " + newType + "(new) is incompatible to " + oriType + "(before). On Intent " + to + ". Use setOverrideForce() if you are sure you want to do this!"); } // TODO: Check resolvable Target is not overridden with unresolvable one setOverrideForce(source, to); } else { setOverrideForce(from, to); } } public static final Map<Intent, Intent> DEFAULT_INTENT_OVERRIDES = new HashMap<>(); static { DEFAULT_INTENT_OVERRIDES.put( new AndroidSettingFactory.ExternalIntent("Landroid/intent/action/DIAL"), new AndroidSettingFactory.ExternalIntent("Landroid/intent/action/DIAL")); } /** * Set multiple overrides at the same time. * * <p>See {@link #setOverride(Intent, Intent)}. */ public void setOverrides(Map<Intent, Intent> overrides) { for (final Map.Entry<Intent, Intent> entry : overrides.entrySet()) { final Intent from = entry.getKey(); final Intent to = entry.getValue(); if (from.equals(to)) { registerIntent(to); } else { setOverride(from, to); } } } /** * Just throw in the override. * * <p>See {@link #setOverride(Intent, Intent)}. */ public void setOverrideForce(Intent from, Intent to) { if (from == null) { throw new IllegalArgumentException("The Intent given as 'from' is null"); } if (to == null) { throw new IllegalArgumentException("The Intent given as 'to' is null"); } logger.info("Override Intent {} to {}", from, to); overrideIntents.put(from, to); } /** * Get Intent with applied overrides. * * <p>If there are no overrides or the Intent is not registered return it as is. * * <p>See {@link #setOverride(Intent, Intent)}. See {@link #registerIntent(Intent)}. * * @param intent The intent to resolve * @return where to resolve it to or the given intent if no information is available * <p>TODO: TODO: Malicious Intent-Table could cause endless loops */ public Intent getIntent(Intent intent) { if (overrideIntents.containsKey(intent)) { Intent ret = overrideIntents.get(intent); while (!ret.equals(intent)) { // Follow the chain of overrides if (!overrideIntents.containsKey(intent)) { logger.info("Resolved {} to {}", intent, ret); return ret; } else { logger.debug("Resolving {} hop over {}", intent, ret); final Intent old = ret; ret = overrideIntents.get(ret); if (ret == old) { // Yes, == // This is an evil hack(tm). I should fix the Intent-Table! logger.warn("Malformend Intent-Table, staying with " + ret + " for " + intent); return ret; } } } ret = overrideIntents.get(ret); // Once again to get Info set in register logger.info("Resolved {} to {}", intent, ret); return ret; } else { logger.info("No information on {} hash: {}", intent, intent.hashCode()); for (Intent known : overrideIntents.keySet()) { logger.debug("Known Intents: {} hash: {}", known, known.hashCode()); } return intent; } } /** * Searches Intent specifications for the occurrence of clazz. * * @return the intent is registered or there exists an override. */ public boolean existsIntentFor(TypeName clazz) { for (Intent i : overrideIntents.keySet()) { if (i.getAction().toString().equals(clazz.toString())) { // XXX toString-Matches are shitty return true; } } for (Intent i : overrideIntents.values()) { if (i.getAction().toString().equals(clazz.toString())) { return true; } } return false; } private final transient Map<CallSiteReference, Intent> seenIntentCalls = HashMapFactory.make(); /** * DO NOT CALL! - This is for IntentContextSelector. * * <p>Add information that an Intent was called to the later summary. This is for * information-purpose only and does not change any behavior. * * <p>Intents are added as seen - without any resolved overrides. */ public void addCallSeen(CallSiteReference from, Intent intent) { seenIntentCalls.put(from, intent); } /** Return all Sites, that start Components based on Intents. */ public Map<CallSiteReference, Intent> getSeen() { return seenIntentCalls; // No need to make read-only } private boolean allowIntentRerouting = true; /** * Controll modification of an Intents target after construction. * * <p>After an Intent has been constructed its target may be changed using functions like * setAction or setComponent. This setting controlls the behavior of the model on occurrence of * such a function: * * <p>If set to false the Intent will be marked as unresolvable. * * <p>If set to true the first occurrence of such a function changes the target of the Intent * unless: * * <p>* The Intent was explicit and the new action is not: The call gets ignored * The Intent was * explicit and the new target is explicit: It becomes unresolvable * It's the second occurrence * of such a function: It becomes unresolvable * It was resolvable: It becomes unresolvable * * <p>The default is to activate this behavior. * * @param allow Allow rerouting as described * @return previous setting */ public boolean setAllowIntentRerouting(boolean allow) { boolean prev = allowIntentRerouting; allowIntentRerouting = allow; return prev; } /** * Controll modification of an Intents target after construction. * * <p>See: {@link #setAllowIntentRerouting(boolean)}. * * @return the set behavior or true, the default */ public boolean isAllowIntentRerouting() { return allowIntentRerouting; } /** Last 8 digits encode the date. */ private static final long serialVersionUID = 8740020131212L; }
26,448
34.790257
107
java
WALA
WALA-master/dalvik/src/main/java/com/ibm/wala/dalvik/util/AndroidManifestXMLReader.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 under the terms listed below. * */ /* * Copyright (c) 2013, * Tobias Blaschke <code@tobiasblaschke.de> * All rights reserved. * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The names of the contributors may not be used to endorse or promote * products derived from this software without specific prior written * permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ package com.ibm.wala.dalvik.util; import com.ibm.wala.dalvik.ipa.callgraph.propagation.cfa.Intent; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.lang.reflect.InvocationTargetException; import java.util.ArrayDeque; import java.util.Collections; import java.util.EnumSet; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import javax.xml.parsers.ParserConfigurationException; import javax.xml.parsers.SAXParserFactory; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.xml.sax.Attributes; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import org.xml.sax.helpers.DefaultHandler; /** * Read in an extracted AndroidManifest.xml. * * <p>The file has to be in the extracted (human readable) XML-Format. You can extract it using the * program `apktool`. * * <p>Tags and Attributes not known by the Parser are skipped over. * * <p>To add a Tag to the parsed ones: You have to extend the enum Tags: All Tags on the path to the * Tag in question have to be in the enum. Eventually you will have to adapt the ParserItem of the * Parent-Tags and add it to their allowed Sub-Tags. * * <p>To add an Attribute to the handled ones: You'll have to extend the Enum Attrs if the * Attribute-Name is not yet present there. Then add the Attribute to the relevant Attributes of * it's containing Tag. * * <p>You will be able to access it using attributesHistory.get(Attr).peek() * * <p>TODO: TODO: Handle Info in the DATA-Tag correctly! * * @since 2013-10-13 * @author Tobias Blaschke &lt;code@tobiasblaschke.de&gt; */ public class AndroidManifestXMLReader { /** * This logs low-level parsing. * * <p>Mainly pushes and pops from stacks and seen tags. If you only want Information about objects * created use the logger in AndroidSettingFactory as this parser generates all objects using it. */ private static final Logger logger = LoggerFactory.getLogger(AndroidSettingFactory.class); public AndroidManifestXMLReader(File xmlFile) { if (xmlFile == null) { throw new IllegalArgumentException("xmlFile may not be null"); } try (final FileInputStream in = new FileInputStream(xmlFile)) { readXML(in); } catch (Exception e) { e.printStackTrace(); throw new IllegalStateException("Exception was thrown"); } } public AndroidManifestXMLReader(InputStream xmlFile) { if (xmlFile == null) { throw new IllegalArgumentException("xmlFile may not be null"); } try { readXML(xmlFile); } catch (Exception e) { e.printStackTrace(); throw new IllegalStateException("Exception was thrown"); } } private static void readXML(InputStream xml) throws SAXException, IOException, ParserConfigurationException { assert (xml != null) : "xmlFile may not be null"; final SAXHandler handler = new SAXHandler(); final SAXParserFactory factory = SAXParserFactory.newInstance(); factory.newSAXParser().parse(new InputSource(xml), handler); } // Needed to delay initialization private interface ISubTags { Set<Tag> getSubTags(); } private interface HistoryKey {} /** Only includes relevant tags. */ @SuppressWarnings("Convert2Lambda") private enum Tag implements HistoryKey { /** This tag is nat an actual part of the document. */ ROOT( "ROOT", new ISubTags() { @Override public Set<Tag> getSubTags() { return EnumSet.of(Tag.MANIFEST); } }, null, NoOpItem.class), MANIFEST( "manifest", new ISubTags() { @Override public Set<Tag> getSubTags() { return EnumSet.of(Tag.APPLICATION); } }, EnumSet.of(Attr.PACKAGE), ManifestItem.class), APPLICATION( "application", new ISubTags() { @Override public Set<Tag> getSubTags() { return EnumSet.of(Tag.ACTIVITY, Tag.SERVICE, Tag.RECEIVER, Tag.PROVIDER, Tag.ALIAS); } }, // Allowed children.. Collections.emptySet(), // Interesting Attributes NoOpItem.class), // Handler ACTIVITY( "activity", new ISubTags() { @Override public Set<Tag> getSubTags() { return EnumSet.of(Tag.INTENT); } }, EnumSet.of(Attr.NAME, Attr.ENABLED, Attr.PROCESS), ComponentItem.class), ALIAS( "activity-alias", new ISubTags() { @Override public Set<Tag> getSubTags() { return EnumSet.of(Tag.INTENT); } }, EnumSet.of(Attr.ENABLED, Attr.TARGET, Attr.NAME), ComponentItem.class), SERVICE( "service", new ISubTags() { @Override public Set<Tag> getSubTags() { return EnumSet.of(Tag.INTENT); } }, EnumSet.of(Attr.ENABLED, Attr.NAME, Attr.PROCESS), ComponentItem.class), RECEIVER( "receiver", new ISubTags() { @Override public Set<Tag> getSubTags() { return EnumSet.of(Tag.INTENT); } }, EnumSet.of(Attr.ENABLED, Attr.NAME, Attr.PROCESS), ComponentItem.class), PROVIDER( "provider", new ISubTags() { @Override public Set<Tag> getSubTags() { return EnumSet.of(Tag.INTENT); } }, EnumSet.of(Attr.ENABLED, Attr.ORDER, Attr.NAME, Attr.PROCESS), ComponentItem.class), INTENT( "intent-filter", new ISubTags() { @Override public Set<Tag> getSubTags() { return EnumSet.of(Tag.ACTION, Tag.DATA); } }, Collections.emptySet(), IntentItem.class), ACTION( "action", Collections::emptySet, EnumSet.of(Attr.NAME), FinalItem.class), // (new ITagDweller() { // public Tag getTag() { return Tag.ACTION; }})), DATA( "data", Collections::emptySet, EnumSet.of(Attr.SCHEME, Attr.HOST, Attr.PATH, Attr.MIME), FinalItem.class), // (new ITagDweller() { // public Tag getTag() { return Tag.DATA; }})), /** Internal pseudo-tag used for tags in the documents, that have no parser representation. */ UNIMPORTANT("UNIMPORTANT", null, Collections.emptySet(), null); private final String tagName; private final Set<Attr> relevantAttributes; private final ISubTags allowedSubTagsHolder; private final ParserItem item; private Set<Tag> allowedSubTags; // Delay init private static final Map<String, Tag> reverseMap = new HashMap<>(); // HashMapFactory.make(9); Tag( String tagName, ISubTags allowedSubTags, Set<Attr> relevant, Class<? extends ParserItem> item) { this.tagName = tagName; this.relevantAttributes = relevant; this.allowedSubTagsHolder = allowedSubTags; if (item != null) { try { this.item = item.getDeclaredConstructor().newInstance(); this.item.setSelf(this); } catch (IllegalArgumentException | InvocationTargetException | NoSuchMethodException | SecurityException | InstantiationException e) { e.getCause().printStackTrace(); throw new IllegalStateException("InstantiationException was thrown"); } catch (java.lang.IllegalAccessException e) { e.printStackTrace(); if (e.getCause() != null) { e.getCause().printStackTrace(); } throw new IllegalStateException("IllegalAccessException was thrown"); } } else { this.item = null; } } static { for (Tag tag : Tag.values()) { reverseMap.put(tag.tagName, tag); } } /** The class that takes action on this tag. */ public ParserItem getHandler() { if (this.item == null) { System.err.println("Requested non existing handler for: " + this); } return this.item; } /** The Tags that may appear as a child of this Tag. */ public Set<Tag> getAllowedSubTags() { if (this.allowedSubTagsHolder == null) { return null; } else if (this.allowedSubTags == null) { this.allowedSubTags = allowedSubTagsHolder.getSubTags(); } return Collections.unmodifiableSet(this.allowedSubTags); } /** * The Attributes read in when parsing the Tag. * * <p>The read attributes get thrown on a Stack, thus they don't need to be evaluated in the Tag * itself but may also be handled by a parent. * * <p>The handling Item has to pop them after it has evaluated them else it gets a big mess. */ public Set<Attr> getRelevantAttributes() { return Collections.unmodifiableSet(this.relevantAttributes); } /** The given Attr is in {@link #getRelevantAttributes()}. */ public boolean isRelevant(Attr attr) { return relevantAttributes.contains(attr); } /** All Tags in this Enum but UNIMPORTANT are relevant. */ @SuppressWarnings("unused") public boolean isRelevant() { return (this != Tag.UNIMPORTANT); } /** * Match the Tag-Name in the XML-File against the one associated to the Enums Tag. * * <p>If no Tag in this Enum matches Tag.UNIMPORTANT is returned and the parser will ignore the * tree under this tag. * * <p>Matching is case insensitive of course. */ public static Tag fromString(String tag) { tag = tag.toLowerCase(); return reverseMap.getOrDefault(tag, Tag.UNIMPORTANT); } /** The Tag appears in the XML File using this name. */ @SuppressWarnings("unused") public String getName() { return this.tagName; } } /** * Attributes that may appear in a Tags.Tag. * * <p>In order to evaluate a new attribute it has to be added to the Tags it may appear in and at * least one ParserItem has to be adapted. * * <p>Values read for the single Attrs will get pushed to the attributesHistory (in Items). */ private enum Attr implements HistoryKey { PACKAGE("package"), NAME("name"), SCHEME("scheme"), HOST("host"), PATH("path"), ENABLED("enabled"), TARGET("targetActivity"), PROCESS("process"), ORDER("initOrder"), MIME("mimeType"); private final String attrName; Attr(String attrName) { this.attrName = attrName; } @SuppressWarnings("unused") public boolean isRelevantIn(Tag tag) { return tag.isRelevant(this); } public String getName() { return this.attrName; } } /** * Contains the "path" from Tag.ROOT that currently gets evaluated. * * <p>On an opening Tag the Tag gets pushed. It get's popped again once it's evaluated. That is on * the closing Tag or on the closing Tag of a parent: A Item does not remove its own Tag from the * Stack. */ private static final ArrayDeque<Tag> parserStack = new ArrayDeque<>(); /** * Contains either Attributes of a child or the evaluation-result of a child-Tag. * * <p>The Item that consumes an Attribute has to pop it. */ private static final Map<HistoryKey, ArrayDeque<Object>> attributesHistory = new HashMap<>(); // No EnumMap possible :( static { for (Attr attr : Attr.values()) { attributesHistory.put(attr, new ArrayDeque<>()); } for (Tag tag : Tag.values()) { attributesHistory.put(tag, new ArrayDeque<>()); } } /** * Handling of a Tag. * * <p>Does (if not overridden) all the needed Push- and Pop-Operations. Items may however choose * to leave some stuff on the Stack. In this case this data has to be popped by the handling * parent, or the Tag may only occur once or bad things will happen. * * <p>_CAUTION_: This will be instantiated by an Enum, so if you write local Fields you will get * surprising results! You should mark all of them as final to be sure. */ private abstract static class ParserItem { protected Tag self; /** * Set the Tag this ParserItem-Instance is an Handler for. * * <p>This may only be set once! */ public void setSelf(Tag self) { if (this.self != null) { throw new IllegalStateException("Self can only be set once!"); } this.self = self; } public ParserItem() {} /** * Remember attributes to the tag. * * <p>The read attributes will be pushed to the attributesHistory. * * <p>Leave Parser-Stack alone! This is called by SAXHandler only! */ public void enter(Attributes saxAttrs) { for (Attr relevant : self.getRelevantAttributes()) { String attr = saxAttrs.getValue(relevant.getName()); if (attr == null) { attr = saxAttrs.getValue("android:" + relevant.getName()); } attributesHistory.get(relevant).push(attr); logger.debug("Pushing '{}' for {} in {}", attr, relevant, self); // if there is no such value in saxAttrs it returns null } } /** * Remove all Attributes generated by self and self itself. * * <p>This is called by the consuming ParserItem. */ public void popAttributes() { for (Attr relevant : self.getRelevantAttributes()) { try { logger.debug( "Popping {} of value {} in {}", relevant, attributesHistory.get(relevant).peek(), self); attributesHistory.get(relevant).pop(); } catch (java.util.EmptyStackException e) { System.err.println(self + " failed to pop " + relevant); throw e; } } if (attributesHistory.containsKey(self) && attributesHistory.get(self) != null && !attributesHistory.get(self).isEmpty()) { try { attributesHistory.get(self).pop(); } catch (java.util.EmptyStackException e) { System.err.println("The Stack for " + self + " was Empty when trying to pop"); throw e; } } } /** * Consume sub-items on the stack. * * <p>Do this by popping them, but leave self on the stack! For each Item popped call its * popAttributes()! */ public void leave() { while (parserStack.peek() != self) { final Set<Tag> allowedSubTags = self.getAllowedSubTags(); Tag subTag = parserStack.pop(); if (allowedSubTags.contains(subTag)) { if (subTag.getHandler() == null) { throw new IllegalArgumentException("The SubTag " + subTag + " has no handler!"); } subTag.getHandler().popAttributes(); // hmmm.... logger.debug("New Stack: {}", parserStack); // parserStack.pop(); } else { throw new IllegalStateException( subTag + " is not allowed as sub-tag of " + self + " in Context:\n\t" + parserStack); } } } } /** * An ParserItem that contains no sub-tags. * * <p>You can use it directly if you don't intend to do any computation on this Tag but remember * its Attributes. */ private static class FinalItem extends ParserItem { @Override public void leave() { final Set<Tag> subs = self.getAllowedSubTags(); if (!((subs == null) || subs.isEmpty())) { throw new IllegalArgumentException( "FinalItem can not be applied to " + self + " as it contains sub-tags: " + self.getAllowedSubTags()); } if (parserStack.peek() != self) { throw new IllegalStateException( "Topstack is not " + self + " which is disallowed for a FinalItem!\n" + "This is most certainly caused by an implementation mistake on a ParserItem. Stack is:\n\t" + parserStack); } } } /** * Only extracts Attributes. * * <p>It's like FinalItem but may contain sub-tags. */ private static class NoOpItem extends ParserItem {} /** The root-element of an AndroidManifest contains the package. */ private static class ManifestItem extends ParserItem { @Override public void enter(Attributes saxAttrs) { super.enter(saxAttrs); AndroidEntryPointManager.MANAGER.setPackage( (String) attributesHistory.get(Attr.PACKAGE).peek()); } } /** * Read the specification of an Intent from AndroidManifest. * * <p>TODO: Handle the URI */ private static class IntentItem extends ParserItem { @Override public void leave() { Set<Tag> allowedTags = EnumSet.copyOf(self.getAllowedSubTags()); Set<String> urls = new HashSet<>(); Set<String> names = new HashSet<>(); while (parserStack.peek() != self) { Tag current = parserStack.pop(); if (allowedTags.contains(current)) { if (current == Tag.ACTION) { Object oName = attributesHistory.get(Attr.NAME).peek(); if (oName == null) { throw new IllegalStateException( "The currently parsed Action did not leave the required 'name' Attribute" + " on the Stack! Attributes-Stack for name is: " + attributesHistory.get(Attr.NAME)); } else if (oName instanceof String) { names.add((String) oName); } else { throw new IllegalStateException( "Unexpected Attribute type for name: " + oName.getClass().toString()); } } else if (current == Tag.DATA) { Object oUrl = attributesHistory.get(Attr.SCHEME).peek(); if (oUrl == null) { // TODO } else if (oUrl instanceof String) { urls.add((String) oUrl); } else { throw new IllegalStateException( "Unexpected Attribute type for name: " + oUrl.getClass().toString()); } } else { throw new IllegalStateException("Error in parser implementation"); } current.getHandler().popAttributes(); } else { throw new IllegalStateException( "In INTENT: Tag " + current + " not allowed in Context " + parserStack + "\n\t" + "Allowed Tags: " + allowedTags); } } /* // Pushing intent... final String pack; if ((attributesHistory.get(Attr.PACKAGE) != null ) && (!(attributesHistory.get(Attr.PACKAGE).isEmpty()))) { pack = (String) attributesHistory.get(Attr.PACKAGE).peek(); } else { logger.warn("Empty Package {}", attributesHistory.get(Attr.PACKAGE).peek()); pack = null; } */ if (!names.isEmpty()) { for (String name : names) { if (urls.isEmpty()) urls.add(null); for (String url : urls) { logger.info("New Intent ({}, {})", name, url); final Intent intent = AndroidSettingFactory.intent(name, url); attributesHistory.get(self).push(intent); } } } else { /* * Previously, an exception was thrown but in fact there is no need to crash here. Actions * are required, but if there is no action in a particular intent-filter, then no intent * will pass the intent filter. See also * http://developer.android.com/guide/topics/manifest/action-element.html So we'll just * issue a warning and continue happily with our work... */ logger.warn( "specified intent without action - this means that no intents will pass the filter..."); } } } private static class ComponentItem extends ParserItem { @Override public void leave() { final Set<Tag> allowedTags = self.getAllowedSubTags(); final Set<Intent> overrideTargets = new HashSet<>(); while (parserStack.peek() != self) { Tag current = parserStack.pop(); if (allowedTags.contains(current)) { if (current == Tag.INTENT) { // do not expect item at top of stack if no intent was produced if (attributesHistory.get(Tag.INTENT).isEmpty()) continue; Object oIntent = attributesHistory.get(Tag.INTENT).peek(); if (oIntent == null) { throw new IllegalStateException( "The currently parsed Intent did not push a Valid intent to the " + "Stack! Attributes-Stack for name is: " + attributesHistory.get(Attr.NAME)); } else if (oIntent instanceof Intent) { overrideTargets.add((Intent) oIntent); } else { throw new IllegalStateException( "Unexpected Attribute type for Intent: " + oIntent.getClass().toString()); } } else { throw new IllegalStateException("Error in parser implementation"); } current.getHandler().popAttributes(); } else { throw new IllegalStateException( "In " + self + ": Tag " + current + " not allowed in Context " + parserStack + "\n\t" + "Allowed Tags: " + allowedTags); } } // Generating Intent for this... final String pack; if ((attributesHistory.get(Attr.PACKAGE) != null) && !attributesHistory.get(Attr.PACKAGE).isEmpty()) { pack = (String) attributesHistory.get(Attr.PACKAGE).peek(); } else { logger.warn("Empty Package {}", attributesHistory.get(Attr.PACKAGE).peek()); pack = null; } final String name; if (self == Tag.ALIAS) { name = (String) attributesHistory.get(Attr.TARGET).peek(); // TODO: Verify type! } else { name = (String) attributesHistory.get(Attr.NAME).peek(); // TODO: Verify type! } final Intent intent = AndroidSettingFactory.intent(pack, name, null); logger.info("\tRegister: {}", intent); AndroidEntryPointManager.MANAGER.registerIntent(intent); for (Intent ovr : overrideTargets) { logger.info("\tOverride: {} --> {}", ovr, intent); if (ovr.equals(intent)) { AndroidEntryPointManager.MANAGER.registerIntent(intent); } else { AndroidEntryPointManager.MANAGER.setOverride(ovr, intent); } } } } private static class SAXHandler extends DefaultHandler { private int unimportantDepth = 0; public SAXHandler() { super(); parserStack.push(Tag.ROOT); } @Override public void startElement(String uri, String name, String qName, Attributes attrs) { Tag tag = Tag.fromString(qName); if ((tag == Tag.UNIMPORTANT) || (unimportantDepth > 0)) { unimportantDepth++; } else { logger.debug("Handling {} made from {}", tag, qName); final ParserItem handler = tag.getHandler(); if (handler != null) { handler.enter(attrs); } parserStack.push(tag); } } @Override public void endElement(String uri, String localName, String qName) { if (unimportantDepth > 0) { unimportantDepth--; } else { final Tag tag = Tag.fromString(qName); final ParserItem handler = tag.getHandler(); if (handler != null) { handler.leave(); } } } } }
25,732
32.859211
113
java
WALA
WALA-master/dalvik/src/main/java/com/ibm/wala/dalvik/util/AndroidPreFlightChecks.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 under the terms listed below. * */ /* * Copyright (c) 2013, * Tobias Blaschke <code@tobiasblaschke.de> * All rights reserved. * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The names of the contributors may not be used to endorse or promote * products derived from this software without specific prior written * permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ package com.ibm.wala.dalvik.util; import com.ibm.wala.dalvik.ipa.callgraph.androidModel.parameters.IInstantiationBehavior; import com.ibm.wala.dalvik.ipa.callgraph.impl.AndroidEntryPoint; import com.ibm.wala.ipa.cha.IClassHierarchy; import com.ibm.wala.types.Selector; import com.ibm.wala.types.TypeName; import com.ibm.wala.types.TypeReference; import java.util.EnumSet; import java.util.List; import java.util.Set; /** * Does optional checks before building the CallGraph. * * <p>The android-model expects some configuration to be of specific settings to unfold it's full * performance. * * <p>These checks may be run before building the CallGraph to verify everything is in place. * * @author Tobias Blaschke &lt;code@tobiasblaschke.de&gt; * @since 2013-11-01 */ public class AndroidPreFlightChecks { private final AndroidEntryPointManager manager; // private final AnalysisOptions options; private final IClassHierarchy cha; public AndroidPreFlightChecks(AndroidEntryPointManager manager, IClassHierarchy cha) { this.manager = manager; // this.options = options; this.cha = cha; } public enum Test { OVERRIDES, INTENTS, REUSE, STUBS_VERSION, OBJECT_IN_EP } /** * Perform all checks defined in this class. * * @return if the checks passed */ public boolean all() { return allBut(EnumSet.noneOf(Test.class)); } /** * Perform all checks defined in this class but the listed ones. * * @param skip checks not to perform * @return if the checks passed */ public boolean allBut(Set<Test> skip) { boolean pass = true; if (!skip.contains(Test.OVERRIDES)) { pass &= checkOverridesInPlace(); } if (!skip.contains(Test.INTENTS)) { pass &= checkIntentSpecs(); } if (!skip.contains(Test.REUSE)) { pass &= checkAllComponentsReuse(); } if (!skip.contains(Test.STUBS_VERSION)) { pass &= checkStubsVersion(); } if (!skip.contains(Test.OBJECT_IN_EP)) { pass &= checkNoObjectInEntryPoints(); } return pass; } /** * The Overrides are needed to resolve intents in the startComponent-Calls. * * <p>Without these overrides the startComponent-Calls will not be overridden. In a static * analysis there won't be a way to resolve the actual target of the call. * * @see com.ibm.wala.dalvik.ipa.callgraph.propagation.cfa.IntentContextInterpreter * @see com.ibm.wala.dalvik.ipa.callgraph.propagation.cfa.IntentContextSelector * @return if check passed TODO: this doesn't check anything yet */ public boolean checkOverridesInPlace() { boolean pass = true; // TODO: Check StartComponentMethodTargetSelector // TODO: Check IntentContextInterpreter // TODO: Check IntentContextSelector return pass; } /** * Checks whether stubs are recent enough to contain some used functions. * * <p>If the stubs are to old some parts that rely on these functions may be skipped entirely. * * @return if check passed */ public boolean checkStubsVersion() { boolean pass = true; if (this.cha.lookupClass(AndroidTypes.Fragment) == null) { pass = false; } if (this.cha.lookupClass(AndroidTypes.UserHandle) == null) { pass = false; } if (this.cha.resolveMethod( this.cha.lookupClass(AndroidTypes.Activity), Selector.make("getLoaderManager()Landroid/app/LoaderManager;")) == null) { pass = false; } if (this.cha.resolveMethod( this.cha.lookupClass(AndroidTypes.Activity), Selector.make("getSystemService(Ljava/lang/String;)Ljava/lang/Object;")) == null) { pass = false; } if (this.cha.resolveMethod( this.cha.lookupClass(AndroidTypes.Context), Selector.make("getSystemService(Ljava/lang/String;)Ljava/lang/Object;")) == null) { pass = false; } return pass; } /** * Is enough info present to resolve Intents. * * <p>This information is needed by the startComponent-functions in order to resolve the target of * the call (if enough context is present). * * <p>If this information is unavailable the call will be resolved to the function * AndroidModel.Class.startUNKNOWNComponent which will call all Components of the specific type * (Activity, Service, ..) present in the application. * * @return if check passed */ public boolean checkIntentSpecs() { boolean pass = true; final List<AndroidEntryPoint> entrypoits = AndroidEntryPointManager.ENTRIES; for (AndroidEntryPoint ep : entrypoits) { final TypeName test = ep.getMethod().getDeclaringClass().getName(); if (!this.manager.existsIntentFor(test)) { if (test.toString().startsWith("Landroid/")) { continue; } pass = false; } } return pass; } /** * In order to for the startComponent-calls to work components should be set reuse. * * <p>If components are _not_ set reuse the following will happen: * * <p>* The caller context can not be set * No result will be transmitted back to onActivityResult * * @return if the test passed */ public boolean checkAllComponentsReuse() { boolean pass = true; final IInstantiationBehavior behaviour = this.manager.getInstantiationBehavior( cha); // XXX: This generates false positives without cha! final List<AndroidEntryPoint> entrypoits = AndroidEntryPointManager.ENTRIES; for (AndroidEntryPoint ep : entrypoits) { final TypeName test = ep.getMethod().getDeclaringClass().getName(); IInstantiationBehavior.InstanceBehavior behave = behaviour.getBehavior( test, /* asParameterTo= */ null, /* inCall= */ null, /* withName= */ null); if (behave != IInstantiationBehavior.InstanceBehavior.REUSE) { pass = false; } } return pass; } /** Check if an Entrypoint takes an object. */ public boolean checkNoObjectInEntryPoints() { boolean pass = true; final List<AndroidEntryPoint> entrypoits = AndroidEntryPointManager.ENTRIES; for (AndroidEntryPoint ep : entrypoits) { final TypeName[] params = ep.getMethod().getDescriptor().getParameters(); if (params == null) continue; for (final TypeName type : params) { if (type.equals( TypeReference.JavaLangObject.getName())) { // Why if JavaLangObjectName private? .. narf pass = false; break; } } } return pass; } }
8,481
31.623077
100
java
WALA
WALA-master/dalvik/src/main/java/com/ibm/wala/dalvik/util/AndroidSettingFactory.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 under the terms listed below. * */ /* * Copyright (c) 2013, * Tobias Blaschke <code@tobiasblaschke.de> * All rights reserved. * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The names of the contributors may not be used to endorse or promote * products derived from this software without specific prior written * permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ package com.ibm.wala.dalvik.util; import com.ibm.wala.core.util.strings.Atom; import com.ibm.wala.core.util.strings.StringStuff; import com.ibm.wala.dalvik.ipa.callgraph.propagation.cfa.Intent; /** * Generate a Settings-Object from a String-Representation. * * <p>This is for use by a parser to generate the Objects to place in the AndroidEntryPointManager. * * @see AndroidManifestXMLReader * @author Tobias Blaschke &lt;code@tobiasblaschke.de&gt; * @since 2013-10-14 */ public class AndroidSettingFactory { /** * Add an Intent that is _shure_ to be handled internally _only_. * * <p>If there was an additional external handling of this intent it will be ignored! */ public static class InternalIntent extends Intent { @Override public IntentType getType() { return Intent.IntentType.INTERNAL_TARGET; } public InternalIntent(String action) { super(action); } public InternalIntent(Atom action) { super(action); } public InternalIntent(Atom action, Atom uri) { super(action, uri); } @Override // Force clash! public int hashCode() { return super.hashCode(); } @Override // Force clash! public boolean equals(Object o) { return super.equals(o); } } public static class UnknownIntent extends Intent { @Override public IntentType getType() { return Intent.IntentType.UNKNOWN_TARGET; } public UnknownIntent(String action) { super(action); } public UnknownIntent(Atom action) { super(action); } public UnknownIntent(Atom action, Atom uri) { super(action, uri); } @Override // Force clash! public int hashCode() { return super.hashCode(); } @Override // Force clash! public boolean equals(Object o) { return super.equals(o); } } public static class ExternalIntent extends Intent { @Override public IntentType getType() { return Intent.IntentType.EXTERNAL_TARGET; } public ExternalIntent(String action) { super(action); } public ExternalIntent(Atom action) { super(action); } public ExternalIntent(Atom action, Atom uri) { super(action, uri); } @Override // Force clash! public int hashCode() { return super.hashCode(); } @Override // Force clash! public boolean equals(Object o) { return super.equals(o); } } public static class StandardIntent extends Intent { @Override public IntentType getType() { return Intent.IntentType.STANDARD_ACTION; } public StandardIntent(String action) { super(action); } public StandardIntent(Atom action) { super(action); } public StandardIntent(Atom action, Atom uri) { super(action, uri); } @Override // Force clash! public int hashCode() { return super.hashCode(); } @Override // Force clash! public boolean equals(Object o) { return super.equals(o); } } public static class IgnoreIntent extends Intent { @Override public IntentType getType() { return Intent.IntentType.IGNORE; } public IgnoreIntent(String action) { super(action); } public IgnoreIntent(Atom action) { super(action); } public IgnoreIntent(Atom action, Atom uri) { super(action, uri); } @Override // Force clash! public int hashCode() { return super.hashCode(); } @Override // Force clash! public boolean equals(Object o) { return super.equals(o); } } /** * Make an intent. * * @param pack The applications package. May be null if unknown - but this may yield an exception * @param name The Action this intent represents * @param uri The URI to match may be null * @throws IllegalArgumentException If name was null or starts with a dot and pack is null TODO: * Check Target-Types */ public static Intent intent(String pack, String name, String uri) { if ((name == null) || name.isEmpty()) { throw new IllegalArgumentException("name may not be null or empty"); } Intent.IntentType type = Intent.IntentType.UNKNOWN_TARGET; if (name.startsWith(".")) { if ((pack == null) || pack.isEmpty()) { throw new IllegalArgumentException( "The pack is needed to resolve the full name of " + name + ", but it's empty"); } name = pack + name; type = Intent.IntentType.INTERNAL_TARGET; // TODO Ehhh... } else if (!name.contains(".")) { if ((pack != null) && !pack.isEmpty()) { name = pack + '.' + name; } type = Intent.IntentType.INTERNAL_TARGET; // TODO Ehhh... } else if ((pack != null) && name.startsWith(pack)) { type = Intent.IntentType.INTERNAL_TARGET; // TODO Ehhh... } else if (name.startsWith("android.intent.action")) { type = Intent.IntentType.STANDARD_ACTION; } // convert name to the L-Slash format.. if ((name.startsWith("L") || name.contains("."))) { name = StringStuff.deployment2CanonicalTypeString(name); } final Atom action = Atom.findOrCreateAsciiAtom(name); final Intent ret; Atom mUri = null; if (uri != null) { mUri = Atom.findOrCreateAsciiAtom(uri); } switch (type) { case INTERNAL_TARGET: if (uri != null) { ret = new InternalIntent(action, mUri); } else { ret = new InternalIntent(action); } break; default: if (uri != null) { ret = new StandardIntent(action, mUri); } else { ret = new StandardIntent(action); } break; } return ret; } // // Short-Hand functions follow... // public static Intent intent(String fullyQualifiedAction, String uri) { if (fullyQualifiedAction.startsWith(".")) { String pack = AndroidEntryPointManager.MANAGER.getPackage(); if (pack != null) { return intent(pack, fullyQualifiedAction, uri); } else { throw new IllegalArgumentException( "The action " + fullyQualifiedAction + " is not fully qualified and the application package is unknown! Use " + " intent(String pack, String name, String uri) to build the intent!"); } } else { return intent(null, fullyQualifiedAction, uri); } } public static Intent intent(String fullyQualifiedAction) { if (fullyQualifiedAction.startsWith(".")) { throw new IllegalArgumentException( "The action " + fullyQualifiedAction + " is not fully qualified! Use " + " intent(String pack, String name, null) to build the intent!"); } return intent(null, fullyQualifiedAction, null); } }
8,719
27.874172
99
java
WALA
WALA-master/dalvik/src/main/java/com/ibm/wala/dalvik/util/AndroidTypes.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 under the terms listed below. * */ /* * Copyright (c) 2013, * Tobias Blaschke <code@tobiasblaschke.de> * All rights reserved. * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The names of the contributors may not be used to endorse or promote * products derived from this software without specific prior written * permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ package com.ibm.wala.dalvik.util; import com.ibm.wala.types.ClassLoaderReference; import com.ibm.wala.types.TypeName; import com.ibm.wala.types.TypeReference; /** * Constants for types used by the AndroidModel * * @author Tobias Blaschke &lt;code@tobiasblaschke.de&gt; */ public final class AndroidTypes { public static final TypeName HandlerName = TypeName.string2TypeName("Landroid/os/Handler"); public static final TypeReference Handler = TypeReference.findOrCreate(ClassLoaderReference.Primordial, HandlerName); public static final TypeName IntentName = TypeName.string2TypeName("Landroid/content/Intent"); public static final TypeReference Intent = TypeReference.findOrCreate(ClassLoaderReference.Primordial, IntentName); public static final TypeName ApplicationName = TypeName.string2TypeName("Landroid/app/Application"); public static final TypeReference Application = TypeReference.findOrCreate(ClassLoaderReference.Primordial, ApplicationName); public static final TypeName ActivityName = TypeName.string2TypeName("Landroid/app/Activity"); public static final TypeReference Activity = TypeReference.findOrCreate(ClassLoaderReference.Primordial, ActivityName); public static final TypeName FragmentName = TypeName.string2TypeName("Landroid/app/Fragment"); public static final TypeReference Fragment = TypeReference.findOrCreate(ClassLoaderReference.Primordial, FragmentName); public static final TypeName ServiceName = TypeName.string2TypeName("Landroid/app/Service"); public static final TypeReference Service = TypeReference.findOrCreate(ClassLoaderReference.Primordial, ServiceName); public static final TypeName IntentServiceName = TypeName.string2TypeName("Landroid/app/IntentService"); public static final TypeReference IntentService = TypeReference.findOrCreate(ClassLoaderReference.Primordial, IntentServiceName); public static final TypeName AbstractInputMethodServiceName = TypeName.string2TypeName("Landroid/inputmethodservice/AbstractInputMethodService"); public static final TypeReference AbstractInputMethodService = TypeReference.findOrCreate(ClassLoaderReference.Primordial, AbstractInputMethodServiceName); public static final TypeName AccessibilityServiceName = TypeName.string2TypeName("Landroid/accessibilityservice/AccessibilityService"); public static final TypeReference AccessibilityService = TypeReference.findOrCreate(ClassLoaderReference.Primordial, AccessibilityServiceName); public static final TypeName DreamServiceName = TypeName.string2TypeName("Landroid/service/dreams/DreamService"); public static final TypeReference DreamService = TypeReference.findOrCreate(ClassLoaderReference.Primordial, DreamServiceName); public static final TypeName HostApduServiceName = TypeName.string2TypeName("Landroid/nfc/cardemulation/HostApduService"); public static final TypeReference HostApduService = TypeReference.findOrCreate(ClassLoaderReference.Primordial, HostApduServiceName); public static final TypeName MediaRouteProviderServiceName = TypeName.string2TypeName("Landroid/support/v7/media/MediaRouteProviderService"); public static final TypeReference MediaRouteProviderService = TypeReference.findOrCreate(ClassLoaderReference.Primordial, MediaRouteProviderServiceName); public static final TypeName NotificationListenerServiceName = TypeName.string2TypeName("Landroid/service/notification/NotificationListenerService"); public static final TypeReference NotificationListenerService = TypeReference.findOrCreate(ClassLoaderReference.Primordial, NotificationListenerServiceName); public static final TypeName OffHostApduServiceName = TypeName.string2TypeName("Landroid/nfc/cardemulation/OffHostApduService"); public static final TypeReference OffHostApduService = TypeReference.findOrCreate(ClassLoaderReference.Primordial, OffHostApduServiceName); public static final TypeName PrintServiceName = TypeName.string2TypeName("Landroid/printservice/PrintService"); public static final TypeReference PrintService = TypeReference.findOrCreate(ClassLoaderReference.Primordial, PrintServiceName); public static final TypeName RecognitionServiceName = TypeName.string2TypeName("Landroid/speech/RecognitionService"); public static final TypeReference RecognitionService = TypeReference.findOrCreate(ClassLoaderReference.Primordial, RecognitionServiceName); public static final TypeName RemoteViewsServiceName = TypeName.string2TypeName("Landroid/widget/RemoteViewsService"); public static final TypeReference RemoteViewsService = TypeReference.findOrCreate(ClassLoaderReference.Primordial, RemoteViewsServiceName); public static final TypeName SettingInjectorServiceName = TypeName.string2TypeName("Landroid/location/SettingInjectorService"); public static final TypeReference SettingInjectorService = TypeReference.findOrCreate(ClassLoaderReference.Primordial, SettingInjectorServiceName); public static final TypeName SpellCheckerServiceName = TypeName.string2TypeName("Landroid/service/textservice/SpellCheckerService"); public static final TypeReference SpellCheckerService = TypeReference.findOrCreate(ClassLoaderReference.Primordial, SpellCheckerServiceName); public static final TypeName TextToSpeechServiceName = TypeName.string2TypeName("Landroid/speech/tts/TextToSpeechService"); public static final TypeReference TextToSpeechService = TypeReference.findOrCreate(ClassLoaderReference.Primordial, TextToSpeechServiceName); public static final TypeName VpnServiceName = TypeName.string2TypeName("Landroid/net/VpnService"); public static final TypeReference VpnService = TypeReference.findOrCreate(ClassLoaderReference.Primordial, VpnServiceName); public static final TypeName WallpaperServiceName = TypeName.string2TypeName("Landroid/service/wallpaper/WallpaperService"); public static final TypeReference WallpaperService = TypeReference.findOrCreate(ClassLoaderReference.Primordial, WallpaperServiceName); public static final TypeName InputMethodServiceName = TypeName.string2TypeName("Landroid/inputmethodservice/InputMethodService"); public static final TypeReference InputMethodService = TypeReference.findOrCreate(ClassLoaderReference.Primordial, InputMethodServiceName); public static final TypeName ContentProviderName = TypeName.string2TypeName("Landroid/content/ContentProvider"); public static final TypeReference ContentProvider = TypeReference.findOrCreate(ClassLoaderReference.Primordial, ContentProviderName); public static final TypeName BroadcastReceiverName = TypeName.string2TypeName("Landroid/content/BroadcastReceiver"); public static final TypeReference BroadcastReceiver = TypeReference.findOrCreate(ClassLoaderReference.Primordial, BroadcastReceiverName); public static final TypeName ContentResolverName = TypeName.string2TypeName("Landroid/content/ContentResolver"); public static final TypeReference ContentResolver = TypeReference.findOrCreate(ClassLoaderReference.Primordial, ContentResolverName); public static final TypeName MenuName = TypeName.findOrCreate("Landroid/view/Menu"); public static final TypeReference Menu = TypeReference.findOrCreate(ClassLoaderReference.Primordial, MenuName); public static final TypeName ContextMenuName = TypeName.findOrCreate("Landroid/view/ContextMenu"); public static final TypeReference ContextMenu = TypeReference.findOrCreate(ClassLoaderReference.Primordial, ContextMenuName); public static final TypeName MenuItemName = TypeName.findOrCreate("Landroid/view/MenuItem"); public static final TypeReference MenuItem = TypeReference.findOrCreate(ClassLoaderReference.Primordial, MenuItemName); public static final TypeName TelephonyManagerName = TypeName.findOrCreate("Landroid/telephony/TelephonyManager"); public static final TypeReference TelephonyManager = TypeReference.findOrCreate(ClassLoaderReference.Primordial, TelephonyManagerName); public static final TypeName ActionModeName = TypeName.findOrCreate("Landroid/view/ActionMode"); public static final TypeReference ActionMode = TypeReference.findOrCreate(ClassLoaderReference.Primordial, ActionModeName); public static final TypeName AttributeSetName = TypeName.findOrCreate("Landroid/util/AttributeSet"); public static final TypeReference AttributeSet = TypeReference.findOrCreate(ClassLoaderReference.Primordial, AttributeSetName); public static final TypeName ActionModeCallbackName = TypeName.findOrCreate("Landroid/view/ActionMode$Callback"); public static final TypeReference ActionModeCallback = TypeReference.findOrCreate(ClassLoaderReference.Primordial, ActionModeCallbackName); public static final TypeName BundleName = TypeName.findOrCreate("Landroid/os/Bundle"); public static final TypeReference Bundle = TypeReference.findOrCreate(ClassLoaderReference.Primordial, BundleName); public static final TypeName IntentSenderName = TypeName.findOrCreate("Landroid/content/IntentSender"); public static final TypeReference IntentSender = TypeReference.findOrCreate(ClassLoaderReference.Primordial, IntentSenderName); public static final TypeName IIntentSenderName = TypeName.findOrCreate("Landroid/content/IIntentSender"); public static final TypeReference IIntentSender = TypeReference.findOrCreate(ClassLoaderReference.Primordial, IntentSenderName); public static final TypeName IBinderName = TypeName.findOrCreate("Landroid/os/IBinder"); public static final TypeReference IBinder = TypeReference.findOrCreate(ClassLoaderReference.Primordial, IBinderName); public static final TypeName ActivityThreadName = TypeName.findOrCreate("Landroid/app/ActivityThread"); public static final TypeReference ActivityThread = TypeReference.findOrCreate(ClassLoaderReference.Primordial, ActivityThreadName); public static final TypeName ContextName = TypeName.findOrCreate("Landroid/content/Context"); public static final TypeReference Context = TypeReference.findOrCreate(ClassLoaderReference.Primordial, ContextName); public static final TypeName ContextWrapperName = TypeName.findOrCreate("Landroid/content/ContextWrapper"); public static final TypeReference ContextWrapper = TypeReference.findOrCreate(ClassLoaderReference.Primordial, ContextWrapperName); public static final TypeName ContextImplName = TypeName.findOrCreate("Landroid/app/ContextImpl"); public static final TypeReference ContextImpl = TypeReference.findOrCreate(ClassLoaderReference.Primordial, ContextImplName); public static final TypeName BridgeContextName = TypeName.findOrCreate("Lcom/android/layoutlib/bridge/android/BridgeContext"); public static final TypeReference BridgeContext = TypeReference.findOrCreate(ClassLoaderReference.Primordial, BridgeContextName); public static final TypeName ContextThemeWrapperName = TypeName.findOrCreate("Landroid/view/ContextThemeWrapper"); public static final TypeReference ContextThemeWrapper = TypeReference.findOrCreate(ClassLoaderReference.Primordial, ContextThemeWrapperName); public static final TypeName PolicyManagerName = TypeName.findOrCreate("Lcom/android/internal/policy/PolicyManager"); public static final TypeReference PolicyManager = TypeReference.findOrCreate(ClassLoaderReference.Primordial, PolicyManagerName); public static final TypeName WindowName = TypeName.findOrCreate("Landroid/view/Window"); public static final TypeReference Window = TypeReference.findOrCreate(ClassLoaderReference.Primordial, WindowName); public static final TypeName UserHandleName = TypeName.findOrCreate("Landroid/os/UserHandle"); public static final TypeReference UserHandle = TypeReference.findOrCreate(ClassLoaderReference.Primordial, UserHandleName); public static final TypeName LoadedApkName = TypeName.findOrCreate("Landroid/app/LoadedApk"); public static final TypeReference LoadedApk = TypeReference.findOrCreate(ClassLoaderReference.Primordial, LoadedApkName); public static final TypeName ResourcesName = TypeName.findOrCreate("Landroid/content/res/Resources"); public static final TypeReference Resources = TypeReference.findOrCreate(ClassLoaderReference.Primordial, ResourcesName); public static final TypeName InstrumentationName = TypeName.findOrCreate("Landroid/app/Instrumentation"); public static final TypeReference Instrumentation = TypeReference.findOrCreate(ClassLoaderReference.Primordial, InstrumentationName); public static final TypeName ActivityInfoName = TypeName.findOrCreate("Landroid/content/pm/ActivityInfo"); public static final TypeReference ActivityInfo = TypeReference.findOrCreate(ClassLoaderReference.Primordial, ActivityInfoName); public static final TypeName ConfigurationName = TypeName.findOrCreate("Landroid/content/res/Configuration"); public static final TypeReference Configuration = TypeReference.findOrCreate(ClassLoaderReference.Primordial, ConfigurationName); public static final TypeName KeyEventName = TypeName.findOrCreate("Landroid/view/KeyEvent"); public enum AndroidContextType { CONTEXT_IMPL, CONTEXT_BRIDGE, ACTIVITY, APPLICATION, SERVICE, /** For internal use during development */ USELESS } }
15,477
56.970037
100
java
WALA
WALA-master/dalvik/src/main/java/com/ibm/wala/dalvik/util/package-info.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 under the terms listed below. * */ /* * Copyright (c) 2013, * Tobias Blaschke <code@tobiasblaschke.de> * All rights reserved. * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The names of the contributors may not be used to endorse or promote * products derived from this software without specific prior written * permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ /** * Classes of general use with the AndroidModel. * * <p>These include mainly locationg and managing EntryPoints. The model howver is built in the * androidModel-Package. * * @author Tobias Blaschke &lt;code@tobiasblaschke.de&gt; */ package com.ibm.wala.dalvik.util;
2,161
42.24
95
java
WALA
WALA-master/dalvik/src/main/java/com/ibm/wala/dalvik/util/androidEntryPoints/ActivityEP.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 under the terms listed below. * */ /* * Copyright (c) 2013, * Tobias Blaschke <code@tobiasblaschke.de> * All rights reserved. * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The names of the contributors may not be used to endorse or promote * products derived from this software without specific prior written * permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ package com.ibm.wala.dalvik.util.androidEntryPoints; import com.ibm.wala.dalvik.ipa.callgraph.impl.AndroidEntryPoint; import com.ibm.wala.dalvik.ipa.callgraph.impl.AndroidEntryPoint.ExecutionOrder; import com.ibm.wala.dalvik.util.AndroidEntryPointLocator.AndroidPossibleEntryPoint; import java.util.List; /** * Hardcoded EntryPoint-specifications for an Android-Activity. * * <p>The specifications are read and handled by AndroidEntryPointLocator. * * @see com.ibm.wala.dalvik.util.AndroidEntryPointLocator * @author Tobias Blaschke &lt;code@tobiasblaschke.de&gt; */ public final class ActivityEP { // see: http://developer.android.com/reference/android/app/Activity.html // // The entrypoints for the start and stop of the activity come first. // Then some view-handling ones // they are followed by user interaction stuff // /** * Called after App.onCreate - assumed to be before Service.onCreate. * * <p>This does not have to be called before Service.onCreate but the user assumably starts most * apps with an activity we place it slightly before the Services */ public static final AndroidPossibleEntryPoint onCreate = new AndroidPossibleEntryPoint( "onCreate", ExecutionOrder.after( new AndroidEntryPoint.IExecutionOrder[] { ExecutionOrder.AT_FIRST, // ApplicationEP.onCreate, // Uncommenting would create a ring-dependency })); // , // new AndroidEntryPoint.IExecutionOrder[] { // //ServiceEP.onCreate // Not necessarily but let's assume it // XXX: // Causes Loop // } // )); /** * Called a view steps before the Activity gets visible. * * <p>Called after onCreate(Bundle) — or after onRestart() when the activity had been stopped, but * is now again being displayed to the user. It will be followed by onResume(). */ public static final AndroidPossibleEntryPoint onStart = new AndroidPossibleEntryPoint( "onStart", ExecutionOrder.after( new AndroidEntryPoint.IExecutionOrder[] {onCreate, ExecutionOrder.START_OF_LOOP})); /** * Restores the View-State (and may do other stuff). * * <p>This method is called after onStart() when the activity is being re-initialized from a * previously saved state, given here in savedInstanceState. * * <p>The default implementation of this method performs a restore of any view state that had * previously been frozen by onSaveInstanceState(Bundle). * * <p>This method is called between onStart() and onPostCreate(Bundle). */ public static final AndroidPossibleEntryPoint onRestoreInstanceState = new AndroidPossibleEntryPoint("onRestoreInstanceState", ExecutionOrder.after(onStart)); /** * Called when activity start-up is complete. * * <p>Called after onStart() and onRestoreInstanceState(Bundle) */ public static final AndroidPossibleEntryPoint onPostCreate = new AndroidPossibleEntryPoint( "onPostCreate", ExecutionOrder.after( new AndroidEntryPoint.IExecutionOrder[] { onRestoreInstanceState, onStart, ExecutionOrder.START_OF_LOOP })); /** * Activity starts interacting with the user. * * <p>Called after onRestoreInstanceState(Bundle), onRestart(), or onPause() Use * onWindowFocusChanged(boolean) to know for certain that your activity is visible to the user. */ public static final AndroidPossibleEntryPoint onResume = new AndroidPossibleEntryPoint( "onResume", ExecutionOrder.after( new AndroidEntryPoint.IExecutionOrder[] { onPostCreate, onRestoreInstanceState, // onRestart defined later.. // onPause defined later // ExecutionOrder.MIDDLE_OF_LOOP })); /** Called when activity resume is complete. */ public static final AndroidPossibleEntryPoint onPostResume = new AndroidPossibleEntryPoint("onPostResume", ExecutionOrder.after(onResume)); /** * Activity is re-launched while at the top of the activity stack instead of a new instance of the * activity being started. onNewIntent() will be called on the existing instance with the Intent * that was used to re-launch it. * * <p>An activity will always be paused before receiving a new intent, so you can count on * onResume() being called after this method. */ public static final AndroidPossibleEntryPoint onNewIntent = new AndroidPossibleEntryPoint( "onNewIntent", ExecutionOrder.between( new AndroidEntryPoint.IExecutionOrder[] { onPostCreate, onRestoreInstanceState, }, onResume)); /** * Called when you are no longer visible to the user. * * <p>Next call will be either onRestart(), onDestroy(), or nothing, depending on later user * activity. */ public static final AndroidPossibleEntryPoint onStop = new AndroidPossibleEntryPoint("onStop", ExecutionOrder.after(ExecutionOrder.END_OF_LOOP)); /** * Current activity is being re-displayed to the user. * * <p>Called after onStop(), followed by onStart() and then onResume(). */ public static final AndroidPossibleEntryPoint onRestart = new AndroidPossibleEntryPoint("onRestart", ExecutionOrder.after(onStop)); /** * Called to retrieve per-instance state from an activity before being killed. * * <p>It will get restored by onCreate(Bundle) or onRestoreInstanceState(Bundle). * * <p>If called, this method will occur before onStop(). There are no guarantees about whether it * will occur before or after onPause(). */ public static final AndroidPossibleEntryPoint onSaveInstanceState = new AndroidPossibleEntryPoint("onSaveInstanceState", ExecutionOrder.after(onPostResume)); /** * Activity is going to the background. * * <p>Activity has not (yet) been killed. The counterpart to onResume(). * * <p>In situations where the system needs more memory it may kill paused processes to reclaim * resources. In general onSaveInstanceState(Bundle) is used to save per-instance state in the * activity and this method is used to store global persistent data (in content providers, files, * etc.) * * <p>After receiving this call you will usually receive a following call to onStop() however in * some cases there will be a direct call back to onResume() without going through the stopped * state. */ public static final AndroidPossibleEntryPoint onPause = new AndroidPossibleEntryPoint( "onPause", ExecutionOrder.after( new AndroidEntryPoint.IExecutionOrder[] { onResume, onSaveInstanceState, ExecutionOrder.MIDDLE_OF_LOOP })); /** * Perform any final cleanup before an activity is destroyed. * * <p>Someone called finish() on the Activity, or the system is temporarily destroying this * Activity to save space. There are situations where the system will simply kill the activity's * hosting process without calling this method. */ public static final AndroidPossibleEntryPoint onDestroy = new AndroidPossibleEntryPoint( "onDestroy", ExecutionOrder.after( new AndroidEntryPoint.IExecutionOrder[] {onStop, ExecutionOrder.AT_LAST})); /** Called when an Activity started by this one returns its result. */ public static final AndroidPossibleEntryPoint onActivityResult = new AndroidPossibleEntryPoint( "onActivityResult", ExecutionOrder.after( new AndroidEntryPoint.IExecutionOrder[] { ExecutionOrder.MULTIPLE_TIMES_IN_LOOP, // If this Activity starts an notherone it most certainly goes into background so // place this after onPause onPause })); // // View stuff // /** * Accessibility events that are sent by the system when something notable happens in the user * interface. For example, when a Button is clicked, a View is focused, etc. * * <p>TODO: Assert included everywhere */ public static final AndroidPossibleEntryPoint dispatchPopulateAccessibilityEvent = new AndroidPossibleEntryPoint( "dispatchPopulateAccessibilityEvent", ExecutionOrder.after( new AndroidEntryPoint.IExecutionOrder[] { ExecutionOrder.AT_FIRST, onCreate // TODO: where to put? })); /** Helper */ private static final ExecutionOrder getVisible = ExecutionOrder.after( new AndroidEntryPoint.IExecutionOrder[] { ExecutionOrder.START_OF_LOOP, onResume, onPostCreate, dispatchPopulateAccessibilityEvent }); private static final ExecutionOrder allInitialViewsSetUp = ExecutionOrder.between( getVisible, new AndroidEntryPoint.IExecutionOrder[] { ExecutionOrder.MIDDLE_OF_LOOP, onStop, onPause, onSaveInstanceState }); /** * Callback for creating dialogs that are managed (saved and restored) for you by the activity. * * <p>If you would like an opportunity to prepare your dialog before it is shown, override * onPrepareDialog. * * <p>This method was deprecated in API level 13. */ public static final AndroidPossibleEntryPoint onCreateDialog = new AndroidPossibleEntryPoint( "onCreateDialog", ExecutionOrder.between( new AndroidEntryPoint.IExecutionOrder[] { getVisible, // ExecutionOrder.MIDDLE_OF_LOOP, // Why? }, allInitialViewsSetUp)); /** * Provides an opportunity to prepare a managed dialog before it is being shown. * * <p>This method was deprecated in API level 13. */ public static final AndroidPossibleEntryPoint onPrepareDialog = new AndroidPossibleEntryPoint( "onPrepareDialog", ExecutionOrder.between( new AndroidEntryPoint.IExecutionOrder[] { onCreateDialog, getVisible, }, allInitialViewsSetUp)); /** * used when inflating with the LayoutInflater returned by getSystemService(String). * * <p>TODO: More info This implementation handles tags to embed fragments inside of the activity. */ public static final AndroidPossibleEntryPoint onCreateView = new AndroidPossibleEntryPoint( "onCreateView", ExecutionOrder.between( new AndroidEntryPoint.IExecutionOrder[] { getVisible, onPostCreate // Create or Post? }, allInitialViewsSetUp)); /** * Called when a Fragment is being attached to this activity, immediately after the call to its * Fragment.onAttach() method and before Fragment.onCreate(). */ public static final AndroidPossibleEntryPoint onAttachFragment = new AndroidPossibleEntryPoint( "onAttachFragment", ExecutionOrder.between( new AndroidEntryPoint.IExecutionOrder[] {onCreateView, getVisible}, allInitialViewsSetUp)); /** * Called when the main window associated with the activity has been attached to the window * manager. See View.onAttachedToWindow() for more information. # TODO: See * * <p>Note that this function is guaranteed to be called before View.onDraw including before or * after onMeasure(int, int). */ public static final AndroidPossibleEntryPoint onAttachedToWindow = new AndroidPossibleEntryPoint( "onAttachedToWindow", ExecutionOrder.between( new AndroidEntryPoint.IExecutionOrder[] {onCreateView, getVisible}, allInitialViewsSetUp)); /** * Called when the main window associated with the activity has been detached from the window * manager. See View.onDetachedFromWindow() for more information. # TODO See */ public static final AndroidPossibleEntryPoint onDetachedFromWindow = new AndroidPossibleEntryPoint( "onDetachedFromWindow", ExecutionOrder.between( new AndroidEntryPoint.IExecutionOrder[] { onAttachedToWindow, // ExecutionOrder.END_OF_LOOP, // XXX: Why doesn't this work? }, new AndroidEntryPoint.IExecutionOrder[] { ExecutionOrder.AFTER_LOOP, onStop, onSaveInstanceState, onPause })); /** * This hook is called whenever the content view of the screen changes. * * <p>Due to a call to Window.setContentView or Window.addContentView */ public static final AndroidPossibleEntryPoint onContentChanged = new AndroidPossibleEntryPoint( "onContentChanged", ExecutionOrder.between( new AndroidEntryPoint.IExecutionOrder[] { onCreateView, getVisible // TODO }, new AndroidEntryPoint.IExecutionOrder[] { ExecutionOrder.MULTIPLE_TIMES_IN_LOOP, // TODO onStop, onPause, onSaveInstanceState })); /** * Called by setTheme(int) and getTheme() to apply a theme resource to the current Theme object. * * <p>TODO: Do we have to register an entrypoint for this? */ public static final AndroidPossibleEntryPoint onApplyThemeResource = new AndroidPossibleEntryPoint( "onApplyThemeResource", ExecutionOrder.directlyAfter(onStart) // Narf ); /** * TODO: GET MORE INFO ON THIS!. * * <p>This simply returns null so that all panel sub-windows will have the default menu behavior. */ public static final AndroidPossibleEntryPoint onCreatePanelView = new AndroidPossibleEntryPoint( "onCreatePanelView", ExecutionOrder.between(getVisible, allInitialViewsSetUp)); /** * TODO: GET MORE INFO ON THIS!. * * <p>This calls through to the new onCreateOptionsMenu(Menu) method for the FEATURE_OPTIONS_PANEL * panel */ public static final AndroidPossibleEntryPoint onCreatePanelMenu = new AndroidPossibleEntryPoint( "onCreatePanelMenu", ExecutionOrder.between(getVisible, allInitialViewsSetUp)); /** * TODO: GET MORE INFO ON THIS!. * * <p>This calls through to the new onPrepareOptionsMenu(Menu) method for the * FEATURE_OPTIONS_PANEL */ public static final AndroidPossibleEntryPoint onPreparePanel = new AndroidPossibleEntryPoint( "onPreparePanel", ExecutionOrder.between( new AndroidEntryPoint.IExecutionOrder[] { getVisible, onCreatePanelMenu, // TODO Verify onCreatePanelView, // ExecutionOrder.MIDDLE_OF_LOOP, // TODO: Do Multiple times? }, allInitialViewsSetUp)); /** * TODO: GET MORE INFO ON THIS!. * * <p>This calls through to onOptionsMenuClosed(Menu) method for the FEATURE_OPTIONS_PANEL. For * context menus (FEATURE_CONTEXT_MENU), the onContextMenuClosed(Menu) will be called. */ public static final AndroidPossibleEntryPoint onPanelClosed = new AndroidPossibleEntryPoint( "onPanelClosed", ExecutionOrder.between( new AndroidEntryPoint.IExecutionOrder[] { onCreatePanelMenu, onCreatePanelView, onPreparePanel, ExecutionOrder.MIDDLE_OF_LOOP, // TODO: Do Later? getVisible, allInitialViewsSetUp }, ExecutionOrder.AFTER_LOOP)); /** * Called when a context menu for the view is about to be shown. * * <p>Unlike onCreateOptionsMenu(Menu), this will be called every time the context menu is about * to be shown. * * <p>Use onContextItemSelected(android.view.MenuItem) to know when an item has been selected. */ public static final AndroidPossibleEntryPoint onCreateContextMenu = new AndroidPossibleEntryPoint( "onCreateContextMenu", ExecutionOrder.between(getVisible, allInitialViewsSetUp)); /** * TODO: How does this correlate to onMenuItemSelected. * * <p>You can use this method for any items for which you would like to do processing without * those other facilities. */ public static final AndroidPossibleEntryPoint onContextItemSelected = new AndroidPossibleEntryPoint( "onContextItemSelected", ExecutionOrder.between( new AndroidEntryPoint.IExecutionOrder[] { onCreateContextMenu, getVisible, ExecutionOrder.MIDDLE_OF_LOOP, // TODO: Do Later? }, onPanelClosed // XXX?? )); /** * This hook is called whenever the context menu is being closed. * * <p>either by the user canceling the menu with the back/menu button, or when an item is * selected. */ public static final AndroidPossibleEntryPoint onContextMenuClosed = new AndroidPossibleEntryPoint( "onContextMenuClosed", ExecutionOrder.between( new AndroidEntryPoint.IExecutionOrder[] { onCreateContextMenu, onContextItemSelected, getVisible }, ExecutionOrder.AFTER_LOOP // To much? XXX )); public static final AndroidPossibleEntryPoint onCreateOptionsMenu = new AndroidPossibleEntryPoint( "onCreateOptionsMenu", ExecutionOrder.directlyAfter( onCreateContextMenu) // TODO: Well it behaves different! See onPrepareOptionsMenu, ); public static final AndroidPossibleEntryPoint onOptionsItemSelected = new AndroidPossibleEntryPoint( "onOptionsItemSelected", ExecutionOrder.directlyAfter(onContextItemSelected)); public static final AndroidPossibleEntryPoint onPrepareOptionsMenu = new AndroidPossibleEntryPoint( "onPrepareOptionsMenu", ExecutionOrder.between( new AndroidEntryPoint.IExecutionOrder[] {onCreateOptionsMenu, getVisible}, new AndroidEntryPoint.IExecutionOrder[] { onOptionsItemSelected, allInitialViewsSetUp })); public static final AndroidPossibleEntryPoint onOptionsMenuClosed = new AndroidPossibleEntryPoint( "onOptionsMenuClosed", ExecutionOrder.directlyAfter(onContextMenuClosed)); /** TODO: More Info */ public static final AndroidPossibleEntryPoint onMenuOpened = new AndroidPossibleEntryPoint( "onMenuOpened", ExecutionOrder.between( new AndroidEntryPoint.IExecutionOrder[] { onCreateOptionsMenu, onPrepareOptionsMenu, onCreateContextMenu, getVisible }, new AndroidEntryPoint.IExecutionOrder[] { onOptionsItemSelected, onContextItemSelected, allInitialViewsSetUp })); /** * TODO More info. * * <p>This calls through to the new onOptionsItemSelected(MenuItem) */ public static final AndroidPossibleEntryPoint onMenuItemSelected = new AndroidPossibleEntryPoint( "onMenuItemSelected", ExecutionOrder.between( new AndroidEntryPoint.IExecutionOrder[] { onCreateContextMenu, onPrepareOptionsMenu, onMenuOpened, getVisible }, new AndroidEntryPoint.IExecutionOrder[] { onOptionsItemSelected, // Calls through to this functions onContextItemSelected, allInitialViewsSetUp })); public static final AndroidPossibleEntryPoint onTitleChanged = new AndroidPossibleEntryPoint( "onTitleChanged", ExecutionOrder.directlyAfter(getVisible) // TODO: What placement to choose? ); public static final AndroidPossibleEntryPoint onChildTitleChanged = new AndroidPossibleEntryPoint( "onChildTitleChanged", ExecutionOrder.directlyAfter(onTitleChanged)); // // User Interaction // /** * Called whenever a key, touch, or trackball event is dispatched to the activity. * * <p>This callback and onUserLeaveHint() are intended to help activities manage status bar * notifications intelligently; specifically, for helping activities determine the proper time to * cancel a notification. * * <p>All calls to your activity's onUserLeaveHint() callback will be accompanied by calls to * onUserInteraction(). * * <p>Note that this callback will be invoked for the touch down action that begins a touch * gesture, but may not be invoked for the touch-moved and touch-up actions that follow. */ public static final AndroidPossibleEntryPoint onUserInteraction = new AndroidPossibleEntryPoint( "onUserInteraction", ExecutionOrder.after( new AndroidEntryPoint.IExecutionOrder[] { getVisible, allInitialViewsSetUp, dispatchPopulateAccessibilityEvent, ExecutionOrder.MULTIPLE_TIMES_IN_LOOP })); public static final AndroidPossibleEntryPoint dispatchTouchEvent = new AndroidPossibleEntryPoint( "dispatchTouchEvent", ExecutionOrder.after( new AndroidEntryPoint.IExecutionOrder[] { // TODO: Relation to onGenericMotionEvent onUserInteraction, // TODO: Verify getVisible, allInitialViewsSetUp, dispatchPopulateAccessibilityEvent, ExecutionOrder.MULTIPLE_TIMES_IN_LOOP })); /** * Called when a touch screen event was not handled by any of the views under it. * * <p>This is most useful to process touch events that happen outside of your window bounds, where * there is no view to receive it. */ public static final AndroidPossibleEntryPoint onTouchEvent = new AndroidPossibleEntryPoint( "onTouchEvent", ExecutionOrder.after( new AndroidEntryPoint.IExecutionOrder[] { // TODO: Relation to onGenericMotionEvent onUserInteraction, // TODO: Verify dispatchPopulateAccessibilityEvent, dispatchTouchEvent })); /** * You can override this to intercept all generic motion events before they are dispatched to the * window. * * <p>TODO: Verify before on... stuff */ public static final AndroidPossibleEntryPoint dispatchGenericMotionEvent = new AndroidPossibleEntryPoint( "dispatchGenericMotionEvent", ExecutionOrder.after( new AndroidEntryPoint.IExecutionOrder[] { onUserInteraction, // TODO: Verify getVisible, dispatchPopulateAccessibilityEvent, allInitialViewsSetUp, ExecutionOrder.MULTIPLE_TIMES_IN_LOOP })); /** * Called when a generic motion event was not handled by any of the views inside of the activity. * * <p>Generic motion events with source class SOURCE_CLASS_POINTER are delivered to the view under * the pointer. All other generic motion events are delivered to the focused view. * * <p>TODO: After onUserInteraction? */ public static final AndroidPossibleEntryPoint onGenericMotionEvent = new AndroidPossibleEntryPoint( "onGenericMotionEvent", ExecutionOrder.after(dispatchGenericMotionEvent)); public static final AndroidPossibleEntryPoint dispatchTrackballEvent = new AndroidPossibleEntryPoint( "dispatchTrackballEvent", ExecutionOrder.after( new AndroidEntryPoint.IExecutionOrder[] { dispatchPopulateAccessibilityEvent, onUserInteraction, // TODO: Verify onGenericMotionEvent, // TODO: Verify getVisible, allInitialViewsSetUp, ExecutionOrder.MULTIPLE_TIMES_IN_LOOP })); /** * Called when the trackball was moved and not handled by any of the views inside of the activity. * * <p>The call here happens before trackball movements are converted to DPAD key events, which * then get sent back to the view hierarchy, and will be processed at the point for things like * focus navigation. */ public static final AndroidPossibleEntryPoint onTrackballEvent = new AndroidPossibleEntryPoint( "onTrackballEvent", ExecutionOrder.after( new AndroidEntryPoint.IExecutionOrder[] { dispatchTrackballEvent, onUserInteraction, // TODO: Verify onGenericMotionEvent, // TODO: Verify })); /** * You can override this to intercept all key events before they are dispatched to the window. * TODO: Verify before on... stuff */ public static final AndroidPossibleEntryPoint dispatchKeyEvent = new AndroidPossibleEntryPoint( "dispatchKeyEvent", ExecutionOrder.after( new AndroidEntryPoint.IExecutionOrder[] { onUserInteraction, // TODO: Verify onTrackballEvent, // DPAD key events TODO: Verify getVisible, allInitialViewsSetUp, dispatchPopulateAccessibilityEvent, ExecutionOrder.MULTIPLE_TIMES_IN_LOOP })); public static final AndroidPossibleEntryPoint dispatchKeyShortcutEvent = new AndroidPossibleEntryPoint( "dispatchKeyShortcutEvent", ExecutionOrder.after( new AndroidEntryPoint.IExecutionOrder[] { dispatchKeyEvent, onUserInteraction, // TODO: Verify onTrackballEvent, // DPAD key events TODO: Verify getVisible, allInitialViewsSetUp, dispatchPopulateAccessibilityEvent, ExecutionOrder.MULTIPLE_TIMES_IN_LOOP })); /** * The default implementation takes care of KEYCODE_BACK by calling onBackPressed(), though the * behavior varies based on the application compatibility mode: for ECLAIR or later applications, * it will set up the dispatch to call onKeyUp(int, KeyEvent) where the action will be performed; * for earlier applications, it will perform the action immediately in on-down, as those versions * of the platform behaved. * * <p>TODO: After onUserInteraction? */ public static final AndroidPossibleEntryPoint onKeyDown = new AndroidPossibleEntryPoint( "onKeyDown", ExecutionOrder.after( new AndroidEntryPoint.IExecutionOrder[] { onUserInteraction, dispatchKeyEvent, onTrackballEvent // DPAD key events })); public static final AndroidPossibleEntryPoint onKeyLongPress = new AndroidPossibleEntryPoint( "onKeyLongPress", ExecutionOrder.after( new AndroidEntryPoint.IExecutionOrder[] {dispatchKeyEvent, onKeyDown})); public static final AndroidPossibleEntryPoint onKeyMultiple = new AndroidPossibleEntryPoint( "onKeyMultiple", ExecutionOrder.after( new AndroidEntryPoint.IExecutionOrder[] {dispatchKeyEvent, onKeyDown})); public static final AndroidPossibleEntryPoint onKeyShortcut = new AndroidPossibleEntryPoint( "onKeyShortcut", ExecutionOrder.after( new AndroidEntryPoint.IExecutionOrder[] { dispatchKeyEvent, dispatchKeyShortcutEvent, onKeyDown })); /** The default implementation handles KEYCODE_BACK to stop the activity and go back. */ public static final AndroidPossibleEntryPoint onKeyUp = new AndroidPossibleEntryPoint( "onKeyUp", ExecutionOrder.after( new AndroidEntryPoint.IExecutionOrder[] { dispatchKeyEvent, onKeyDown, onKeyLongPress, onKeyMultiple, onKeyShortcut })); public static final AndroidPossibleEntryPoint onBackPressed = new AndroidPossibleEntryPoint( "onBackPressed", ExecutionOrder.after( // TODO Why is this so late? new AndroidEntryPoint.IExecutionOrder[] { dispatchKeyEvent, onKeyDown, // May be both of them depending on version onKeyUp })); /** This method will be invoked by the default implementation of onNavigateUp() */ public static final AndroidPossibleEntryPoint onCreateNavigateUpTaskStack = new AndroidPossibleEntryPoint( "onCreateNavigateUpTaskStack", ExecutionOrder.between( new AndroidEntryPoint.IExecutionOrder[] {ExecutionOrder.START_OF_LOOP // onBackPressed // TODO: Verify }, new AndroidEntryPoint.IExecutionOrder[] { onPause, onSaveInstanceState, ExecutionOrder.AFTER_LOOP // TODO This is to LATE! })); /** * Prepare the synthetic task stack that will be generated during Up navigation from a different * task. */ public static final AndroidPossibleEntryPoint onPrepareNavigateUpTaskStack = new AndroidPossibleEntryPoint( "onPrepareNavigateUpTaskStack", ExecutionOrder.between( new AndroidEntryPoint.IExecutionOrder[] { onCreateNavigateUpTaskStack, // onBackPressed // TODO: Verify }, new AndroidEntryPoint.IExecutionOrder[] { onPause, onSaveInstanceState, ExecutionOrder.END_OF_LOOP // TODO This is to LATE! })); /** * This is called when a child activity of this one attempts to navigate up. The default * implementation simply calls onNavigateUp() on this activity (the parent). */ public static final AndroidPossibleEntryPoint onNavigateUpFromChild = new AndroidPossibleEntryPoint( "onNavigateUpFromChild", ExecutionOrder.between( new AndroidEntryPoint.IExecutionOrder[] { onCreateNavigateUpTaskStack, // No // onBackPressed, // TODO: Verify }, new AndroidEntryPoint.IExecutionOrder[] { onCreateNavigateUpTaskStack, onPrepareNavigateUpTaskStack, onSaveInstanceState, onPause })); /** * This method is called whenever the user chooses to navigate Up within your application's * activity hierarchy from the action bar. */ public static final AndroidPossibleEntryPoint onNavigateUp = new AndroidPossibleEntryPoint( "onNavigateUp", ExecutionOrder.between( new AndroidEntryPoint.IExecutionOrder[] { // onBackPressed, // TODO: Verify onNavigateUpFromChild }, new AndroidEntryPoint.IExecutionOrder[] { onCreateNavigateUpTaskStack, onPrepareNavigateUpTaskStack, onSaveInstanceState, onPause })); /** * This hook is called when the user signals the desire to start a search. * * <p>..in response to a menu item, search button, or other widgets within your activity. */ public static final AndroidPossibleEntryPoint onSearchRequested = new AndroidPossibleEntryPoint( "onSearchRequested", ExecutionOrder.after( new AndroidEntryPoint.IExecutionOrder[] { ExecutionOrder.MULTIPLE_TIMES_IN_LOOP, onKeyUp, onTrackballEvent, onOptionsItemSelected, onContextItemSelected, onMenuItemSelected })); // // Misc stuff // /** Menus may depend on it.. */ public static final AndroidPossibleEntryPoint onActionModeStarted = new AndroidPossibleEntryPoint( "onActionModeStarted", ExecutionOrder.MULTIPLE_TIMES_IN_LOOP // TODO where to put?? ); public static final AndroidPossibleEntryPoint onActionModeFinished = new AndroidPossibleEntryPoint( "onActionModeFinished", ExecutionOrder.after(onActionModeStarted)); /** Give the Activity a chance to control the UI for an action mode requested by the system. */ public static final AndroidPossibleEntryPoint onWindowStartingActionMode = new AndroidPossibleEntryPoint( "onWindowStartingActionMode", ExecutionOrder.between( ExecutionOrder.MULTIPLE_TIMES_IN_LOOP, // TODO where to put?? onActionModeStarted)); /** * Will be called if you have selected configurations you would like to handle with the * configChanges attribute in your manifest. If any configuration change occurs that is not * selected to be reported by that attribute, then instead of reporting it the system will stop * and restart the activity */ public static final AndroidPossibleEntryPoint onConfigurationChanged = new AndroidPossibleEntryPoint( "onConfigurationChanged", ExecutionOrder.between( // TODO: Find a nice position new AndroidEntryPoint.IExecutionOrder[] {onStop}, new AndroidEntryPoint.IExecutionOrder[] {onRestart})); public static final AndroidPossibleEntryPoint onSharedPreferenceChanged = new AndroidPossibleEntryPoint( "onSharedPreferenceChanged", ExecutionOrder.between( // TODO: Find a nice position new AndroidEntryPoint.IExecutionOrder[] {onStop}, new AndroidEntryPoint.IExecutionOrder[] {onRestart})); /** This method is called before pausing */ public static final AndroidPossibleEntryPoint onCreateDescription = new AndroidPossibleEntryPoint( "onCreateDescription", ExecutionOrder.between(onSaveInstanceState, onPause)); /** This method is called before pausing */ public static final AndroidPossibleEntryPoint onCreateThumbnail = new AndroidPossibleEntryPoint( "onCreateThumbnail", ExecutionOrder.directlyBefore(onCreateDescription)); /** * This function will be called after any global assist callbacks. * * <p>Assit is requested by the user. TODO: WTF is this? */ public static final AndroidPossibleEntryPoint onProvideAssistData = new AndroidPossibleEntryPoint( "onProvideAssistData", ExecutionOrder.between(allInitialViewsSetUp, ExecutionOrder.MIDDLE_OF_LOOP)); /** * Called by the system, as part of destroying an activity due to a configuration change, when it * is known that a new instance will immediately be created for the new configuration. * * <p>The function will be called between onStop() and onDestroy(). A new instance of the activity * will always be immediately created after this one's onDestroy() is called. */ public static final AndroidPossibleEntryPoint onRetainNonConfigurationInstance = new AndroidPossibleEntryPoint( "onRetainNonConfigurationInstance", ExecutionOrder.between(onStop, onDestroy)); /** * While the exact point at which this will be called is not defined, generally it will happen * when all background process have been killed. That is, before reaching the point of killing * processes hosting service and foreground UI that we would like to avoid killing. */ public static final AndroidPossibleEntryPoint onLowMemory = new AndroidPossibleEntryPoint( "onLowMemory", ExecutionOrder.between( // TODO: find a nice position ExecutionOrder.END_OF_LOOP, new AndroidEntryPoint.IExecutionOrder[] { ExecutionOrder.AFTER_LOOP, onConfigurationChanged // XXX ??!! })); /** * This will happen for example when it goes in the background and there is not enough memory to * keep as many background processes running as desired. */ public static final AndroidPossibleEntryPoint onTrimMemory = new AndroidPossibleEntryPoint( "onTrimMemory", ExecutionOrder.directlyBefore( onLowMemory) // may potentially come before onLowMemory but they are near enough... ); /** * Called as part of the activity lifecycle when an activity is about to go into the background as * the result of user choice. For example, when the user presses the Home key. * * <p>this method is called right before the activity's onPause() callback. */ public static final AndroidPossibleEntryPoint onUserLeaveHint = new AndroidPossibleEntryPoint("onUserLeaveHint", ExecutionOrder.directlyBefore(onPause)); /** This is called whenever the current window attributes change. */ public static final AndroidPossibleEntryPoint onWindowAttributesChanged = new AndroidPossibleEntryPoint( "onWindowAttributesChanged", ExecutionOrder.between( new AndroidEntryPoint.IExecutionOrder[] {ExecutionOrder.MULTIPLE_TIMES_IN_LOOP}, new AndroidEntryPoint.IExecutionOrder[] {ExecutionOrder.END_OF_LOOP})); /** * Called when the current Window of the activity gains or loses focus. * * <p>Note that this provides information about global focus state, which is managed independently * of activity lifecycles. As such, while focus changes will generally have some relation to * lifecycle changes, you should not rely on any particular order between the callbacks here and * those in the other lifecycle methods such as onResume(). */ public static final AndroidPossibleEntryPoint onWindowFocusChanged = new AndroidPossibleEntryPoint( "onWindowFocusChanged", ExecutionOrder.directlyAfter(onResume) // TODO see above... ); /** * Add the EntryPoint specifications defined in this file to the given list. * * @param possibleEntryPoints the list to extend. */ public static void populate(List<? super AndroidPossibleEntryPoint> possibleEntryPoints) { possibleEntryPoints.add(onCreate); possibleEntryPoints.add(onStart); possibleEntryPoints.add(onRestoreInstanceState); possibleEntryPoints.add(onPostCreate); possibleEntryPoints.add(onResume); possibleEntryPoints.add(onPostResume); possibleEntryPoints.add(onNewIntent); possibleEntryPoints.add(onStop); possibleEntryPoints.add(onRestart); possibleEntryPoints.add(onSaveInstanceState); possibleEntryPoints.add(onPause); possibleEntryPoints.add(onDestroy); possibleEntryPoints.add(onActivityResult); possibleEntryPoints.add(dispatchPopulateAccessibilityEvent); possibleEntryPoints.add(onCreateDialog); possibleEntryPoints.add(onPrepareDialog); possibleEntryPoints.add(onCreateView); possibleEntryPoints.add(onAttachFragment); possibleEntryPoints.add(onAttachedToWindow); possibleEntryPoints.add(onDetachedFromWindow); possibleEntryPoints.add(onContentChanged); possibleEntryPoints.add(onApplyThemeResource); possibleEntryPoints.add(onCreatePanelView); possibleEntryPoints.add(onCreatePanelMenu); possibleEntryPoints.add(onPreparePanel); possibleEntryPoints.add(onPanelClosed); possibleEntryPoints.add(onCreateContextMenu); possibleEntryPoints.add(onContextItemSelected); possibleEntryPoints.add(onContextMenuClosed); possibleEntryPoints.add(onCreateOptionsMenu); possibleEntryPoints.add(onOptionsItemSelected); possibleEntryPoints.add(onPrepareOptionsMenu); possibleEntryPoints.add(onOptionsMenuClosed); possibleEntryPoints.add(onMenuOpened); possibleEntryPoints.add(onMenuItemSelected); possibleEntryPoints.add(onTitleChanged); possibleEntryPoints.add(onChildTitleChanged); possibleEntryPoints.add(onUserInteraction); possibleEntryPoints.add(dispatchTouchEvent); possibleEntryPoints.add(onTouchEvent); possibleEntryPoints.add(dispatchGenericMotionEvent); possibleEntryPoints.add(onGenericMotionEvent); possibleEntryPoints.add(dispatchTrackballEvent); possibleEntryPoints.add(onTrackballEvent); possibleEntryPoints.add(dispatchKeyEvent); possibleEntryPoints.add(dispatchKeyShortcutEvent); possibleEntryPoints.add(onKeyDown); possibleEntryPoints.add(onKeyLongPress); possibleEntryPoints.add(onKeyMultiple); possibleEntryPoints.add(onKeyShortcut); possibleEntryPoints.add(onKeyUp); possibleEntryPoints.add(onBackPressed); possibleEntryPoints.add(onCreateNavigateUpTaskStack); possibleEntryPoints.add(onPrepareNavigateUpTaskStack); possibleEntryPoints.add(onNavigateUpFromChild); possibleEntryPoints.add(onNavigateUp); possibleEntryPoints.add(onSearchRequested); possibleEntryPoints.add(onActionModeStarted); possibleEntryPoints.add(onActionModeFinished); possibleEntryPoints.add(onWindowStartingActionMode); possibleEntryPoints.add(onConfigurationChanged); possibleEntryPoints.add(onCreateDescription); possibleEntryPoints.add(onCreateThumbnail); possibleEntryPoints.add(onProvideAssistData); possibleEntryPoints.add(onRetainNonConfigurationInstance); possibleEntryPoints.add(onLowMemory); possibleEntryPoints.add(onTrimMemory); possibleEntryPoints.add(onUserLeaveHint); possibleEntryPoints.add(onWindowAttributesChanged); possibleEntryPoints.add(onWindowFocusChanged); possibleEntryPoints.add(onSharedPreferenceChanged); } }
43,402
40.854388
100
java
WALA
WALA-master/dalvik/src/main/java/com/ibm/wala/dalvik/util/androidEntryPoints/ApplicationEP.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 under the terms listed below. * */ /* * Copyright (c) 2013, * Tobias Blaschke <code@tobiasblaschke.de> * All rights reserved. * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The names of the contributors may not be used to endorse or promote * products derived from this software without specific prior written * permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ package com.ibm.wala.dalvik.util.androidEntryPoints; import com.ibm.wala.dalvik.ipa.callgraph.impl.AndroidEntryPoint; import com.ibm.wala.dalvik.ipa.callgraph.impl.AndroidEntryPoint.ExecutionOrder; import com.ibm.wala.dalvik.util.AndroidEntryPointLocator.AndroidPossibleEntryPoint; import java.util.List; /** * Hardcoded EntryPoint-specifications for an Android-Application. * * <p>The specifications are read and handled by AndroidEntryPointLocator. * * @see <a * href="http://developer.android.com/reference/android/app/Application.html">Application</a> * @see com.ibm.wala.dalvik.util.AndroidEntryPointLocator * @author Tobias Blaschke &lt;code@tobiasblaschke.de&gt; */ public final class ApplicationEP { /** * Called when the application is starting, before any activity, service, or receiver objects * (excluding content providers) have been created. */ public static final AndroidPossibleEntryPoint onCreate = new AndroidPossibleEntryPoint( "onCreate", ExecutionOrder.between( new AndroidEntryPoint.IExecutionOrder[] { ExecutionOrder.AT_FIRST, ProviderEP.onCreate /* Yes, ContentProviders come before App! */ }, new AndroidEntryPoint.IExecutionOrder[] {ActivityEP.onCreate, ServiceEP.onCreate})); /** * Called by the system when the device configuration changes while your component is running. * * <p>Note that, unlike activities, other components are never restarted when a configuration * changes: they must always deal with the results of the change, such as by re-retrieving * resources. */ public static final AndroidPossibleEntryPoint onConfigurationChanged = new AndroidPossibleEntryPoint( "onConfigurationChanged", ExecutionOrder.between( new AndroidEntryPoint.IExecutionOrder[] { ActivityEP.onConfigurationChanged, ExecutionOrder.END_OF_LOOP }, new AndroidEntryPoint.IExecutionOrder[] {ExecutionOrder.AT_LAST})); /** * This is called when the overall system is running low on memory, and actively running processes * should trim their memory usage. * * <p>While the exact point at which this will be called is not defined, generally it will happen * when all background process have been killed. That is, before reaching the point of killing * processes hosting service and foreground UI that we would like to avoid killing. */ public static final AndroidPossibleEntryPoint onLowMemory = new AndroidPossibleEntryPoint( "onLowMemory", ExecutionOrder.between( new AndroidEntryPoint.IExecutionOrder[] { ExecutionOrder.END_OF_LOOP, ActivityEP.onLowMemory }, new AndroidEntryPoint.IExecutionOrder[] { ExecutionOrder.AFTER_LOOP, onConfigurationChanged // XXX ??! })); // /** This method is for use in emulated process environments. */ /* public static final AndroidPossibleEntryPoint onTerminate = new AndroidPossibleEntryPoint(AndroidComponent.APPLICATION, "onTerminate", ExecutionOrder.AT_LAST ); */ /** * Called when the operating system has determined that it is a good time for a process to trim * unneeded memory from its process. */ public static final AndroidPossibleEntryPoint onTrimMemory = new AndroidPossibleEntryPoint( "onTrimMemory", ExecutionOrder.directlyBefore(onLowMemory) // may potentially come before onLowMemory ); /** * Add the EntryPoint specifications defined in this file to the given list. * * @param possibleEntryPoints the list to extend. */ public static void populate(List<? super AndroidPossibleEntryPoint> possibleEntryPoints) { possibleEntryPoints.add(onCreate); possibleEntryPoints.add(onConfigurationChanged); possibleEntryPoints.add(onLowMemory); // possibleEntryPoints.add(onTerminate); possibleEntryPoints.add(onTrimMemory); } }
5,969
41.94964
121
java
WALA
WALA-master/dalvik/src/main/java/com/ibm/wala/dalvik/util/androidEntryPoints/FragmentEP.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 under the terms listed below. * */ /* * Copyright (c) 2013, * Tobias Blaschke <code@tobiasblaschke.de> * All rights reserved. * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The names of the contributors may not be used to endorse or promote * products derived from this software without specific prior written * permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ package com.ibm.wala.dalvik.util.androidEntryPoints; import com.ibm.wala.dalvik.ipa.callgraph.impl.AndroidEntryPoint; import com.ibm.wala.dalvik.ipa.callgraph.impl.AndroidEntryPoint.ExecutionOrder; import com.ibm.wala.dalvik.util.AndroidEntryPointLocator.AndroidPossibleEntryPoint; import java.util.List; /** * Hardcoded EntryPoint-specifications for an Android-Activity. * * <p>The specifications are read and handled by AndroidEntryPointLocator. * * @see <a href="https://developer.android.com/reference/android/app/Fragment.html">Fragment</a> * @see com.ibm.wala.dalvik.util.AndroidEntryPointLocator * @author Tobias Blaschke &lt;code@tobiasblaschke.de&gt; */ public final class FragmentEP { // // Start-up sequence: // /** * called once the fragment is associated with its activity. * * <p>Called before onCreate */ public static final AndroidPossibleEntryPoint onAttach = new AndroidPossibleEntryPoint( "onAttach", ExecutionOrder.between( new AndroidEntryPoint.IExecutionOrder[] { ExecutionOrder.AT_FIRST, ApplicationEP.onCreate, ProviderEP.onCreate // ActivityEP.onCreate // I's same time... }, new AndroidEntryPoint.IExecutionOrder[] { ExecutionOrder.START_OF_LOOP, // ServiceEP.onCreate // Shall we put that there? })); /** * called to do initial creation of the fragment. * * <p>Called before before onCreateView. Note that this can be called while the fragment's * activity is still in the process of being created. once the activity itself is created: * onActivityCreated(Bundle). */ public static final AndroidPossibleEntryPoint onCreate = new AndroidPossibleEntryPoint( "onCreate", ExecutionOrder.between( new AndroidEntryPoint.IExecutionOrder[] { ExecutionOrder.AT_FIRST, onAttach, // ActivityEP.onCreate // I's same time... }, new AndroidEntryPoint.IExecutionOrder[] { ExecutionOrder.START_OF_LOOP, })); /** * creates and returns the view hierarchy associated with the fragment. * * <p>This will be called between onCreate(Bundle) and onActivityCreated(Bundle). XXX: * CONTRADICTING DOCUMENTATION! his is optional, and non-graphical fragments can return null. */ public static final AndroidPossibleEntryPoint onCreateView = new AndroidPossibleEntryPoint( "onCreateView", ExecutionOrder.between( new AndroidEntryPoint.IExecutionOrder[] { ExecutionOrder.AT_FIRST, onCreate, // ActivityEP.onCreate // May still be same time... }, new AndroidEntryPoint.IExecutionOrder[] { ExecutionOrder.START_OF_LOOP, })); /** * tells the fragment that its activity has completed its own Activity.onCreate(). * * <p>Called when the fragment's activity has been created and this fragment's view hierarchy * instantiated. This is called after onCreateView XXX: CONTRADICTING DOCUMENTATION! and before * onViewStateRestored(Bundle). */ public static final AndroidPossibleEntryPoint onActivityCreated = new AndroidPossibleEntryPoint( "onActivityCreated", ExecutionOrder.between( new AndroidEntryPoint.IExecutionOrder[] { ExecutionOrder.AT_FIRST, onCreate, onCreateView // XXX: Now which one is correct? }, new AndroidEntryPoint.IExecutionOrder[] { ExecutionOrder.START_OF_LOOP, // onCreateView // XXX: Now which one is correct? })); /** * tells the fragment that all of the saved state of its view hierarchy has been restored. * * <p>Called when all saved state has been restored into the view hierarchy of the fragment. This * is called after onActivityCreated(Bundle) and before onStart(). */ public static final AndroidPossibleEntryPoint onViewStateRestored = new AndroidPossibleEntryPoint( "onViewStateRestored", ExecutionOrder.between( new AndroidEntryPoint.IExecutionOrder[] { ExecutionOrder.AT_FIRST, // TODO: Already Part of loop? onCreateView, onActivityCreated }, new AndroidEntryPoint.IExecutionOrder[] { ExecutionOrder.START_OF_LOOP, // TODO: Start of the Activity at this point? })); /** * makes the fragment visible to the user (based on its containing activity being started). * * <p>Called when the Fragment is visible to the user. This is generally tied to Activity.onStart * of the containing Activity's lifecycle. */ public static final AndroidPossibleEntryPoint onStart = new AndroidPossibleEntryPoint( "onStart", ExecutionOrder.between( new AndroidEntryPoint.IExecutionOrder[] { ExecutionOrder.START_OF_LOOP, ActivityEP.onStart, // TODO: Verify onViewStateRestored }, new AndroidEntryPoint.IExecutionOrder[] {ExecutionOrder.MIDDLE_OF_LOOP})); /** * makes the fragment interacting with the user (based on its containing activity being resumed). * * <p>Called when the fragment is visible to the user and actively running. This is generally tied * to Activity.onResume of the containing Activity's lifecycle. */ public static final AndroidPossibleEntryPoint onResume = new AndroidPossibleEntryPoint( "onResume", ExecutionOrder.between( new AndroidEntryPoint.IExecutionOrder[] { ExecutionOrder.START_OF_LOOP, onStart, ActivityEP.onPostCreate, ActivityEP.onRestoreInstanceState, ActivityEP.onResume // TODO: Rather after or before? }, new AndroidEntryPoint.IExecutionOrder[] {ExecutionOrder.MIDDLE_OF_LOOP})); // // Stop sequence // /** * fragment is no longer interacting with the user either because its activity is being paused or * a fragment operation is modifying it in the activity. * * <p>Called when the Fragment is no longer resumed. This is generally tied to Activity.onPause of * the containing Activity's lifecycle. */ public static final AndroidPossibleEntryPoint onPause = new AndroidPossibleEntryPoint( "onPause", ExecutionOrder.between( new AndroidEntryPoint.IExecutionOrder[] { ExecutionOrder.END_OF_LOOP, ActivityEP.onPause // TODO: Rather after or before? }, new AndroidEntryPoint.IExecutionOrder[] {ExecutionOrder.AFTER_LOOP})); /** * fragment is no longer visible to the user either because its activity is being stopped or a * fragment operation is modifying it in the activity. * * <p>Called when the Fragment is no longer started. This is generally tied to Activity.onStop of * the containing Activity's lifecycle. */ public static final AndroidPossibleEntryPoint onStop = new AndroidPossibleEntryPoint( "onStop", ExecutionOrder.after( new AndroidEntryPoint.IExecutionOrder[] { onPause, ActivityEP.onStop // TODO: Rather after or before? })); /** * allows the fragment to clean up resources associated with its View. * * <p>Called when the view previously created by onCreateView(LayoutInflater, ViewGroup, Bundle) * has been detached from the fragment. This is called after onStop() and before onDestroy(). It * is called regardless of whether onCreateView returned a non-null view. * * <p>Internally it is called after the view's state has been saved but before it has been removed * from its parent. */ public static final AndroidPossibleEntryPoint onDestroyView = new AndroidPossibleEntryPoint( "onDestroyView", ExecutionOrder.after( new AndroidEntryPoint.IExecutionOrder[] { onStop, ActivityEP.onStop // TODO: Rather after or before? })); /** * called to do final cleanup of the fragment's state. * * <p>Called when the fragment is no longer in use. This is called after onStop() and before * onDetach(). */ public static final AndroidPossibleEntryPoint onDestroy = new AndroidPossibleEntryPoint( "onDestroy", ExecutionOrder.after( new AndroidEntryPoint.IExecutionOrder[] { onDestroyView, ActivityEP.onStop // TODO: Rather after or before? })); /** * called immediately prior to the fragment no longer being associated with its activity. * * <p>Called when the fragment is no longer attached to its activity. This is called after * onDestroy(). */ public static final AndroidPossibleEntryPoint onDetach = new AndroidPossibleEntryPoint( "onDetach", ExecutionOrder.between( new AndroidEntryPoint.IExecutionOrder[] {ExecutionOrder.AT_LAST, onDestroy}, new AndroidEntryPoint.IExecutionOrder[] {ActivityEP.onDestroy})); // // Misc // /** @see ActivityEP#onActivityResult */ public static final AndroidPossibleEntryPoint onActivityResult = new AndroidPossibleEntryPoint( "onActivityResult", ExecutionOrder.after( new AndroidEntryPoint.IExecutionOrder[] { ExecutionOrder.MULTIPLE_TIMES_IN_LOOP, // If this Activity starts an notherone it most certainly goes into background so // place this after onPause onPause, ActivityEP.onPause, // ActivityEP.onActivityResult // TODO: Resolve if to put here... })); /** Unlike activities, other components are never restarted. */ public static final AndroidPossibleEntryPoint onConfigurationChanged = new AndroidPossibleEntryPoint( "onConfigurationChanged", ExecutionOrder.directlyAfter(ActivityEP.onConfigurationChanged) // TODO: Verify ); /** This hook is called whenever an item in a context menu is selected. */ public static final AndroidPossibleEntryPoint onContextItemSelected = new AndroidPossibleEntryPoint( "onContextItemSelected", ExecutionOrder.directlyAfter(ActivityEP.onContextItemSelected) // TODO: Verify ); /** Called when a fragment loads an animation. */ public static final AndroidPossibleEntryPoint onCreateAnimator = new AndroidPossibleEntryPoint( "onCreateAnimator", ExecutionOrder.directlyAfter(onResume) // TODO: Here? ); /** * Called when a context menu for the view is about to be shown. * * <p>Unlike onCreateOptionsMenu, this will be called every time the context menu is about to be * shown */ public static final AndroidPossibleEntryPoint onCreateContextMenu = new AndroidPossibleEntryPoint( "onCreateContextMenu", ExecutionOrder.directlyAfter(ActivityEP.onCreateContextMenu)); /** Initialize the contents of the Activity's standard options menu. */ public static final AndroidPossibleEntryPoint onCreateOptionsMenu = new AndroidPossibleEntryPoint( "onCreateOptionsMenu", ExecutionOrder.directlyAfter(ActivityEP.onCreateOptionsMenu)); /** * Called when this fragment's option menu items are no longer being included in the overall * options menu. Receiving this call means that the menu needed to be rebuilt, but this fragment's * items were not included in the newly built menu (its onCreateOptionsMenu was not called). */ public static final AndroidPossibleEntryPoint onDestroyOptionsMenu = new AndroidPossibleEntryPoint( "onDestroyOptionsMenu", ExecutionOrder.after( new AndroidEntryPoint.IExecutionOrder[] { ExecutionOrder.END_OF_LOOP, // TODO: Here? })); /** * Called when the hidden state has changed. * * <p>Fragments start out not hidden. */ public static final AndroidPossibleEntryPoint onHiddenChanged = new AndroidPossibleEntryPoint( "onHiddenChanged", ExecutionOrder.after( new AndroidEntryPoint.IExecutionOrder[] { ExecutionOrder.MIDDLE_OF_LOOP, // TODO: Here? })); /** * Called when a fragment is being created as part of a view layout inflation, typically from * setting the content view of an activity. * * <p>This may be called immediately after the fragment is created from a tag in a layout file. * Note this is before the fragment's onAttach(Activity) has been called... */ public static final AndroidPossibleEntryPoint onInflate = new AndroidPossibleEntryPoint( "onInflate", ExecutionOrder.between( new AndroidEntryPoint.IExecutionOrder[] { ExecutionOrder.AT_FIRST, ApplicationEP.onCreate, // TODO: Here? ActivityEP.onCreate }, new AndroidEntryPoint.IExecutionOrder[] {onAttach})); /** * @see ActivityEP#onLowMemory * @see ApplicationEP#onLowMemory */ public static final AndroidPossibleEntryPoint onLowMemory = new AndroidPossibleEntryPoint( "onLowMemory", ExecutionOrder.directlyBefore(ActivityEP.onLowMemory)); /** @see ActivityEP#onOptionsItemSelected */ public static final AndroidPossibleEntryPoint onOptionsItemSelected = new AndroidPossibleEntryPoint( "onOptionsItemSelected", ExecutionOrder.directlyAfter(ActivityEP.onOptionsItemSelected) // TODO: After? Before? ); /** @see ActivityEP#onOptionsMenuClosed */ public static final AndroidPossibleEntryPoint onOptionsMenuClosed = new AndroidPossibleEntryPoint( "onOptionsMenuClosed", ExecutionOrder.directlyAfter(ActivityEP.onOptionsMenuClosed) // TODO: After? Before? ); /** * This is called right before the menu is shown, every time it is shown. * * @see ActivityEP#onPrepareOptionsMenu */ public static final AndroidPossibleEntryPoint onPrepareOptionsMenu = new AndroidPossibleEntryPoint( "onPrepareOptionsMenu", ExecutionOrder.between( new AndroidEntryPoint.IExecutionOrder[] { ExecutionOrder.START_OF_LOOP, onCreateOptionsMenu, onResume }, new AndroidEntryPoint.IExecutionOrder[] { onOptionsItemSelected, onOptionsMenuClosed, ExecutionOrder.AFTER_LOOP })); /** * Called to ask the fragment to save its current dynamic state. * * <p>Bundle here will be available in the Bundle given to onCreate(Bundle), * onCreateView(LayoutInflater, ViewGroup, Bundle), and onActivityCreated(Bundle). * * <p>This method may be called at any time before onDestroy(). There are many situations where a * fragment may be mostly torn down, but its state will not be saved until its owning activity * actually needs to save its state. */ public static final AndroidPossibleEntryPoint onSaveInstanceState = new AndroidPossibleEntryPoint( "onSaveInstanceState", ExecutionOrder.between( new AndroidEntryPoint.IExecutionOrder[] { onStop, onDestroyView // See comment there }, new AndroidEntryPoint.IExecutionOrder[] { onDestroy, ExecutionOrder.AT_LAST // XXX: To early })); /** @see ActivityEP#onTrimMemory */ public static final AndroidPossibleEntryPoint onTrimMemory = new AndroidPossibleEntryPoint( "onTrimMemory", ExecutionOrder.directlyBefore(ActivityEP.onTrimMemory)); /** * Called immediately after onCreateView has returned, but before any saved state has been * restored in to the view. */ public static final AndroidPossibleEntryPoint onViewCreated = new AndroidPossibleEntryPoint( "onViewCreated", ExecutionOrder.between( onCreateView, new AndroidEntryPoint.IExecutionOrder[] {onActivityCreated, onViewStateRestored})); /** * Add the EntryPoint specifications defined in this file to the given list. * * @param possibleEntryPoints the list to extend. */ public static void populate(List<? super AndroidPossibleEntryPoint> possibleEntryPoints) { possibleEntryPoints.add(onAttach); possibleEntryPoints.add(onCreate); possibleEntryPoints.add(onCreateView); possibleEntryPoints.add(onActivityCreated); possibleEntryPoints.add(onViewStateRestored); possibleEntryPoints.add(onStart); possibleEntryPoints.add(onResume); possibleEntryPoints.add(onPause); possibleEntryPoints.add(onStop); possibleEntryPoints.add(onDestroyView); possibleEntryPoints.add(onDestroy); possibleEntryPoints.add(onDetach); possibleEntryPoints.add(onActivityResult); possibleEntryPoints.add(onConfigurationChanged); possibleEntryPoints.add(onContextItemSelected); possibleEntryPoints.add(onCreateAnimator); possibleEntryPoints.add(onCreateContextMenu); possibleEntryPoints.add(onCreateOptionsMenu); possibleEntryPoints.add(onDestroyOptionsMenu); possibleEntryPoints.add(onHiddenChanged); possibleEntryPoints.add(onInflate); possibleEntryPoints.add(onLowMemory); possibleEntryPoints.add(onOptionsItemSelected); possibleEntryPoints.add(onOptionsMenuClosed); possibleEntryPoints.add(onPrepareOptionsMenu); possibleEntryPoints.add(onSaveInstanceState); possibleEntryPoints.add(onTrimMemory); possibleEntryPoints.add(onViewCreated); } }
19,843
40.341667
100
java
WALA
WALA-master/dalvik/src/main/java/com/ibm/wala/dalvik/util/androidEntryPoints/LoaderCB.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 under the terms listed below. * */ /* * Copyright (c) 2013, * Tobias Blaschke <code@tobiasblaschke.de> * All rights reserved. * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The names of the contributors may not be used to endorse or promote * products derived from this software without specific prior written * permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ package com.ibm.wala.dalvik.util.androidEntryPoints; import com.ibm.wala.dalvik.ipa.callgraph.impl.AndroidEntryPoint.ExecutionOrder; import com.ibm.wala.dalvik.util.AndroidEntryPointLocator.AndroidPossibleEntryPoint; import java.util.List; /** * Hardcoded specifications of androids loader call-backs. * * <p>The specifications are read and handled by AndroidEntryPointLocator if the flags of * AndroidEntryPointLocator are set to include call-backs. * * @see com.ibm.wala.dalvik.util.AndroidEntryPointLocator * @author Tobias Blaschke &lt;code@tobiasblaschke.de&gt; */ public final class LoaderCB { /** Instantiate and return a new Loader for the given ID. */ public static final AndroidPossibleEntryPoint onCreateLoader = new AndroidPossibleEntryPoint( "onCreateLoader", ExecutionOrder.AT_FIRST); // TODO: Baaad position /** Called when a previously created loader has finished its load. */ public static final AndroidPossibleEntryPoint onLoadFinished = new AndroidPossibleEntryPoint( "onLoadFinished", ExecutionOrder.after(onCreateLoader)); // TODO: Baaad position /** * Called when a previously created loader is being reset, and thus making its data unavailable. */ public static final AndroidPossibleEntryPoint onLoaderReset = new AndroidPossibleEntryPoint( "onLoaderReset", ExecutionOrder.after(onCreateLoader)); // TODO: Baaad position /** * Add the EntryPoint specifications defined in this file to the given list. * * @param possibleEntryPoints the list to extend. */ public static void populate(List<? super AndroidPossibleEntryPoint> possibleEntryPoints) { possibleEntryPoints.add(onCreateLoader); possibleEntryPoints.add(onLoadFinished); possibleEntryPoints.add(onLoaderReset); } }
3,690
41.918605
98
java
WALA
WALA-master/dalvik/src/main/java/com/ibm/wala/dalvik/util/androidEntryPoints/LocationEP.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 under the terms listed below. * */ /* * Copyright (c) 2013, * Tobias Blaschke <code@tobiasblaschke.de> * All rights reserved. * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The names of the contributors may not be used to endorse or promote * products derived from this software without specific prior written * permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ package com.ibm.wala.dalvik.util.androidEntryPoints; import com.ibm.wala.dalvik.ipa.callgraph.impl.AndroidEntryPoint.ExecutionOrder; import com.ibm.wala.dalvik.util.AndroidEntryPointLocator.AndroidPossibleEntryPoint; import java.util.List; /** * Hardcoded specifications of androids location handling call-backs. * * <p>The specifications are read and handled by AndroidEntryPointLocator if the flags of * AndroidEntryPointLocator are set to include call-backs. * * @see com.ibm.wala.dalvik.util.AndroidEntryPointLocator * @author Tobias Blaschke &lt;code@tobiasblaschke.de&gt; */ public final class LocationEP { public static final AndroidPossibleEntryPoint onLocationChanged = new AndroidPossibleEntryPoint("onLocationChanged", ExecutionOrder.MIDDLE_OF_LOOP); public static final AndroidPossibleEntryPoint onProviderDisabled = new AndroidPossibleEntryPoint("onProviderDisabled", ExecutionOrder.MIDDLE_OF_LOOP); public static final AndroidPossibleEntryPoint onProviderEnabled = new AndroidPossibleEntryPoint("onProviderEnabled", ExecutionOrder.MIDDLE_OF_LOOP); public static final AndroidPossibleEntryPoint onStatusChanged = new AndroidPossibleEntryPoint("onStatusChanged", ExecutionOrder.MIDDLE_OF_LOOP); public static final AndroidPossibleEntryPoint onGpsStatusChanged = new AndroidPossibleEntryPoint("onGpsStatusChanged", ExecutionOrder.MIDDLE_OF_LOOP); public static final AndroidPossibleEntryPoint onNmeaReceived = new AndroidPossibleEntryPoint("onNmeaReceived", ExecutionOrder.MIDDLE_OF_LOOP); /** * Add the EntryPoint specifications defined in this file to the given list. * * @param possibleEntryPoints the list to extend. */ public static void populate(List<? super AndroidPossibleEntryPoint> possibleEntryPoints) { possibleEntryPoints.add(onLocationChanged); possibleEntryPoints.add(onProviderDisabled); possibleEntryPoints.add(onProviderEnabled); possibleEntryPoints.add(onStatusChanged); possibleEntryPoints.add(onGpsStatusChanged); possibleEntryPoints.add(onNmeaReceived); } }
3,982
43.752809
92
java
WALA
WALA-master/dalvik/src/main/java/com/ibm/wala/dalvik/util/androidEntryPoints/ProviderEP.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 under the terms listed below. * */ /* * Copyright (c) 2013, * Tobias Blaschke <code@tobiasblaschke.de> * All rights reserved. * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The names of the contributors may not be used to endorse or promote * products derived from this software without specific prior written * permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ package com.ibm.wala.dalvik.util.androidEntryPoints; import com.ibm.wala.dalvik.ipa.callgraph.impl.AndroidEntryPoint; import com.ibm.wala.dalvik.ipa.callgraph.impl.AndroidEntryPoint.ExecutionOrder; import com.ibm.wala.dalvik.util.AndroidEntryPointLocator.AndroidPossibleEntryPoint; import java.util.List; /** * Hardcoded EntryPoint-specifications for an Android-ContentProvider. * * <p>The specifications are read and handled by AndroidEntryPointLocator. * * @see com.ibm.wala.dalvik.util.AndroidEntryPointLocator * @author Tobias Blaschke &lt;code@tobiasblaschke.de&gt; */ public final class ProviderEP { public static final AndroidPossibleEntryPoint onCreate = new AndroidPossibleEntryPoint("onCreate", ExecutionOrder.AT_FIRST); public static final AndroidPossibleEntryPoint query = new AndroidPossibleEntryPoint( "query", ExecutionOrder.after( new AndroidEntryPoint.IExecutionOrder[] { onCreate, // ActivityEP.onResume, ExecutionOrder.START_OF_LOOP })); public static final AndroidPossibleEntryPoint insert = new AndroidPossibleEntryPoint( "insert", ExecutionOrder.after( new AndroidEntryPoint.IExecutionOrder[] { onCreate, // ActivityEP.onResume, ExecutionOrder.START_OF_LOOP })); public static final AndroidPossibleEntryPoint onConfigurationChanged = new AndroidPossibleEntryPoint( "onConfigurationChanged", ExecutionOrder.after( new AndroidEntryPoint.IExecutionOrder[] { onCreate, // ActivityEP.onResume, ExecutionOrder.START_OF_LOOP })); public static final AndroidPossibleEntryPoint onLowMemory = new AndroidPossibleEntryPoint( "onLowMemory", ExecutionOrder.after( new AndroidEntryPoint.IExecutionOrder[] { onCreate, // ActivityEP.onResume, ExecutionOrder.START_OF_LOOP })); public static final AndroidPossibleEntryPoint onTrimMemory = new AndroidPossibleEntryPoint( "onTrimMemory", ExecutionOrder.after( new AndroidEntryPoint.IExecutionOrder[] { onCreate, // ActivityEP.onResume, ExecutionOrder.START_OF_LOOP })); public static final AndroidPossibleEntryPoint update = new AndroidPossibleEntryPoint( "update", ExecutionOrder.after( new AndroidEntryPoint.IExecutionOrder[] { onCreate, // ActivityEP.onResume, ExecutionOrder.START_OF_LOOP })); /** * Add the EntryPoint specifications defined in this file to the given list. * * @param possibleEntryPoints the list to extend. */ public static void populate(List<? super AndroidPossibleEntryPoint> possibleEntryPoints) { possibleEntryPoints.add(onCreate); possibleEntryPoints.add(query); possibleEntryPoints.add(insert); possibleEntryPoints.add(update); possibleEntryPoints.add(onConfigurationChanged); possibleEntryPoints.add(onLowMemory); possibleEntryPoints.add(onTrimMemory); } }
5,217
37.940299
92
java
WALA
WALA-master/dalvik/src/main/java/com/ibm/wala/dalvik/util/androidEntryPoints/ServiceEP.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 under the terms listed below. * */ /* * Copyright (c) 2013, * Tobias Blaschke <code@tobiasblaschke.de> * All rights reserved. * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The names of the contributors may not be used to endorse or promote * products derived from this software without specific prior written * permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ package com.ibm.wala.dalvik.util.androidEntryPoints; import com.ibm.wala.dalvik.ipa.callgraph.impl.AndroidEntryPoint; import com.ibm.wala.dalvik.ipa.callgraph.impl.AndroidEntryPoint.ExecutionOrder; import com.ibm.wala.dalvik.util.AndroidEntryPointLocator.AndroidPossibleEntryPoint; import java.util.List; /** * Hardcoded EntryPoint-specifications for an Android-Service. * * <p>The specifications are read and handled by AndroidEntryPointLocator. * * @see com.ibm.wala.dalvik.util.AndroidEntryPointLocator * @author Tobias Blaschke &lt;code@tobiasblaschke.de&gt; */ public final class ServiceEP { /** Called by the system when the service is first created. */ public static final AndroidPossibleEntryPoint onCreate = new AndroidPossibleEntryPoint( "onCreate", ExecutionOrder.after( new AndroidEntryPoint.IExecutionOrder[] { ExecutionOrder.AT_FIRST, ProviderEP.onCreate, // ApplicationEP.onCreate, // Uncommenting would create a ring-dependency })); /** * Called by the system every time a client explicitly starts the service by calling * startService(Intent). For backwards compatibility, the default implementation calls onStart. * * <p>startService-Services are not informed when they are stopped. */ public static final AndroidPossibleEntryPoint onStartCommand = new AndroidPossibleEntryPoint( "onStartCommand", ExecutionOrder.after( new AndroidEntryPoint.IExecutionOrder[] {ExecutionOrder.AT_FIRST, onCreate})); /** Only for backwards compatibility. */ public static final AndroidPossibleEntryPoint onStart = new AndroidPossibleEntryPoint( "onStart", ExecutionOrder.after( new AndroidEntryPoint.IExecutionOrder[] { ExecutionOrder.AT_FIRST, onCreate, onStartCommand // onStartCommand usually calls onStart })); /** * Return the communication channel to the service. May return null if clients can not bind to the * service. * * <p>Services started this way can be notified before they get stopped via onUnbind */ public static final AndroidPossibleEntryPoint onBind = new AndroidPossibleEntryPoint( "onBind", ExecutionOrder.after( new AndroidEntryPoint.IExecutionOrder[] {onCreate, ExecutionOrder.BEFORE_LOOP})); /** * Called when all clients have disconnected from a particular interface published by the service. * Return true if you would like to have the service's onRebind(Intent) method later called when * new clients bind to it. */ public static final AndroidPossibleEntryPoint onUnbind = new AndroidPossibleEntryPoint( "onUnbind", ExecutionOrder.after( new AndroidEntryPoint.IExecutionOrder[] {onBind, ExecutionOrder.END_OF_LOOP})); /** * Called when new clients have connected to the service, after it had previously been notified * that all had disconnected in its onUnbind(Intent). This will only be called if the * implementation of onUnbind(Intent) was overridden to return true. */ public static final AndroidPossibleEntryPoint onRebind = new AndroidPossibleEntryPoint( "onRebind", ExecutionOrder.after(new AndroidEntryPoint.IExecutionOrder[] {onBind, onUnbind})); /** * Called by the system to notify a Service that it is no longer used and is being removed. Upon * return, there will be no more calls in to this Service object and it is effectively dead. */ public static final AndroidPossibleEntryPoint onDestroy = new AndroidPossibleEntryPoint( "onDestroy", ExecutionOrder.after( new AndroidEntryPoint.IExecutionOrder[] { onUnbind, onStart, onBind, onStartCommand, ExecutionOrder.AT_LAST })); /** * This is called if the service is currently running and the user has removed a task that comes * from the service's application. If you have set ServiceInfo.FLAG_STOP_WITH_TASK then you will * not receive this callback; instead, the service will simply be stopped. */ public static final AndroidPossibleEntryPoint onTaskRemoved = new AndroidPossibleEntryPoint( "onTaskRemoved", ExecutionOrder.between( new AndroidEntryPoint.IExecutionOrder[] { onUnbind, onStart, onBind, onStartCommand, ExecutionOrder.AT_LAST }, new AndroidEntryPoint.IExecutionOrder[] {onDestroy})); /** Called by the system when the device configuration changes while your component is running. */ public static final AndroidPossibleEntryPoint onConfigurationChanged = new AndroidPossibleEntryPoint( "onConfigurationChanged", ExecutionOrder.between( new AndroidEntryPoint.IExecutionOrder[] { // TODO: Position onCreate }, new AndroidEntryPoint.IExecutionOrder[] {ExecutionOrder.AFTER_LOOP})); /** * This is called when the overall system is running low on memory, and actively running processes * should trim their memory usage. */ public static final AndroidPossibleEntryPoint onLowMemory = new AndroidPossibleEntryPoint( "onLowMemory", ExecutionOrder.between( // TODO: find a nice position new AndroidEntryPoint.IExecutionOrder[] { ExecutionOrder.END_OF_LOOP, }, new AndroidEntryPoint.IExecutionOrder[] { ExecutionOrder.AFTER_LOOP, // onConfigurationChanged // XXX ??!! })); /** * Called when the operating system has determined that it is a good time for a process to trim * unneeded memory from its process. */ public static final AndroidPossibleEntryPoint onTrimMemory = new AndroidPossibleEntryPoint( "onTrimMemory", ExecutionOrder.between( // TODO: find a nice position new AndroidEntryPoint.IExecutionOrder[] {ExecutionOrder.END_OF_LOOP}, new AndroidEntryPoint.IExecutionOrder[] { ExecutionOrder.AFTER_LOOP, // onConfigurationChanged // XXX ??!! })); public static final AndroidPossibleEntryPoint onHandleIntent = new AndroidPossibleEntryPoint( "onHandleIntent", ExecutionOrder.between( new AndroidEntryPoint.IExecutionOrder[] {onCreate}, new AndroidEntryPoint.IExecutionOrder[] {onStart})); public static final AndroidPossibleEntryPoint onCreateInputMethodInterface = new AndroidPossibleEntryPoint( "onCreateInputMethodInterface", ExecutionOrder.directlyAfter(onCreate)); public static final AndroidPossibleEntryPoint onCreateInputMethodSessionInterface = new AndroidPossibleEntryPoint( "onCreateInputMethodSessionInterface", ExecutionOrder.after(onCreateInputMethodInterface)); // TODO: Place public static final AndroidPossibleEntryPoint onGenericMotionEvent = new AndroidPossibleEntryPoint( "onGenericMotionEvent", ExecutionOrder.directlyAfter(ActivityEP.onGenericMotionEvent)); public static final AndroidPossibleEntryPoint onTrackballEvent = new AndroidPossibleEntryPoint("onTrackballEvent", ActivityEP.onTrackballEvent); public static final AndroidPossibleEntryPoint onAccessibilityEvent = new AndroidPossibleEntryPoint( "onAccessibilityEvent", ExecutionOrder.after(onTrackballEvent)); // TODO: Place public static final AndroidPossibleEntryPoint onInterrupt = new AndroidPossibleEntryPoint("onInterrupt", ExecutionOrder.after(onAccessibilityEvent)); public static final AndroidPossibleEntryPoint onActionModeFinished = new AndroidPossibleEntryPoint("onActionModeFinished", ActivityEP.onActionModeFinished); public static final AndroidPossibleEntryPoint onActionModeStarted = new AndroidPossibleEntryPoint("onActionModeStarted", ActivityEP.onActionModeStarted); public static final AndroidPossibleEntryPoint onAttachedToWindow = new AndroidPossibleEntryPoint("onAttachedToWindow", ActivityEP.onAttachedToWindow); public static final AndroidPossibleEntryPoint onContentChanged = new AndroidPossibleEntryPoint("onContentChanged", ActivityEP.onContentChanged); public static final AndroidPossibleEntryPoint onCreatePanelMenu = new AndroidPossibleEntryPoint("onCreatePanelMenu", ActivityEP.onCreatePanelMenu); public static final AndroidPossibleEntryPoint onCreatePanelView = new AndroidPossibleEntryPoint("onCreatePanelView", ActivityEP.onCreatePanelView); public static final AndroidPossibleEntryPoint onDetachedFromWindow = new AndroidPossibleEntryPoint("onDetachedFromWindow", ActivityEP.onDetachedFromWindow); public static final AndroidPossibleEntryPoint onDreamingStarted = new AndroidPossibleEntryPoint( "onDreamingStarted", ExecutionOrder.after(onStart)); // TODO: Place public static final AndroidPossibleEntryPoint onDreamingStopped = new AndroidPossibleEntryPoint( "onDreamingStopped", ExecutionOrder.between( new AndroidEntryPoint.IExecutionOrder[] { // TODO: Place onDreamingStarted, onBind, onStartCommand, }, new AndroidEntryPoint.IExecutionOrder[] {onDestroy, onUnbind})); public static final AndroidPossibleEntryPoint onMenuItemSelected = new AndroidPossibleEntryPoint("onMenuItemSelected", ActivityEP.onMenuItemSelected); public static final AndroidPossibleEntryPoint onMenuOpened = new AndroidPossibleEntryPoint("onMenuOpened", ActivityEP.onMenuOpened); public static final AndroidPossibleEntryPoint onPanelClosed = new AndroidPossibleEntryPoint("onPanelClosed", ActivityEP.onPanelClosed); public static final AndroidPossibleEntryPoint onPreparePanel = new AndroidPossibleEntryPoint("onPreparePanel", ActivityEP.onPreparePanel); public static final AndroidPossibleEntryPoint onSearchRequested = new AndroidPossibleEntryPoint("onSearchRequested", ActivityEP.onSearchRequested); public static final AndroidPossibleEntryPoint onWindowAttributesChanged = new AndroidPossibleEntryPoint( "onWindowAttributesChanged", ActivityEP.onWindowAttributesChanged); public static final AndroidPossibleEntryPoint onWindowFocusChanged = new AndroidPossibleEntryPoint("onWindowFocusChanged", ActivityEP.onWindowFocusChanged); public static final AndroidPossibleEntryPoint onWindowStartingActionMode = new AndroidPossibleEntryPoint( "onWindowStartingActionMode", ActivityEP.onWindowStartingActionMode); public static final AndroidPossibleEntryPoint onDeactivated = new AndroidPossibleEntryPoint( "onDeactivated", ExecutionOrder.directlyBefore(ActivityEP.onPause)); public static final AndroidPossibleEntryPoint onCreateMediaRouteProvider = new AndroidPossibleEntryPoint("onCreateMediaRouteProvider", onCreate); public static final AndroidPossibleEntryPoint onNotificationPosted = new AndroidPossibleEntryPoint("onNotificationPosted", ExecutionOrder.MULTIPLE_TIMES_IN_LOOP); public static final AndroidPossibleEntryPoint onNotificationRemoved = new AndroidPossibleEntryPoint( "onNotificationRemoved", ExecutionOrder.after(onNotificationPosted)); public static final AndroidPossibleEntryPoint onConnected = new AndroidPossibleEntryPoint("onConnected", ExecutionOrder.after(onStart)); public static final AndroidPossibleEntryPoint onCreatePrinterDiscoverySession = new AndroidPossibleEntryPoint( "onCreatePrinterDiscoverySession", ExecutionOrder.between(onStart, onConnected)); public static final AndroidPossibleEntryPoint onDisconnected = new AndroidPossibleEntryPoint( "onDisconnected", ExecutionOrder.between(onConnected, onDestroy)); // XXX: Section hop public static final AndroidPossibleEntryPoint onPrintJobQueued = new AndroidPossibleEntryPoint( "onPrintJobQueued", ExecutionOrder.between(onConnected, onDisconnected)); // XXX: Section hop public static final AndroidPossibleEntryPoint onRequestCancelPrintJob = new AndroidPossibleEntryPoint( "onRequestCancelPrintJob", ExecutionOrder.between(onPrintJobQueued, onDisconnected)); // XXX: Section hop public static final AndroidPossibleEntryPoint onCancel = new AndroidPossibleEntryPoint( "onCancel", ExecutionOrder.between( ExecutionOrder.MULTIPLE_TIMES_IN_LOOP, ExecutionOrder.END_OF_LOOP)); public static final AndroidPossibleEntryPoint onStartListening = new AndroidPossibleEntryPoint( "onStartListening", ExecutionOrder.between(ExecutionOrder.MULTIPLE_TIMES_IN_LOOP, onCancel)); public static final AndroidPossibleEntryPoint onStopListening = new AndroidPossibleEntryPoint( "onStopListening", ExecutionOrder.between(onCancel, ExecutionOrder.END_OF_LOOP)); public static final AndroidPossibleEntryPoint onGetViewFactory = new AndroidPossibleEntryPoint( "onGetViewFactory", ExecutionOrder.after(onStart)); // TODO: Position public static final AndroidPossibleEntryPoint onGetEnabled = new AndroidPossibleEntryPoint( "onGetEnabled", ExecutionOrder.after(onStart)); // TODO: Position public static final AndroidPossibleEntryPoint onGetSummary = new AndroidPossibleEntryPoint( "onGetSummary", ExecutionOrder.after(onStart)); // TODO: Position public static final AndroidPossibleEntryPoint onGetFeaturesForLanguage = new AndroidPossibleEntryPoint( "onGetFeaturesForLanguage", ExecutionOrder.after(onStart)); // TODO: Position public static final AndroidPossibleEntryPoint onGetLanguage = new AndroidPossibleEntryPoint( "onGetLanguage", ExecutionOrder.directlyBefore(onGetFeaturesForLanguage)); public static final AndroidPossibleEntryPoint onLoadLanguage = new AndroidPossibleEntryPoint("onLoadLanguage", ExecutionOrder.directlyBefore(onGetLanguage)); public static final AndroidPossibleEntryPoint onIsLanguageAvailable = new AndroidPossibleEntryPoint( "onIsLanguageAvailable", ExecutionOrder.directlyBefore(onLoadLanguage)); public static final AndroidPossibleEntryPoint onSynthesizeText = new AndroidPossibleEntryPoint( "onSynthesizeText", ExecutionOrder.after( new AndroidEntryPoint.IExecutionOrder[] { onGetLanguage, onLoadLanguage, ExecutionOrder.MULTIPLE_TIMES_IN_LOOP })); public static final AndroidPossibleEntryPoint onStop = new AndroidPossibleEntryPoint("onStop", ExecutionOrder.directlyBefore(ActivityEP.onStop)); public static final AndroidPossibleEntryPoint onRevoke = new AndroidPossibleEntryPoint( "onRevoke", ExecutionOrder.between(ExecutionOrder.END_OF_LOOP, onDestroy)); public static final AndroidPossibleEntryPoint onCreateEngine = new AndroidPossibleEntryPoint( "onCreateEngine", ExecutionOrder.between(onCreate, onStart)); // TODO: Position public static final AndroidPossibleEntryPoint onAppPrivateCommand = new AndroidPossibleEntryPoint( "onAppPrivateCommand", ExecutionOrder.MULTIPLE_TIMES_IN_LOOP); // TODO: Position /** to find out about switching to a new client. */ public static final AndroidPossibleEntryPoint onBindInput = new AndroidPossibleEntryPoint("onBindInput", ExecutionOrder.after(ActivityEP.onResume)); /** Compute the interesting insets into your UI. */ public static final AndroidPossibleEntryPoint onComputeInsets = new AndroidPossibleEntryPoint("onComputeInsets", ExecutionOrder.after(onStart)); public static final AndroidPossibleEntryPoint onConfigureWindow = new AndroidPossibleEntryPoint("onConfigureWindow", ExecutionOrder.after(onComputeInsets)); public static final AndroidPossibleEntryPoint onCreateCandidatesView = new AndroidPossibleEntryPoint( "onCreateCandidatesView", ExecutionOrder.between(onStart, onComputeInsets)); /** non-demand generation of the UI. */ public static final AndroidPossibleEntryPoint onCreateExtractTextView = new AndroidPossibleEntryPoint( "onCreateExtractTextView", ExecutionOrder.after(onCreateCandidatesView)); /** non-demand generation of the UI. */ public static final AndroidPossibleEntryPoint onCreateInputView = new AndroidPossibleEntryPoint("onCreateInputView", onCreateExtractTextView); /** non-demand generation of the UI. */ public static final AndroidPossibleEntryPoint onStartCandidatesView = new AndroidPossibleEntryPoint("onStartCandidatesView", onCreateExtractTextView); // public static final AndroidPossibleEntryPoint onCreateInputMethodInterface = new // AndroidPossibleEntryPoint( // AndroidComponent.INPUT_METHOD_SERVICE, "onCreateInputMethodInterface", // ExecutionOrder.after(onCreate)); // public static final AndroidPossibleEntryPoint onCreateInputMethodSessionInterface = new // AndroidPossibleEntryPoint( // AndroidComponent.INPUT_METHOD_SERVICE, "onCreateInputMethodSessionInterface", // ExecutionOrder.directlyAfter(onCreateInputMethodInterface)); public static final AndroidPossibleEntryPoint onDisplayCompletions = new AndroidPossibleEntryPoint("onDisplayCompletions", ExecutionOrder.MULTIPLE_TIMES_IN_LOOP); public static final AndroidPossibleEntryPoint onEvaluateFullscreenMode = new AndroidPossibleEntryPoint( "onEvaluateFullscreenMode", ExecutionOrder.MULTIPLE_TIMES_IN_LOOP); public static final AndroidPossibleEntryPoint onEvaluateInputViewShown = new AndroidPossibleEntryPoint( "onEvaluateInputViewShown", ExecutionOrder.MULTIPLE_TIMES_IN_LOOP); public static final AndroidPossibleEntryPoint onExtractTextContextMenuItem = new AndroidPossibleEntryPoint( "onExtractTextContextMenuItem", ExecutionOrder.MULTIPLE_TIMES_IN_LOOP); public static final AndroidPossibleEntryPoint onExtractedCursorMovement = new AndroidPossibleEntryPoint( "onExtractedCursorMovement", ExecutionOrder.MULTIPLE_TIMES_IN_LOOP); public static final AndroidPossibleEntryPoint onExtractedSelectionChanged = new AndroidPossibleEntryPoint( "onExtractedSelectionChanged", ExecutionOrder.directlyAfter(onExtractedCursorMovement)); public static final AndroidPossibleEntryPoint onExtractedTextClicked = new AndroidPossibleEntryPoint( "onExtractedTextClicked", ExecutionOrder.directlyAfter(onExtractedCursorMovement)); public static final AndroidPossibleEntryPoint onExtractingInputChanged = new AndroidPossibleEntryPoint( "onExtractingInputChanged", ExecutionOrder.after( new AndroidEntryPoint.IExecutionOrder[] { onExtractedTextClicked, onExtractedSelectionChanged, ExecutionOrder.MULTIPLE_TIMES_IN_LOOP })); public static final AndroidPossibleEntryPoint onFinishInput = new AndroidPossibleEntryPoint( "onFinishInput", ExecutionOrder.after( new AndroidEntryPoint.IExecutionOrder[] { onExtractingInputChanged, })); public static final AndroidPossibleEntryPoint onFinishInputView = new AndroidPossibleEntryPoint("onFinishInputView", ExecutionOrder.after(onFinishInput)); public static final AndroidPossibleEntryPoint onFinishCandidatesView = new AndroidPossibleEntryPoint( "onFinishCandidatesView", ExecutionOrder.after( new AndroidEntryPoint.IExecutionOrder[] { onExtractingInputChanged, onFinishInput, onStartCandidatesView })); // public static final AndroidPossibleEntryPoint onGenericMotionEvent = new // AndroidPossibleEntryPoint( // AndroidComponent.INPUT_METHOD_SERVICE, "onGenericMotionEvent", // ExecutionOrder.directlyBefore(ActivityEP.onGenericMotionEvent)); /** * for user-interface initialization, in particular to deal with configuration changes while the * service is running. */ public static final AndroidPossibleEntryPoint onInitializeInterface = new AndroidPossibleEntryPoint( "onInitializeInterface", ExecutionOrder.MULTIPLE_TIMES_IN_LOOP); // TODO: Position public static final AndroidPossibleEntryPoint onKeyDown = new AndroidPossibleEntryPoint( "onKeyDown", ExecutionOrder.directlyBefore(ActivityEP.onKeyDown)); public static final AndroidPossibleEntryPoint onKeyLongPress = new AndroidPossibleEntryPoint( "onKeyLongPress", ExecutionOrder.directlyBefore(ActivityEP.onKeyLongPress)); public static final AndroidPossibleEntryPoint onKeyMultiple = new AndroidPossibleEntryPoint( "onKeyMultiple", ExecutionOrder.directlyBefore(ActivityEP.onKeyMultiple)); public static final AndroidPossibleEntryPoint onKeyUp = new AndroidPossibleEntryPoint("onKeyUp", ExecutionOrder.directlyBefore(ActivityEP.onKeyUp)); public static final AndroidPossibleEntryPoint onShowInputRequested = new AndroidPossibleEntryPoint("onShowInputRequested", ExecutionOrder.MULTIPLE_TIMES_IN_LOOP); /** deal with an input session starting with the client. */ public static final AndroidPossibleEntryPoint onStartInput = new AndroidPossibleEntryPoint( "onStartInput", ExecutionOrder.after( new AndroidEntryPoint.IExecutionOrder[] { onCreateInputMethodSessionInterface, ActivityEP.onResume })); /** deal with input starting within the input area of the IME. */ public static final AndroidPossibleEntryPoint onStartInputView = new AndroidPossibleEntryPoint("onStartInputView", onStartInput); // InputMethodService.onTrackballEvent public static final AndroidPossibleEntryPoint onUnbindInput = new AndroidPossibleEntryPoint("onUnbindInput", onUnbind); // TODO: Position public static final AndroidPossibleEntryPoint onUpdateCursor = new AndroidPossibleEntryPoint( "onUpdateCursor", ExecutionOrder.directlyBefore(onGenericMotionEvent)); /** * Called when the application has reported new extracted text to be shown due to changes in its * current text state. */ public static final AndroidPossibleEntryPoint onUpdateExtractedText = new AndroidPossibleEntryPoint( "onUpdateExtractedText", ExecutionOrder.directlyAfter(onExtractedTextClicked)); public static final AndroidPossibleEntryPoint onUpdateExtractingViews = new AndroidPossibleEntryPoint( "onUpdateExtractingViews", ExecutionOrder.after(onExtractingInputChanged)); public static final AndroidPossibleEntryPoint onUpdateExtractingVisibility = new AndroidPossibleEntryPoint( "onUpdateExtractingVisibility", ExecutionOrder.after(onUpdateExtractingViews)); public static final AndroidPossibleEntryPoint onUpdateSelection = new AndroidPossibleEntryPoint( "onUpdateSelection", ExecutionOrder.after(onExtractedSelectionChanged)); public static final AndroidPossibleEntryPoint onViewClicked = new AndroidPossibleEntryPoint( "onViewClicked", ExecutionOrder.after( new AndroidEntryPoint.IExecutionOrder[] { onGenericMotionEvent, onTrackballEvent, onKeyUp })); public static final AndroidPossibleEntryPoint onWindowShown = new AndroidPossibleEntryPoint( "onWindowShown", ExecutionOrder.after( new AndroidEntryPoint.IExecutionOrder[] {onConfigureWindow, onCreateCandidatesView})); public static final AndroidPossibleEntryPoint onWindowHidden = new AndroidPossibleEntryPoint( "onWindowHidden", ExecutionOrder.between( new AndroidEntryPoint.IExecutionOrder[] { onWindowShown, }, new AndroidEntryPoint.IExecutionOrder[] {onDestroy, ActivityEP.onPause})); /** * After return of this method the BroadcastReceiver is assumed to have stopped. * * <p>As a BroadcastReceiver is oftain used in conjunction with a service it's defined here... */ public static final AndroidPossibleEntryPoint onReceive = new AndroidPossibleEntryPoint( "onReceive", ExecutionOrder.after( new AndroidEntryPoint.IExecutionOrder[] { ExecutionOrder.AT_FIRST, ProviderEP.onCreate, // ApplicationEP.onCreate })); // , // new AndroidEntryPoint.IExecutionOrder[] { // // BroadcastReceivers oftain use a Service - so place it before them. // ServiceEP.onCreate // } // )); /** * Add the EntryPoint specifications defined in this file to the given list. * * @param possibleEntryPoints the list to extend. */ public static void populate(List<? super AndroidPossibleEntryPoint> possibleEntryPoints) { possibleEntryPoints.add(onCreate); possibleEntryPoints.add(onStart); possibleEntryPoints.add(onStartCommand); possibleEntryPoints.add(onBind); possibleEntryPoints.add(onUnbind); possibleEntryPoints.add(onRebind); possibleEntryPoints.add(onTaskRemoved); possibleEntryPoints.add(onConfigurationChanged); possibleEntryPoints.add(onLowMemory); possibleEntryPoints.add(onTrimMemory); possibleEntryPoints.add(onDestroy); possibleEntryPoints.add(onHandleIntent); possibleEntryPoints.add(onCreateInputMethodInterface); possibleEntryPoints.add(onCreateInputMethodSessionInterface); possibleEntryPoints.add(onGenericMotionEvent); possibleEntryPoints.add(onTrackballEvent); possibleEntryPoints.add(onAccessibilityEvent); possibleEntryPoints.add(onInterrupt); possibleEntryPoints.add(onActionModeFinished); possibleEntryPoints.add(onActionModeStarted); possibleEntryPoints.add(onAttachedToWindow); possibleEntryPoints.add(onContentChanged); possibleEntryPoints.add(onCreatePanelMenu); possibleEntryPoints.add(onCreatePanelView); possibleEntryPoints.add(onDetachedFromWindow); possibleEntryPoints.add(onDreamingStarted); possibleEntryPoints.add(onDreamingStopped); possibleEntryPoints.add(onMenuItemSelected); possibleEntryPoints.add(onMenuOpened); possibleEntryPoints.add(onPanelClosed); possibleEntryPoints.add(onPreparePanel); possibleEntryPoints.add(onSearchRequested); possibleEntryPoints.add(onWindowAttributesChanged); possibleEntryPoints.add(onWindowFocusChanged); possibleEntryPoints.add(onWindowStartingActionMode); possibleEntryPoints.add(onDeactivated); possibleEntryPoints.add(onCreateMediaRouteProvider); possibleEntryPoints.add(onNotificationPosted); possibleEntryPoints.add(onNotificationRemoved); possibleEntryPoints.add(onConnected); possibleEntryPoints.add(onCreatePrinterDiscoverySession); possibleEntryPoints.add(onDisconnected); possibleEntryPoints.add(onPrintJobQueued); possibleEntryPoints.add(onRequestCancelPrintJob); possibleEntryPoints.add(onCancel); possibleEntryPoints.add(onStartListening); possibleEntryPoints.add(onStopListening); possibleEntryPoints.add(onGetViewFactory); possibleEntryPoints.add(onGetEnabled); possibleEntryPoints.add(onGetSummary); possibleEntryPoints.add(onGetFeaturesForLanguage); possibleEntryPoints.add(onGetLanguage); possibleEntryPoints.add(onIsLanguageAvailable); possibleEntryPoints.add(onLoadLanguage); possibleEntryPoints.add(onStop); possibleEntryPoints.add(onSynthesizeText); possibleEntryPoints.add(onRevoke); possibleEntryPoints.add(onCreateEngine); possibleEntryPoints.add(onAppPrivateCommand); possibleEntryPoints.add(onBindInput); possibleEntryPoints.add(onComputeInsets); possibleEntryPoints.add(onConfigureWindow); possibleEntryPoints.add(onCreateCandidatesView); possibleEntryPoints.add(onCreateExtractTextView); possibleEntryPoints.add(onCreateInputMethodInterface); possibleEntryPoints.add(onCreateInputMethodSessionInterface); possibleEntryPoints.add(onCreateInputView); possibleEntryPoints.add(onDisplayCompletions); possibleEntryPoints.add(onEvaluateFullscreenMode); possibleEntryPoints.add(onEvaluateInputViewShown); possibleEntryPoints.add(onExtractTextContextMenuItem); possibleEntryPoints.add(onExtractedCursorMovement); possibleEntryPoints.add(onExtractedSelectionChanged); possibleEntryPoints.add(onExtractedTextClicked); possibleEntryPoints.add(onExtractingInputChanged); possibleEntryPoints.add(onFinishCandidatesView); possibleEntryPoints.add(onFinishInput); possibleEntryPoints.add(onFinishInputView); possibleEntryPoints.add(onGenericMotionEvent); possibleEntryPoints.add(onInitializeInterface); possibleEntryPoints.add(onKeyDown); possibleEntryPoints.add(onKeyLongPress); possibleEntryPoints.add(onKeyMultiple); possibleEntryPoints.add(onKeyUp); possibleEntryPoints.add(onShowInputRequested); possibleEntryPoints.add(onStartCandidatesView); possibleEntryPoints.add(onStartInput); possibleEntryPoints.add(onStartInputView); possibleEntryPoints.add(onTrackballEvent); possibleEntryPoints.add(onUnbindInput); possibleEntryPoints.add(onUpdateCursor); possibleEntryPoints.add(onUpdateExtractedText); possibleEntryPoints.add(onUpdateExtractingViews); possibleEntryPoints.add(onUpdateExtractingVisibility); possibleEntryPoints.add(onUpdateSelection); possibleEntryPoints.add(onViewClicked); possibleEntryPoints.add(onWindowHidden); possibleEntryPoints.add(onWindowShown); possibleEntryPoints.add(onReceive); } }
31,901
44.770445
100
java
WALA
WALA-master/dalvik/src/main/java/com/ibm/wala/dalvik/util/androidEntryPoints/package-info.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 under the terms listed below. * */ /* * Copyright (c) 2013, * Tobias Blaschke <code@tobiasblaschke.de> * All rights reserved. * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The names of the contributors may not be used to endorse or promote * products derived from this software without specific prior written * permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ /** * Hardcoded specifications of the EntryPoints of Android-components. * * <p>A specification consists of a class a possible entrypoint extends, a method-name and the * position in the model the call should be placed at. * * <p>Specifications may also exist for call-back functions not tied to a Component that causes the * start of an Application. These are only considered if the AndroidEntryPointLocator is instructed * to do so. * * <p>If a new class is added to this package the AndroidEntryPointLocator has to be adapted to load * the specifications. * * @see com.ibm.wala.dalvik.util.AndroidEntryPointLocator * @author Tobias Blaschke &lt;code@tobiasblaschke.de&gt; */ package com.ibm.wala.dalvik.util.androidEntryPoints;
2,631
44.37931
100
java
WALA
WALA-master/dalvik/src/test/java/com/ibm/wala/dalvik/drivers/APKCallGraphDriver.java
package com.ibm.wala.dalvik.drivers; import com.ibm.wala.classLoader.IClass; import com.ibm.wala.classLoader.IMethod; import com.ibm.wala.dalvik.test.callGraph.DalvikCallGraphTestBase; import com.ibm.wala.dalvik.test.util.Util; import com.ibm.wala.ipa.callgraph.AnalysisOptions.ReflectionOptions; import com.ibm.wala.ipa.callgraph.CGNode; import com.ibm.wala.ipa.callgraph.CallGraph; import com.ibm.wala.ipa.callgraph.propagation.InstanceKey; import com.ibm.wala.ipa.callgraph.propagation.PointerAnalysis; import com.ibm.wala.ipa.slicer.SDG; import com.ibm.wala.ipa.slicer.Slicer.ControlDependenceOptions; import com.ibm.wala.ipa.slicer.Slicer.DataDependenceOptions; import com.ibm.wala.util.MonitorUtil.IProgressMonitor; import com.ibm.wala.util.collections.HashSetFactory; import com.ibm.wala.util.collections.Pair; import com.ibm.wala.util.io.FileUtil; import java.io.File; import java.util.Collections; import java.util.Set; public class APKCallGraphDriver { private static final boolean dumpIR = Boolean.parseBoolean(System.getProperty("dumpIR", "false")); private static final boolean addAbstract = Boolean.parseBoolean(System.getProperty("addAbstract", "false")); private static int timeout = -1; public static void main(String[] args) { File apk = new File(args[0]); try { timeout = Integer.parseInt(args[1]); System.err.println("timeout is " + timeout); } catch (Throwable e) { // no timeout specified } FileUtil.recurseFiles( apk1 -> { System.gc(); System.err.println("Analyzing " + apk1 + "..."); try { long time = System.currentTimeMillis(); Pair<CallGraph, PointerAnalysis<InstanceKey>> CG; final long startTime = System.currentTimeMillis(); IProgressMonitor pm = new IProgressMonitor() { private boolean cancelled = false; @Override public void beginTask(String task, int totalWork) { // TODO Auto-generated method stub } @Override public void subTask(String subTask) { // TODO Auto-generated method stub } @Override public void cancel() { cancelled = true; } @Override public boolean isCanceled() { if (System.currentTimeMillis() - startTime > timeout) { cancelled = true; } return cancelled; } @Override public void done() { // TODO Auto-generated method stub } @Override public void worked(int units) { // TODO Auto-generated method stub } @Override public String getCancelMessage() { return "timeout"; } }; CG = DalvikCallGraphTestBase.makeAPKCallGraph( null, Util.androidJavaLib(), apk1.getAbsolutePath(), pm, ReflectionOptions.NONE); System.err.println("Analyzed " + apk1 + " in " + (System.currentTimeMillis() - time)); System.err.println( new SDG<>( CG.fst, CG.snd, DataDependenceOptions.NO_BASE_NO_HEAP_NO_EXCEPTIONS, ControlDependenceOptions.NONE)); if (dumpIR) { for (CGNode n1 : CG.fst) { System.err.println(n1.getIR()); System.err.println(); } } else { Set<IMethod> code = HashSetFactory.make(); for (CGNode n2 : CG.fst) { code.add(n2.getMethod()); } if (addAbstract) { for (IClass cls : CG.fst.getClassHierarchy()) { for (IMethod m1 : cls.getDeclaredMethods()) { if (m1.isAbstract() && !Collections.disjoint( CG.fst.getClassHierarchy().getPossibleTargets(m1.getReference()), code)) { code.add(m1); } } } } System.err.println("reachable methods for " + apk1); for (IMethod m2 : code) { System.err.println( m2.getDeclaringClass().getName() + " " + m2.getName() + m2.getDescriptor()); } System.err.println("end of methods"); } } catch (Throwable e) { e.printStackTrace(System.err); } }, file -> file.getName().endsWith("apk"), apk); } }
5,036
33.979167
100
java
WALA
WALA-master/dalvik/src/test/java/com/ibm/wala/dalvik/test/callGraph/DalvikCallGraphTestBase.java
/* * Copyright (c) 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.dalvik.test.callGraph; import com.ibm.wala.classLoader.IClass; import com.ibm.wala.classLoader.JarFileModule; import com.ibm.wala.classLoader.Language; import com.ibm.wala.classLoader.NewSiteReference; import com.ibm.wala.core.tests.callGraph.CallGraphTestUtil; import com.ibm.wala.core.tests.shrike.DynamicCallGraphTestBase; import com.ibm.wala.dalvik.classLoader.DexIRFactory; import com.ibm.wala.dalvik.util.AndroidAnalysisScope; import com.ibm.wala.dalvik.util.AndroidEntryPointLocator; import com.ibm.wala.ipa.callgraph.AnalysisCacheImpl; import com.ibm.wala.ipa.callgraph.AnalysisOptions; import com.ibm.wala.ipa.callgraph.AnalysisOptions.ReflectionOptions; import com.ibm.wala.ipa.callgraph.AnalysisScope; import com.ibm.wala.ipa.callgraph.CGNode; import com.ibm.wala.ipa.callgraph.CallGraph; import com.ibm.wala.ipa.callgraph.Entrypoint; import com.ibm.wala.ipa.callgraph.IAnalysisCacheView; import com.ibm.wala.ipa.callgraph.impl.Util; import com.ibm.wala.ipa.callgraph.propagation.InstanceKey; import com.ibm.wala.ipa.callgraph.propagation.PointerAnalysis; import com.ibm.wala.ipa.callgraph.propagation.SSAContextInterpreter; import com.ibm.wala.ipa.callgraph.propagation.SSAPropagationCallGraphBuilder; import com.ibm.wala.ipa.callgraph.propagation.cfa.DefaultSSAInterpreter; 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.shrike.shrikeBT.analysis.Analyzer.FailureException; import com.ibm.wala.shrike.shrikeCT.InvalidClassFileException; import com.ibm.wala.ssa.SSANewInstruction; import com.ibm.wala.types.ClassLoaderReference; import com.ibm.wala.types.MethodReference; import com.ibm.wala.types.TypeReference; import com.ibm.wala.util.CancelException; import com.ibm.wala.util.MonitorUtil.IProgressMonitor; import com.ibm.wala.util.collections.FilterIterator; import com.ibm.wala.util.collections.HashSetFactory; import com.ibm.wala.util.collections.MapIterator; import com.ibm.wala.util.collections.Pair; import com.ibm.wala.util.io.TemporaryFile; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.net.URI; import java.util.Iterator; import java.util.List; import java.util.Set; import java.util.function.Function; import java.util.function.Predicate; import java.util.jar.JarFile; public class DalvikCallGraphTestBase extends DynamicCallGraphTestBase { protected static <T> Set<T> processCG( CallGraph cg, Predicate<CGNode> filter, Function<CGNode, T> map) { Set<T> result = HashSetFactory.make(); for (CGNode n : cg) { if (filter.test(n)) { result.add(map.apply(n)); } } return result; } protected static Set<MethodReference> applicationMethods(CallGraph cg) { return processCG( cg, t -> t.getMethod() .getReference() .getDeclaringClass() .getClassLoader() .equals(ClassLoaderReference.Application), object -> object.getMethod().getReference()); } public void dynamicCG(File javaJarPath, String mainClass, String... args) throws FileNotFoundException, IOException, ClassNotFoundException, InvalidClassFileException, FailureException, SecurityException, IllegalArgumentException, InterruptedException { File F; try (final FileInputStream in = new FileInputStream(javaJarPath)) { F = TemporaryFile.streamToFile(new File("build/test_jar.jar"), in); } F.deleteOnExit(); instrument(F.getAbsolutePath()); run(mainClass.substring(1).replace('/', '.'), "LibraryExclusions.txt", args); } @SuppressWarnings("unused") private static SSAContextInterpreter makeDefaultInterpreter( AnalysisOptions options, IAnalysisCacheView cache) { return new DefaultSSAInterpreter(options, cache) { @Override public Iterator<NewSiteReference> iterateNewSites(CGNode node) { return new MapIterator<>( new FilterIterator<>( node.getIR().iterateAllInstructions(), SSANewInstruction.class::isInstance), object -> ((SSANewInstruction) object).getNewSite()); } }; } public static Pair<CallGraph, PointerAnalysis<InstanceKey>> makeAPKCallGraph( URI[] androidLibs, File androidAPIJar, String apkFileName, IProgressMonitor monitor, ReflectionOptions policy) throws IOException, ClassHierarchyException, IllegalArgumentException, CancelException { AnalysisScope scope = makeDalvikScope(androidLibs, androidAPIJar, apkFileName); final IClassHierarchy cha = ClassHierarchyFactory.make(scope); IAnalysisCacheView cache = new AnalysisCacheImpl(new DexIRFactory()); List<? extends Entrypoint> es = new AndroidEntryPointLocator().getEntryPoints(cha); assert !es.isEmpty(); AnalysisOptions options = new AnalysisOptions(scope, es); options.setReflectionOptions(policy); // SSAPropagationCallGraphBuilder cgb = Util.makeZeroCFABuilder(options, cache, cha, scope, // null, makeDefaultInterpreter(options, cache)); SSAPropagationCallGraphBuilder cgb = Util.makeZeroCFABuilder(Language.JAVA, options, cache, cha); CallGraph callGraph = cgb.makeCallGraph(options, monitor); PointerAnalysis<InstanceKey> ptrAnalysis = cgb.getPointerAnalysis(); return Pair.make(callGraph, ptrAnalysis); } public static AnalysisScope makeDalvikScope( URI[] androidLibs, File androidAPIJar, String dexFileName) throws IOException { if (androidLibs != null) { return AndroidAnalysisScope.setUpAndroidAnalysisScope( new File(dexFileName).toURI(), CallGraphTestUtil.REGRESSION_EXCLUSIONS, CallGraphTestUtil.class.getClassLoader(), androidLibs); } else { AnalysisScope scope = AndroidAnalysisScope.setUpAndroidAnalysisScope( new File(dexFileName).toURI(), CallGraphTestUtil.REGRESSION_EXCLUSIONS, CallGraphTestUtil.class.getClassLoader()); if (androidAPIJar != null) { scope.addToScope( ClassLoaderReference.Primordial, new JarFileModule(new JarFile(androidAPIJar))); } return scope; } } public static Pair<CallGraph, PointerAnalysis<InstanceKey>> makeDalvikCallGraph( URI[] androidLibs, File androidAPIJar, String mainClassName, String dexFileName) throws IOException, ClassHierarchyException, IllegalArgumentException, CancelException { AnalysisScope scope = makeDalvikScope(androidLibs, androidAPIJar, dexFileName); final IClassHierarchy cha = ClassHierarchyFactory.make(scope); TypeReference mainClassRef = TypeReference.findOrCreate(ClassLoaderReference.Application, mainClassName); IClass mainClass = cha.lookupClass(mainClassRef); assert mainClass != null; System.err.println("building call graph for " + mainClass + ":" + mainClass.getClass()); Iterable<Entrypoint> entrypoints = Util.makeMainEntrypoints(cha, mainClassName); IAnalysisCacheView cache = new AnalysisCacheImpl(new DexIRFactory()); AnalysisOptions options = new AnalysisOptions(scope, entrypoints); SSAPropagationCallGraphBuilder cgb = Util.makeZeroCFABuilder(Language.JAVA, options, cache, cha); CallGraph callGraph = cgb.makeCallGraph(options); MethodReference mmr = MethodReference.findOrCreate(mainClassRef, "main", "([Ljava/lang/String;)V"); assert !callGraph.getNodes(mmr).isEmpty(); PointerAnalysis<InstanceKey> ptrAnalysis = cgb.getPointerAnalysis(); return Pair.make(callGraph, ptrAnalysis); } }
8,099
38.320388
99
java
WALA
WALA-master/dalvik/src/test/java/com/ibm/wala/dalvik/test/callGraph/DroidBenchCGTest.java
/* * Copyright (c) 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.dalvik.test.callGraph; import static com.ibm.wala.dalvik.test.util.Util.walaProperties; import com.ibm.wala.classLoader.IClass; import com.ibm.wala.classLoader.IMethod; import com.ibm.wala.ipa.callgraph.AnalysisOptions.ReflectionOptions; import com.ibm.wala.ipa.callgraph.CallGraph; import com.ibm.wala.ipa.callgraph.propagation.InstanceKey; import com.ibm.wala.ipa.callgraph.propagation.PointerAnalysis; import com.ibm.wala.types.ClassLoaderReference; import com.ibm.wala.types.MethodReference; import com.ibm.wala.types.TypeReference; import com.ibm.wala.util.NullProgressMonitor; 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.Pair; import com.ibm.wala.util.io.FileUtil; import java.io.File; import java.net.URI; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Set; import org.junit.Assert; import org.junit.Test; public abstract class DroidBenchCGTest extends DalvikCallGraphTestBase { private static MethodReference ref(String type, String name, String sig) { return MethodReference.findOrCreate( TypeReference.findOrCreate(ClassLoaderReference.Application, type), name, sig); } private static final Map<String, Set<MethodReference>> uncalledFunctions = HashMapFactory.make(); static { Set<MethodReference> x = HashSetFactory.make(); x.add(ref("Lde/ecspride/data/User", "setPwd", "(Lde/ecspride/data/Password;)V")); x.add(ref("Lde/ecspride/data/Password", "setPassword", "(Ljava/lang/String;)V")); uncalledFunctions.put("PrivateDataLeak1.apk", x); x = HashSetFactory.make(); x.add(ref("Lde/ecspride/Datacontainer", "getSecret", "()Ljava/lang/String;")); x.add(ref("Lde/ecspride/Datacontainer", "getDescription", "()Ljava/lang/String;")); uncalledFunctions.put("FieldSensitivity1.apk", x); x = HashSetFactory.make(); x.add(ref("Lde/ecspride/Datacontainer", "getSecret", "()Ljava/lang/String;")); uncalledFunctions.put("FieldSensitivity2.apk", x); x = HashSetFactory.make(); x.add(ref("Lde/ecspride/Datacontainer", "getDescription", "()Ljava/lang/String;")); uncalledFunctions.put("FieldSensitivity3.apk", x); x = HashSetFactory.make(); x.add(ref("Lde/ecspride/ConcreteClass", "foo", "()Ljava/lang/String;")); uncalledFunctions.put("Reflection1.apk", x); x = HashSetFactory.make(); x.add(ref("Ledu/mit/dynamic_dispatch/A", "f", "()Ljava/lang/String;")); uncalledFunctions.put("VirtualDispatch2.apk", x); x = HashSetFactory.make(); x.add(ref("Ledu/mit/dynamic_dispatch/A", "f", "()Ljava/lang/String;")); uncalledFunctions.put("VirtualDispatch2.apk", x); } public static Set<IMethod> assertUserCodeReachable(CallGraph cg, Set<MethodReference> uncalled) { Set<IMethod> result = HashSetFactory.make(); for (IClass cls : Iterator2Iterable.make( cg.getClassHierarchy() .getLoader(ClassLoaderReference.Application) .iterateAllClasses())) { if (cls.isInterface()) { continue; } if (!cls.getName().toString().startsWith("Landroid") && !cls.getName().toString().equals("Lde/ecspride/R$styleable")) { for (IMethod m : cls.getDeclaredMethods()) { if (!m.isInit() && !m.isAbstract() && !uncalled.contains(m.getReference())) { if (!cg.getNodes(m.getReference()).isEmpty()) { System.err.println("found " + m); } else { result.add(m); } } } } } return result; } private final URI[] androidLibs; private final File androidJavaJar; private final String apkFile; private final Set<MethodReference> uncalled; protected DroidBenchCGTest( URI[] androidLibs, File androidJavaJar, String apkFile, Set<MethodReference> uncalled) { this.androidLibs = androidLibs; this.androidJavaJar = androidJavaJar; this.apkFile = apkFile; this.uncalled = uncalled; } public String apkFile() { return apkFile; } @Test public void runTest() throws Exception { System.err.println("testing " + apkFile + "..."); Pair<CallGraph, PointerAnalysis<InstanceKey>> x = makeAPKCallGraph( androidLibs, androidJavaJar, apkFile, new NullProgressMonitor(), ReflectionOptions.ONE_FLOW_TO_CASTS_APPLICATION_GET_METHOD); // System.err.println(x.fst); Set<IMethod> bad = assertUserCodeReachable(x.fst, uncalled); assertion(bad + " should be empty", bad.isEmpty()); System.err.println("...success testing " + apkFile); } protected void assertion(String string, boolean empty) { Assert.assertTrue(string, empty); } private static final Set<String> skipTests = HashSetFactory.make(); static { // serialization issues skipTests.add("ServiceCommunication1.apk"); skipTests.add("Parcel1.apk"); // Button2 has issues when using the fake Android jar skipTests.add("Button2.apk"); } public static Collection<Object[]> generateData( final URI[] androidLibs, final File androidJavaJar, final String filter) { return generateData(getDroidBenchRoot(), androidLibs, androidJavaJar, filter); } public static String getDroidBenchRoot() { String f = walaProperties.getProperty("droidbench.root"); if (f == null || !new File(f).exists()) { f = "build/DroidBench"; } System.err.println("Use " + f + " as droid bench root"); assert new File(f).exists() : "Use " + f + " as droid bench root"; assert new File(f + "/apk/").exists() : "Use " + f + " as droid bench root"; return f; } public static Collection<Object[]> generateData( String droidBenchRoot, final URI[] androidLibs, final File androidJavaJar, final String filter) { final List<Object[]> files = new ArrayList<>(); FileUtil.recurseFiles( f -> { Set<MethodReference> uncalled = uncalledFunctions.get(f.getName()); if (uncalled == null) { uncalled = Collections.emptySet(); } files.add(new Object[] {androidLibs, androidJavaJar, f.getAbsolutePath(), uncalled}); }, t -> (filter == null || t.getAbsolutePath().contains(filter)) && t.getName().endsWith("apk") && !skipTests.contains(t.getName()), new File(droidBenchRoot + "/apk/")); return files; } }
7,026
34.311558
99
java
WALA
WALA-master/dalvik/src/test/java/com/ibm/wala/dalvik/test/callGraph/DynamicDalvikComparisonJavaLibsTest.java
package com.ibm.wala.dalvik.test.callGraph; import com.ibm.wala.core.tests.util.TestConstants; import com.ibm.wala.ipa.cha.ClassHierarchyException; import com.ibm.wala.shrike.shrikeBT.analysis.Analyzer.FailureException; import com.ibm.wala.shrike.shrikeCT.InvalidClassFileException; import com.ibm.wala.util.CancelException; import java.io.File; import java.io.IOException; import org.junit.Test; public class DynamicDalvikComparisonJavaLibsTest extends DynamicDalvikComparisonTest { @Test public void testJLex() throws ClassHierarchyException, IllegalArgumentException, IOException, CancelException, InterruptedException, ClassNotFoundException, SecurityException, InvalidClassFileException, FailureException { File inputFile = testFile("sample.lex"); test(null, TestConstants.JLEX_MAIN, TestConstants.JLEX, inputFile.getAbsolutePath()); } @Test public void testJavaCup() throws ClassHierarchyException, IllegalArgumentException, IOException, CancelException, InterruptedException, ClassNotFoundException, SecurityException, InvalidClassFileException, FailureException { File inputFile = testFile("sample.cup"); test(null, TestConstants.JAVA_CUP_MAIN, TestConstants.JAVA_CUP, inputFile.getAbsolutePath()); } }
1,295
39.5
97
java
WALA
WALA-master/dalvik/src/test/java/com/ibm/wala/dalvik/test/callGraph/DynamicDalvikComparisonTest.java
/* * Copyright (c) 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.dalvik.test.callGraph; import static com.ibm.wala.dalvik.test.util.Util.convertJarToDex; import static com.ibm.wala.dalvik.test.util.Util.getJavaJar; import com.ibm.wala.core.tests.callGraph.CallGraphTestUtil; import com.ibm.wala.ipa.callgraph.AnalysisScope; import com.ibm.wala.ipa.callgraph.CallGraph; import com.ibm.wala.ipa.callgraph.propagation.InstanceKey; import com.ibm.wala.ipa.callgraph.propagation.PointerAnalysis; import com.ibm.wala.ipa.cha.ClassHierarchyException; import com.ibm.wala.shrike.shrikeBT.analysis.Analyzer.FailureException; import com.ibm.wala.shrike.shrikeCT.InvalidClassFileException; import com.ibm.wala.types.ClassLoaderReference; import com.ibm.wala.util.CancelException; import com.ibm.wala.util.collections.Pair; import com.ibm.wala.util.io.TemporaryFile; import java.io.File; import java.io.IOException; import java.net.URI; public abstract class DynamicDalvikComparisonTest extends DalvikCallGraphTestBase { protected void test(URI[] androidLibs, String mainClass, String javaScopeFile, String... args) throws ClassHierarchyException, IllegalArgumentException, IOException, CancelException, InterruptedException, ClassNotFoundException, SecurityException, InvalidClassFileException, FailureException { AnalysisScope javaScope = CallGraphTestUtil.makeJ2SEAnalysisScope( javaScopeFile, CallGraphTestUtil.REGRESSION_EXCLUSIONS); String javaJarPath = getJavaJar(javaScope); File androidDex = convertJarToDex(javaJarPath); Pair<CallGraph, PointerAnalysis<InstanceKey>> android = makeDalvikCallGraph(androidLibs, null, mainClass, androidDex.getAbsolutePath()); dynamicCG(new File(javaJarPath), mainClass, args); checkEdges( android.fst, t -> t.getDeclaringClass().getClassLoader().equals(ClassLoaderReference.Application)); } protected File testFile(String file) throws IOException { File inputFile = TemporaryFile.urlToFile(file, getClass().getClassLoader().getResource(file)); inputFile.deleteOnExit(); return inputFile; } }
2,467
40.830508
98
java
WALA
WALA-master/dalvik/src/test/java/com/ibm/wala/dalvik/test/callGraph/DynamicDalvikComparisonTestForAndroidLibs.java
package com.ibm.wala.dalvik.test.callGraph; import static com.ibm.wala.dalvik.test.util.Util.androidLibs; import com.ibm.wala.core.tests.util.TestConstants; import com.ibm.wala.ipa.cha.ClassHierarchyException; import com.ibm.wala.shrike.shrikeBT.analysis.Analyzer.FailureException; import com.ibm.wala.shrike.shrikeCT.InvalidClassFileException; import com.ibm.wala.util.CancelException; import java.io.File; import java.io.IOException; import java.net.URI; import org.junit.Test; public class DynamicDalvikComparisonTestForAndroidLibs extends DynamicDalvikComparisonTest { protected URI[] providedAndroidLibs() { return androidLibs(); } @Test public void testJLex() throws ClassHierarchyException, IllegalArgumentException, IOException, CancelException, InterruptedException, ClassNotFoundException, SecurityException, InvalidClassFileException, FailureException { File inputFile = testFile("sample.lex"); test( providedAndroidLibs(), TestConstants.JLEX_MAIN, TestConstants.JLEX, inputFile.getAbsolutePath()); } @Test public void testJavaCup() throws ClassHierarchyException, IllegalArgumentException, IOException, CancelException, InterruptedException, ClassNotFoundException, SecurityException, InvalidClassFileException, FailureException { File inputFile = testFile("sample.cup"); test( providedAndroidLibs(), TestConstants.JAVA_CUP_MAIN, TestConstants.JAVA_CUP, inputFile.getAbsolutePath()); } }
1,558
32.170213
93
java
WALA
WALA-master/dalvik/src/test/java/com/ibm/wala/dalvik/test/callGraph/JVMLDalvikComparisonTest.java
/* * Copyright (c) 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.dalvik.test.callGraph; import static com.ibm.wala.dalvik.test.util.Util.convertJarToDex; import static com.ibm.wala.dalvik.test.util.Util.getJavaJar; import com.ibm.wala.classLoader.Language; import com.ibm.wala.classLoader.ShrikeCTMethod; import com.ibm.wala.core.tests.callGraph.CallGraphTestUtil; import com.ibm.wala.core.tests.util.TestConstants; import com.ibm.wala.dalvik.classLoader.DexIMethod; import com.ibm.wala.ipa.callgraph.AnalysisCacheImpl; import com.ibm.wala.ipa.callgraph.AnalysisOptions; import com.ibm.wala.ipa.callgraph.AnalysisScope; import com.ibm.wala.ipa.callgraph.CGNode; import com.ibm.wala.ipa.callgraph.CallGraph; import com.ibm.wala.ipa.callgraph.Entrypoint; import com.ibm.wala.ipa.callgraph.impl.Util; import com.ibm.wala.ipa.callgraph.propagation.InstanceKey; import com.ibm.wala.ipa.callgraph.propagation.LocalPointerKey; import com.ibm.wala.ipa.callgraph.propagation.PointerAnalysis; import com.ibm.wala.ipa.callgraph.propagation.ReturnValueKey; import com.ibm.wala.ipa.callgraph.propagation.SSAPropagationCallGraphBuilder; import com.ibm.wala.ipa.callgraph.propagation.cfa.ExceptionReturnValueKey; import com.ibm.wala.ipa.cha.ClassHierarchy; import com.ibm.wala.ipa.cha.ClassHierarchyException; import com.ibm.wala.ipa.cha.ClassHierarchyFactory; import com.ibm.wala.shrike.shrikeCT.InvalidClassFileException; import com.ibm.wala.ssa.SSAInstruction; import com.ibm.wala.types.ClassLoaderReference; import com.ibm.wala.types.MethodReference; import com.ibm.wala.util.CancelException; import com.ibm.wala.util.collections.HashSetFactory; import com.ibm.wala.util.collections.Iterator2Collection; import com.ibm.wala.util.collections.Pair; import com.ibm.wala.util.intset.IntSet; import com.ibm.wala.util.intset.IntSetUtil; import com.ibm.wala.util.intset.MutableIntSet; import com.ibm.wala.util.intset.OrdinalSet; import java.io.File; import java.io.IOException; import java.util.Iterator; import java.util.Set; import org.junit.Test; public class JVMLDalvikComparisonTest extends DalvikCallGraphTestBase { private static Pair<CallGraph, PointerAnalysis<InstanceKey>> makeJavaBuilder( String scopeFile, String mainClass) throws IOException, ClassHierarchyException, IllegalArgumentException, CancelException { AnalysisScope scope = CallGraphTestUtil.makeJ2SEAnalysisScope(scopeFile, CallGraphTestUtil.REGRESSION_EXCLUSIONS); ClassHierarchy cha = ClassHierarchyFactory.make(scope); Iterable<Entrypoint> entrypoints = com.ibm.wala.ipa.callgraph.impl.Util.makeMainEntrypoints(cha, mainClass); AnalysisOptions options = CallGraphTestUtil.makeAnalysisOptions(scope, entrypoints); SSAPropagationCallGraphBuilder builder = Util.makeZeroCFABuilder(Language.JAVA, options, new AnalysisCacheImpl(), cha); CallGraph CG = builder.makeCallGraph(options); return Pair.make(CG, builder.getPointerAnalysis()); } private static Set<Pair<CGNode, CGNode>> edgeDiff( CallGraph from, CallGraph to, boolean userOnly) { Set<Pair<CGNode, CGNode>> result = HashSetFactory.make(); for (CGNode f : from) { if (!f.getMethod().isWalaSynthetic()) { outer: for (CGNode t : from) { if (!t.getMethod().isWalaSynthetic() && from.hasEdge(f, t) && (!userOnly || !t.getMethod() .getDeclaringClass() .getClassLoader() .getReference() .equals(ClassLoaderReference.Primordial))) { Set<CGNode> fts = to.getNodes(f.getMethod().getReference()); Set<CGNode> tts = to.getNodes(t.getMethod().getReference()); for (CGNode x : fts) { for (CGNode y : tts) { if (to.hasEdge(x, y)) { continue outer; } } } result.add(Pair.make(f, t)); } } } } return result; } private static void test(String mainClass, String javaScopeFile) throws IllegalArgumentException, IOException, CancelException, ClassHierarchyException { Pair<CallGraph, PointerAnalysis<InstanceKey>> java = makeJavaBuilder(javaScopeFile, mainClass); AnalysisScope javaScope = java.fst.getClassHierarchy().getScope(); String javaJarPath = getJavaJar(javaScope); File androidDex = convertJarToDex(javaJarPath); Pair<CallGraph, PointerAnalysis<InstanceKey>> android = makeDalvikCallGraph(null, null, mainClass, androidDex.getAbsolutePath()); Set<MethodReference> androidMethods = applicationMethods(android.fst); Set<MethodReference> javaMethods = applicationMethods(java.fst); Iterator<Pair<CGNode, CGNode>> javaExtraEdges = edgeDiff(java.fst, android.fst, false).iterator(); assert !checkEdgeDiff(android, androidMethods, javaMethods, javaExtraEdges); Iterator<Pair<CGNode, CGNode>> androidExtraEdges = edgeDiff(android.fst, java.fst, true).iterator(); assert !checkEdgeDiff(java, javaMethods, androidMethods, androidExtraEdges); checkSourceLines(java.fst, android.fst); } private static void checkSourceLines(CallGraph java, CallGraph android) { MutableIntSet ajlines = IntSetUtil.make(); MutableIntSet aalines = IntSetUtil.make(); java.forEach( jnode -> { if (jnode .getMethod() .getReference() .getDeclaringClass() .getClassLoader() .equals(ClassLoaderReference.Application)) { if (jnode.getMethod() instanceof ShrikeCTMethod) { ShrikeCTMethod m = (ShrikeCTMethod) jnode.getMethod(); MutableIntSet jlines = IntSetUtil.make(); for (SSAInstruction inst : jnode.getIR().getInstructions()) { if (inst != null) { try { int bcIndex = m.getBytecodeIndex(inst.iIndex()); int javaLine = m.getLineNumber(bcIndex); jlines.add(javaLine); ajlines.add(javaLine); } catch (InvalidClassFileException e) { assert false : e; } } } for (CGNode an : android.getNodes(m.getReference())) { DexIMethod am = (DexIMethod) an.getMethod(); MutableIntSet alines = IntSetUtil.make(); for (SSAInstruction ainst : an.getIR().getInstructions()) { if (ainst != null) { int ai = am.getLineNumber(am.getBytecodeIndex(ainst.iIndex())); if (ai >= 0) { alines.add(ai); aalines.add(ai); } } } assert alines.size() > 0 : "no debug info"; } } } }); IntSet both = ajlines.intersection(aalines); assert both.size() >= .8 * ajlines.size() : "inconsistent debug info: " + ajlines + " " + aalines; } private static boolean checkEdgeDiff( Pair<CallGraph, PointerAnalysis<InstanceKey>> android, Set<MethodReference> androidMethods, Set<MethodReference> javaMethods, Iterator<Pair<CGNode, CGNode>> javaExtraEdges) { boolean fail = false; if (javaExtraEdges.hasNext()) { fail = true; Set<MethodReference> javaExtraNodes = HashSetFactory.make(javaMethods); javaExtraNodes.removeAll(androidMethods); System.err.println(Iterator2Collection.toSet(javaExtraEdges)); System.err.println(javaExtraNodes); System.err.println(android.fst); for (CGNode n : android.fst) { System.err.println("### " + n); if (n.getIR() != null) { System.err.println(n.getIR()); System.err.println("return: " + android.snd.getPointsToSet(new ReturnValueKey(n))); System.err.println( "exceptions: " + android.snd.getPointsToSet(new ExceptionReturnValueKey(n))); for (int i = 1; i < n.getIR().getSymbolTable().getMaxValueNumber(); i++) { LocalPointerKey x = new LocalPointerKey(n, i); OrdinalSet<InstanceKey> s = android.snd.getPointsToSet(x); if (s != null && !s.isEmpty()) { System.err.println(i + ": " + s); } } } } } return fail; } @Test public void testJLex() throws ClassHierarchyException, IllegalArgumentException, IOException, CancelException { test(TestConstants.JLEX_MAIN, TestConstants.JLEX); } @Test public void testJavaCup() throws ClassHierarchyException, IllegalArgumentException, IOException, CancelException { test(TestConstants.JAVA_CUP_MAIN, TestConstants.JAVA_CUP); } @Test public void testBCEL() throws ClassHierarchyException, IllegalArgumentException, IOException, CancelException { test(TestConstants.BCEL_VERIFIER_MAIN, TestConstants.BCEL); } }
9,390
39.132479
100
java
WALA
WALA-master/dalvik/src/test/java/com/ibm/wala/dalvik/test/callGraph/droidbench/AliasingTest.java
package com.ibm.wala.dalvik.test.callGraph.droidbench; import static com.ibm.wala.dalvik.test.util.Util.androidJavaLib; import com.ibm.wala.dalvik.test.callGraph.DroidBenchCGTest; import com.ibm.wala.types.MethodReference; import java.io.File; import java.io.IOException; import java.net.URI; import java.util.Collection; import java.util.Set; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameters; @RunWith(Parameterized.class) public class AliasingTest extends DroidBenchCGTest { public AliasingTest( URI[] androidLibs, File androidJavaJar, String apkFile, Set<MethodReference> uncalled) { super(androidLibs, androidJavaJar, apkFile, uncalled); } @Parameters(name = "DroidBench: {2}") public static Collection<Object[]> generateData() throws IOException { return DroidBenchCGTest.generateData(null, androidJavaLib(), "Aliasing"); } }
934
31.241379
94
java
WALA
WALA-master/dalvik/src/test/java/com/ibm/wala/dalvik/test/callGraph/droidbench/AndroidSpecificTest.java
package com.ibm.wala.dalvik.test.callGraph.droidbench; import static com.ibm.wala.dalvik.test.util.Util.androidJavaLib; import com.ibm.wala.dalvik.test.callGraph.DroidBenchCGTest; import com.ibm.wala.types.MethodReference; import java.io.File; import java.io.IOException; import java.net.URI; import java.util.Collection; import java.util.Set; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameters; @RunWith(Parameterized.class) public class AndroidSpecificTest extends DroidBenchCGTest { public AndroidSpecificTest( URI[] androidLibs, File androidJavaJar, String apkFile, Set<MethodReference> uncalled) { super(androidLibs, androidJavaJar, apkFile, uncalled); } @Parameters(name = "DroidBench: {2}") public static Collection<Object[]> generateData() throws IOException { return DroidBenchCGTest.generateData(null, androidJavaLib(), "AndroidSpecific"); } }
955
31.965517
94
java
WALA
WALA-master/dalvik/src/test/java/com/ibm/wala/dalvik/test/callGraph/droidbench/ArraysAndListsTest.java
package com.ibm.wala.dalvik.test.callGraph.droidbench; import static com.ibm.wala.dalvik.test.util.Util.androidJavaLib; import com.ibm.wala.dalvik.test.callGraph.DroidBenchCGTest; import com.ibm.wala.types.MethodReference; import java.io.File; import java.io.IOException; import java.net.URI; import java.util.Collection; import java.util.Set; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameters; @RunWith(Parameterized.class) public class ArraysAndListsTest extends DroidBenchCGTest { public ArraysAndListsTest( URI[] androidLibs, File androidJavaJar, String apkFile, Set<MethodReference> uncalled) { super(androidLibs, androidJavaJar, apkFile, uncalled); } @Parameters(name = "DroidBench: {2}") public static Collection<Object[]> generateData() throws IOException { return DroidBenchCGTest.generateData(null, androidJavaLib(), "ArraysAndLists"); } }
952
31.862069
94
java
WALA
WALA-master/dalvik/src/test/java/com/ibm/wala/dalvik/test/callGraph/droidbench/CallbacksTest.java
package com.ibm.wala.dalvik.test.callGraph.droidbench; import static com.ibm.wala.dalvik.test.util.Util.androidJavaLib; import com.ibm.wala.dalvik.test.callGraph.DroidBenchCGTest; import com.ibm.wala.types.MethodReference; import java.io.File; import java.io.IOException; import java.net.URI; import java.util.Collection; import java.util.Set; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameters; @RunWith(Parameterized.class) public class CallbacksTest extends DroidBenchCGTest { public CallbacksTest( URI[] androidLibs, File androidJavaJar, String apkFile, Set<MethodReference> uncalled) { super(androidLibs, androidJavaJar, apkFile, uncalled); } @Parameters(name = "DroidBench: {2}") public static Collection<Object[]> generateData() throws IOException { return DroidBenchCGTest.generateData(null, androidJavaLib(), "Callbacks"); } }
937
31.344828
94
java
WALA
WALA-master/dalvik/src/test/java/com/ibm/wala/dalvik/test/callGraph/droidbench/EmulatorDetectionTest.java
package com.ibm.wala.dalvik.test.callGraph.droidbench; import static com.ibm.wala.dalvik.test.util.Util.androidJavaLib; import com.ibm.wala.dalvik.test.callGraph.DroidBenchCGTest; import com.ibm.wala.types.MethodReference; import java.io.File; import java.io.IOException; import java.net.URI; import java.util.Collection; import java.util.Set; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameters; @RunWith(Parameterized.class) public class EmulatorDetectionTest extends DroidBenchCGTest { public EmulatorDetectionTest( URI[] androidLibs, File androidJavaJar, String apkFile, Set<MethodReference> uncalled) { super(androidLibs, androidJavaJar, apkFile, uncalled); } @Parameters(name = "DroidBench: {2}") public static Collection<Object[]> generateData() throws IOException { return DroidBenchCGTest.generateData(null, androidJavaLib(), "EmulatorDetection"); } }
960
33.321429
94
java
WALA
WALA-master/dalvik/src/test/java/com/ibm/wala/dalvik/test/callGraph/droidbench/FieldAndObjectSensitivityTest.java
package com.ibm.wala.dalvik.test.callGraph.droidbench; import static com.ibm.wala.dalvik.test.util.Util.androidJavaLib; import com.ibm.wala.dalvik.test.callGraph.DroidBenchCGTest; import com.ibm.wala.types.MethodReference; import java.io.File; import java.io.IOException; import java.net.URI; import java.util.Collection; import java.util.Set; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameters; @RunWith(Parameterized.class) public class FieldAndObjectSensitivityTest extends DroidBenchCGTest { public FieldAndObjectSensitivityTest( URI[] androidLibs, File androidJavaJar, String apkFile, Set<MethodReference> uncalled) { super(androidLibs, androidJavaJar, apkFile, uncalled); } @Parameters(name = "DroidBench: {2}") public static Collection<Object[]> generateData() throws IOException { return DroidBenchCGTest.generateData(null, androidJavaLib(), "FieldAndObjectSensitivity"); } }
985
33
94
java
WALA
WALA-master/dalvik/src/test/java/com/ibm/wala/dalvik/test/callGraph/droidbench/GeneralJavaTest.java
package com.ibm.wala.dalvik.test.callGraph.droidbench; import static com.ibm.wala.dalvik.test.util.Util.androidJavaLib; import com.ibm.wala.dalvik.test.callGraph.DroidBenchCGTest; import com.ibm.wala.types.MethodReference; import java.io.File; import java.io.IOException; import java.net.URI; import java.util.Collection; import java.util.Set; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameters; @RunWith(Parameterized.class) public class GeneralJavaTest extends DroidBenchCGTest { public GeneralJavaTest( URI[] androidLibs, File androidJavaJar, String apkFile, Set<MethodReference> uncalled) { super(androidLibs, androidJavaJar, apkFile, uncalled); } @Parameters(name = "DroidBench: {2}") public static Collection<Object[]> generateData() throws IOException { return DroidBenchCGTest.generateData(null, androidJavaLib(), "GeneralJava"); } }
943
31.551724
94
java
WALA
WALA-master/dalvik/src/test/java/com/ibm/wala/dalvik/test/callGraph/droidbench/ImplicitFlowsTest.java
package com.ibm.wala.dalvik.test.callGraph.droidbench; import static com.ibm.wala.dalvik.test.util.Util.androidJavaLib; import com.ibm.wala.dalvik.test.callGraph.DroidBenchCGTest; import com.ibm.wala.types.MethodReference; import java.io.File; import java.io.IOException; import java.net.URI; import java.util.Collection; import java.util.Set; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameters; @RunWith(Parameterized.class) public class ImplicitFlowsTest extends DroidBenchCGTest { public ImplicitFlowsTest( URI[] androidLibs, File androidJavaJar, String apkFile, Set<MethodReference> uncalled) { super(androidLibs, androidJavaJar, apkFile, uncalled); } @Parameters(name = "DroidBench: {2}") public static Collection<Object[]> generateData() throws IOException { return DroidBenchCGTest.generateData(null, androidJavaLib(), "ImplicitFlows"); } }
949
31.758621
94
java
WALA
WALA-master/dalvik/src/test/java/com/ibm/wala/dalvik/test/callGraph/droidbench/InterAppCommunicationTest.java
package com.ibm.wala.dalvik.test.callGraph.droidbench; import static com.ibm.wala.dalvik.test.util.Util.androidJavaLib; import com.ibm.wala.dalvik.test.callGraph.DroidBenchCGTest; import com.ibm.wala.types.MethodReference; import java.io.File; import java.io.IOException; import java.net.URI; import java.util.Collection; import java.util.Set; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameters; @RunWith(Parameterized.class) public class InterAppCommunicationTest extends DroidBenchCGTest { public InterAppCommunicationTest( URI[] androidLibs, File androidJavaJar, String apkFile, Set<MethodReference> uncalled) { super(androidLibs, androidJavaJar, apkFile, uncalled); } @Parameters(name = "DroidBench: {2}") public static Collection<Object[]> generateData() throws IOException { return DroidBenchCGTest.generateData(null, androidJavaLib(), "InterAppCommunication"); } }
972
33.75
94
java
WALA
WALA-master/dalvik/src/test/java/com/ibm/wala/dalvik/test/callGraph/droidbench/InterComponentCommunicationTest.java
package com.ibm.wala.dalvik.test.callGraph.droidbench; import static com.ibm.wala.dalvik.test.util.Util.androidJavaLib; import com.ibm.wala.dalvik.test.callGraph.DroidBenchCGTest; import com.ibm.wala.types.MethodReference; import java.io.File; import java.io.IOException; import java.net.URI; import java.util.Collection; import java.util.Set; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameters; @RunWith(Parameterized.class) public class InterComponentCommunicationTest extends DroidBenchCGTest { public InterComponentCommunicationTest( URI[] androidLibs, File androidJavaJar, String apkFile, Set<MethodReference> uncalled) { super(androidLibs, androidJavaJar, apkFile, uncalled); } @Parameters(name = "DroidBench: {2}") public static Collection<Object[]> generateData() throws IOException { return DroidBenchCGTest.generateData(null, androidJavaLib(), "InterComponentCommunication"); } }
991
33.206897
96
java
WALA
WALA-master/dalvik/src/test/java/com/ibm/wala/dalvik/test/callGraph/droidbench/LifecycleTest.java
package com.ibm.wala.dalvik.test.callGraph.droidbench; import static com.ibm.wala.dalvik.test.util.Util.androidJavaLib; import com.ibm.wala.dalvik.test.callGraph.DroidBenchCGTest; import com.ibm.wala.types.MethodReference; import java.io.File; import java.io.IOException; import java.net.URI; import java.util.Collection; import java.util.Set; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameters; @RunWith(Parameterized.class) public class LifecycleTest extends DroidBenchCGTest { public LifecycleTest( URI[] androidLibs, File androidJavaJar, String apkFile, Set<MethodReference> uncalled) { super(androidLibs, androidJavaJar, apkFile, uncalled); } @Parameters(name = "DroidBench: {2}") public static Collection<Object[]> generateData() throws IOException { return DroidBenchCGTest.generateData(null, androidJavaLib(), "Lifecycle"); } }
937
31.344828
94
java
WALA
WALA-master/dalvik/src/test/java/com/ibm/wala/dalvik/test/callGraph/droidbench/ReflectionTest.java
package com.ibm.wala.dalvik.test.callGraph.droidbench; import static com.ibm.wala.dalvik.test.util.Util.androidJavaLib; import com.ibm.wala.dalvik.test.callGraph.DroidBenchCGTest; import com.ibm.wala.types.MethodReference; import java.io.File; import java.io.IOException; import java.net.URI; import java.util.Collection; import java.util.Set; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameters; @RunWith(Parameterized.class) public class ReflectionTest extends DroidBenchCGTest { public ReflectionTest( URI[] androidLibs, File androidJavaJar, String apkFile, Set<MethodReference> uncalled) { super(androidLibs, androidJavaJar, apkFile, uncalled); } @Parameters(name = "DroidBench: {2}") public static Collection<Object[]> generateData() throws IOException { return DroidBenchCGTest.generateData(null, androidJavaLib(), "Reflection"); } }
940
31.448276
94
java
WALA
WALA-master/dalvik/src/test/java/com/ibm/wala/dalvik/test/callGraph/droidbench/ThreadingTest.java
package com.ibm.wala.dalvik.test.callGraph.droidbench; import static com.ibm.wala.dalvik.test.util.Util.androidJavaLib; import com.ibm.wala.dalvik.test.callGraph.DroidBenchCGTest; import com.ibm.wala.types.MethodReference; import java.io.File; import java.io.IOException; import java.net.URI; import java.util.Collection; import java.util.Set; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameters; @RunWith(Parameterized.class) public class ThreadingTest extends DroidBenchCGTest { public ThreadingTest( URI[] androidLibs, File androidJavaJar, String apkFile, Set<MethodReference> uncalled) { super(androidLibs, androidJavaJar, apkFile, uncalled); } @Parameters(name = "DroidBench: {2}") public static Collection<Object[]> generateData() throws IOException { return DroidBenchCGTest.generateData(null, androidJavaLib(), "Threading"); } }
937
31.344828
94
java
WALA
WALA-master/dalvik/src/test/java/com/ibm/wala/dalvik/test/cha/MultiDexScopeTest.java
package com.ibm.wala.dalvik.test.cha; import static org.junit.Assume.assumeFalse; import com.ibm.wala.classLoader.IClass; import com.ibm.wala.classLoader.IMethod; import com.ibm.wala.core.util.config.AnalysisScopeReader; import com.ibm.wala.dalvik.classLoader.DexFileModule; import com.ibm.wala.dalvik.classLoader.DexIRFactory; import com.ibm.wala.dalvik.test.callGraph.DalvikCallGraphTestBase; import com.ibm.wala.dalvik.test.callGraph.DroidBenchCGTest; 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.CallGraphBuilderCancelException; 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.ClassHierarchy; import com.ibm.wala.ipa.cha.ClassHierarchyException; import com.ibm.wala.ipa.cha.ClassHierarchyFactory; import com.ibm.wala.types.ClassLoaderReference; import com.ibm.wala.types.MethodReference; import com.ibm.wala.types.Selector; import com.ibm.wala.types.TypeReference; import com.ibm.wala.util.PlatformUtil; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.util.ArrayList; import java.util.Iterator; import java.util.Set; import java.util.zip.ZipEntry; import java.util.zip.ZipInputStream; import org.jf.dexlib2.DexFileFactory; import org.jf.dexlib2.Opcodes; import org.jf.dexlib2.dexbacked.DexBackedDexFile; import org.jf.dexlib2.iface.MultiDexContainer; import org.junit.Assert; import org.junit.Test; public class MultiDexScopeTest { private static void addAPKtoScope( ClassLoaderReference loader, AnalysisScope scope, String fileName) { File apkFile = new File(fileName); MultiDexContainer<? extends DexBackedDexFile> multiDex = null; try { multiDex = DexFileFactory.loadDexContainer(apkFile, Opcodes.forApi(24)); } catch (IOException e) { throw new RuntimeException(e); } try { for (String dexEntry : multiDex.getDexEntryNames()) { System.out.println("Adding dex file: " + dexEntry + " of file:" + fileName); scope.addToScope(loader, new DexFileModule(apkFile, dexEntry, 24)); } } catch (IOException e) { throw new RuntimeException(e); } } private static AnalysisScope setUpTestScope(String apkName, String exclusions, ClassLoader loader) throws IOException { AnalysisScope scope; scope = AnalysisScopeReader.instance.readJavaScope("primordial.txt", new File(exclusions), loader); scope.setLoaderImpl( ClassLoaderReference.Application, "com.ibm.wala.dalvik.classLoader.WDexClassLoaderImpl"); addAPKtoScope(ClassLoaderReference.Application, scope, apkName); return scope; } private static int getNumberOfAppClasses(ClassHierarchy cha) { Iterator<IClass> classes = cha.iterator(); int numberOfClasses = 0; while (classes.hasNext()) { if (classes.next().getClassLoader().getName().toString().equals("Application")) numberOfClasses++; } return numberOfClasses; } @Test public void testAPK() throws ClassHierarchyException, IOException { // Known to be broken on Windows, but not intentionally so. Please fix if you know how! // <https://github.com/wala/WALA/issues/608> assumeFalse(PlatformUtil.onWindows()); AnalysisScope scope, scope2; ClassHierarchy cha, cha2; String testAPK = DroidBenchCGTest.getDroidBenchRoot() + "/apk/Aliasing/Merge1.apk"; scope = setUpTestScope(testAPK, "", MultiDexScopeTest.class.getClassLoader()); cha = ClassHierarchyFactory.make(scope); scope2 = DalvikCallGraphTestBase.makeDalvikScope(null, null, testAPK); cha2 = ClassHierarchyFactory.make(scope2); Assert.assertEquals( Integer.valueOf(getNumberOfAppClasses(cha)), Integer.valueOf(getNumberOfAppClasses(cha2))); } public AnalysisScope manuallyInitScope() throws IOException { String multidexApk = "src/test/resources/multidex-test.apk"; AnalysisScope scope = AnalysisScopeReader.instance.readJavaScope( "primordial.txt", new File(""), MultiDexScopeTest.class.getClassLoader()); scope.setLoaderImpl( ClassLoaderReference.Application, "com.ibm.wala.dalvik.classLoader.WDexClassLoaderImpl"); try { // extract dex files to disk and add them manually to scope File dexTmpDir = new File(System.getProperty("java.io.tmpdir")); extractDexFiles(multidexApk, dexTmpDir); File dex1 = new File(dexTmpDir + File.separator + "classes.dex"); scope.addToScope(ClassLoaderReference.Application, DexFileModule.make(dex1)); dex1.delete(); File dex2 = new File(dexTmpDir + File.separator + "classes2.dex"); scope.addToScope(ClassLoaderReference.Application, DexFileModule.make(dex2)); dex2.delete(); } catch (IOException e) { throw new RuntimeException(e); } return scope; } @Test public void testMultiDex() throws ClassHierarchyException, IOException { AnalysisScope scope, scope2; ClassHierarchy cha, cha2; String multidexApk = "src/test/resources/multidex-test.apk"; scope = manuallyInitScope(); cha = ClassHierarchyFactory.make(scope); scope2 = DalvikCallGraphTestBase.makeDalvikScope(null, null, multidexApk); cha2 = ClassHierarchyFactory.make(scope2); Assert.assertEquals(Integer.valueOf(getNumberOfAppClasses(cha)), Integer.valueOf(5)); Assert.assertEquals( Integer.valueOf(getNumberOfAppClasses(cha)), Integer.valueOf(getNumberOfAppClasses(cha2))); } private static void extractDexFiles(String apkFileName, File outDir) throws IOException { try (ZipInputStream zis = new ZipInputStream(new FileInputStream(apkFileName))) { ZipEntry entry; while ((entry = zis.getNextEntry()) != null) { if (!entry.isDirectory()) { if (entry.getName().startsWith("classes") && entry.getName().endsWith(".dex")) { extractFile(zis, outDir + File.separator + entry.getName()); } } zis.closeEntry(); } } } @Test public void testCGCreationFromDexSource() throws ClassHierarchyException, IOException, CallGraphBuilderCancelException { AnalysisScope scope = manuallyInitScope(); ClassHierarchy cha = ClassHierarchyFactory.make(scope); AnalysisCacheImpl cache = new AnalysisCacheImpl(new DexIRFactory()); TypeReference b2 = TypeReference.find(ClassLoaderReference.Application, "Ltest/B2"); TypeReference b = TypeReference.find(ClassLoaderReference.Application, "Ltest/B"); MethodReference callerRef = MethodReference.findOrCreate(b2, "<init>", "(ILjava/lang/String;)V"); MethodReference calleeRef = MethodReference.findOrCreate(b, "<init>", "(I)V"); IClass b2Class = cha.lookupClass(b2); IMethod targetMethod = b2Class.getMethod(Selector.make("<init>(ILjava/lang/String;)V")); ArrayList<DefaultEntrypoint> entrypoints = new ArrayList<>(); entrypoints.add(new DefaultEntrypoint(targetMethod, cha)); AnalysisOptions options = new AnalysisOptions(); options.setAnalysisScope(scope); options.setEntrypoints(entrypoints); options.setReflectionOptions(AnalysisOptions.ReflectionOptions.NONE); CallGraphBuilder<InstanceKey> cgb = Util.makeRTABuilder(options, cache, cha); CallGraph cg1 = cgb.makeCallGraph(options, null); findEdge(cg1, callerRef, calleeRef); cgb = Util.makeZeroOneContainerCFABuilder(options, cache, cha, null, null); CallGraph cg2 = cgb.makeCallGraph(options, null); findEdge(cg2, callerRef, calleeRef); } public static void findEdge(CallGraph cg, MethodReference callerRef, MethodReference calleeRef) { Set<CGNode> callerNodes = cg.getNodes(callerRef); Assert.assertFalse(callerNodes.isEmpty()); CGNode callerNode = callerNodes.iterator().next(); Set<CGNode> calleeNodes = cg.getNodes(calleeRef); Assert.assertFalse(calleeNodes.isEmpty()); CGNode calleeNode = calleeNodes.iterator().next(); Assert.assertTrue(cg.hasEdge(callerNode, calleeNode)); } private static void extractFile(ZipInputStream zipIn, String outFileName) throws IOException { try (BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(outFileName))) { byte[] buffer = new byte[4096]; int read; while ((read = zipIn.read(buffer)) != -1) { bos.write(buffer, 0, read); } } } }
8,757
37.924444
100
java
WALA
WALA-master/dalvik/src/test/java/com/ibm/wala/dalvik/test/ir/DalvikAnnotationsTest.java
package com.ibm.wala.dalvik.test.ir; import com.ibm.wala.core.tests.ir.AnnotationTest; import com.ibm.wala.dalvik.test.util.Util; import com.ibm.wala.ipa.cha.ClassHierarchyException; import java.io.IOException; public class DalvikAnnotationsTest extends AnnotationTest { public static void main(String[] args) { justThisTest(DalvikAnnotationsTest.class); } public DalvikAnnotationsTest() throws ClassHierarchyException, IOException { super(Util.makeCHA(), true); } }
487
26.111111
78
java
WALA
WALA-master/dalvik/src/test/java/com/ibm/wala/dalvik/test/util/Util.java
package com.ibm.wala.dalvik.test.util; import static com.ibm.wala.properties.WalaProperties.ANDROID_RT_DEX_DIR; import static com.ibm.wala.properties.WalaProperties.ANDROID_RT_JAVA_JAR; import com.android.tools.r8.CompilationFailedException; import com.android.tools.r8.D8; import com.android.tools.r8.D8Command; import com.android.tools.r8.OutputMode; import com.ibm.wala.classLoader.JarFileModule; import com.ibm.wala.classLoader.Module; import com.ibm.wala.classLoader.NestedJarFileModule; import com.ibm.wala.core.util.io.FileProvider; import com.ibm.wala.dalvik.test.callGraph.DalvikCallGraphTestBase; import com.ibm.wala.ipa.callgraph.AnalysisScope; 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.properties.WalaProperties; import com.ibm.wala.util.WalaException; import com.ibm.wala.util.io.TemporaryFile; import java.io.File; import java.io.IOException; import java.net.URI; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.ArrayList; import java.util.List; import java.util.Properties; public class Util { public static Properties walaProperties; static { try { walaProperties = WalaProperties.loadProperties(); } catch (WalaException e) { walaProperties = null; } } public static String getJavaJar(AnalysisScope javaScope) throws IOException { Module javaJar = javaScope.getModules(javaScope.getApplicationLoader()).iterator().next(); if (javaJar instanceof JarFileModule) { String javaJarPath = ((JarFileModule) javaJar).getAbsolutePath(); return javaJarPath; } else { assert javaJar instanceof NestedJarFileModule : javaJar; File F = File.createTempFile("android", ".jar"); // F.deleteOnExit(); System.err.println(F.getAbsolutePath()); TemporaryFile.streamToFile(F, ((NestedJarFileModule) javaJar).getNestedContents()); return F.getAbsolutePath(); } } public static File convertJarToDex(String jarFile) throws IOException { Path tmpDir = Files.createTempDirectory("dex"); tmpDir.toFile().deleteOnExit(); try { D8.run( D8Command.builder() .addLibraryFiles(Paths.get(androidJavaLib().getAbsolutePath())) .setMinApiLevel(26) .setOutput(tmpDir, OutputMode.DexIndexed) .addProgramFiles(Paths.get(jarFile)) .build()); } catch (CompilationFailedException e) { throw new RuntimeException("Unexpected compilation failure in D8!", e); } return tmpDir.resolve("classes.dex").toFile(); } public static File androidJavaLib() throws IOException { if (walaProperties != null && walaProperties.getProperty(ANDROID_RT_JAVA_JAR) != null) { return new File(walaProperties.getProperty(ANDROID_RT_JAVA_JAR)); } else { File F = File.createTempFile("android", ".jar"); F.deleteOnExit(); TemporaryFile.urlToFile(F, Util.class.getClassLoader().getResource("android.jar")); return F; } } public static URI[] androidLibs() { List<URI> libs = new ArrayList<>(); if (System.getenv("ANDROID_BOOT_OAT") != null) { libs.add(new File(System.getenv("ANDROID_CORE_OAT")).toURI()); libs.add(new File(System.getenv("ANDROID_BOOT_OAT")).toURI()); } else if (walaProperties != null && walaProperties.getProperty(ANDROID_RT_DEX_DIR) != null) { for (File lib : new File(walaProperties.getProperty(ANDROID_RT_DEX_DIR)) .listFiles((dir, name) -> name.startsWith("boot") && name.endsWith("oat"))) { libs.add(lib.toURI()); } } else { assert "Dalvik".equals(System.getProperty("java.vm.name")); for (File f : new File("/system/framework/") .listFiles( pathname -> { String name = pathname.getName(); return (name.startsWith("core") || name.startsWith("framework")) && (name.endsWith("jar") || name.endsWith("apk")); })) { System.out.println("adding " + f); libs.add(f.toURI()); } } return libs.toArray(new URI[0]); } public static IClassHierarchy makeCHA() throws IOException, ClassHierarchyException { File F = File.createTempFile("walatest", ".jar"); F.deleteOnExit(); TemporaryFile.urlToFile( F, new FileProvider().getResource("com.ibm.wala.core.testdata_1.0.0a.jar")); File androidDex = convertJarToDex(F.getAbsolutePath()); AnalysisScope dalvikScope = DalvikCallGraphTestBase.makeDalvikScope(null, null, androidDex.getAbsolutePath()); return ClassHierarchyFactory.make(dalvikScope); } }
4,792
36.740157
98
java
WALA
WALA-master/ide/jdt/src/main/java/com/ibm/wala/cast/java/client/JDTJavaSourceAnalysisEngine.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. * * WALA JDT Frontend is Copyright (c) 2008 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.cast.java.client; import com.ibm.wala.cast.ir.ssa.AstIRFactory; import com.ibm.wala.cast.java.client.impl.ZeroCFABuilderFactory; import com.ibm.wala.cast.java.ipa.callgraph.JavaSourceAnalysisScope; import com.ibm.wala.cast.java.translator.jdt.JDTClassLoaderFactory; import com.ibm.wala.classLoader.ClassLoaderFactory; import com.ibm.wala.ide.client.EclipseProjectSourceAnalysisEngine; import com.ibm.wala.ide.util.EclipseProjectPath; import com.ibm.wala.ide.util.EclipseProjectPath.AnalysisScopeType; import com.ibm.wala.ide.util.JavaEclipseProjectPath; import com.ibm.wala.ide.util.JdtUtil; 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.CallGraphBuilder; import com.ibm.wala.ipa.callgraph.IAnalysisCacheView; import com.ibm.wala.ipa.callgraph.propagation.InstanceKey; import com.ibm.wala.ipa.cha.IClassHierarchy; import com.ibm.wala.types.ClassLoaderReference; import com.ibm.wala.util.config.SetOfClasses; import java.io.IOException; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.NullProgressMonitor; import org.eclipse.jdt.core.IJavaProject; public class JDTJavaSourceAnalysisEngine extends EclipseProjectSourceAnalysisEngine<IJavaProject, InstanceKey> { private boolean dump; public JDTJavaSourceAnalysisEngine(IJavaProject project) { super(project); } public JDTJavaSourceAnalysisEngine(String projectName) { this(JdtUtil.getNamedProject(projectName)); } public void setDump(boolean dump) { this.dump = dump; } @Override protected ClassLoaderFactory makeClassLoaderFactory(SetOfClasses exclusions) { return new JDTClassLoaderFactory(exclusions, dump); } @Override protected AnalysisScope makeAnalysisScope() { return new JavaSourceAnalysisScope(); } @Override protected ClassLoaderReference getSourceLoader() { return JavaSourceAnalysisScope.SOURCE; } @Override public IAnalysisCacheView makeDefaultCache() { return new AnalysisCacheImpl(AstIRFactory.makeDefaultFactory()); } @Override protected EclipseProjectPath<?, IJavaProject> createProjectPath(IJavaProject project) throws IOException, CoreException { project.open(new NullProgressMonitor()); return JavaEclipseProjectPath.make(project, AnalysisScopeType.SOURCE_FOR_PROJ_AND_LINKED_PROJS); } @Override protected CallGraphBuilder<InstanceKey> getCallGraphBuilder( IClassHierarchy cha, AnalysisOptions options, IAnalysisCacheView cache) { return new ZeroCFABuilderFactory().make(options, cache, cha); } }
4,586
39.59292
100
java
WALA
WALA-master/ide/jdt/src/main/java/com/ibm/wala/cast/java/translator/jdt/JDTClassLoaderFactory.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. * * WALA JDT Frontend is Copyright (c) 2008 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.cast.java.translator.jdt; import com.ibm.wala.cast.java.ipa.callgraph.JavaSourceAnalysisScope; import com.ibm.wala.cast.java.loader.JavaSourceLoaderImpl; import com.ibm.wala.classLoader.ClassLoaderFactoryImpl; import com.ibm.wala.classLoader.ClassLoaderImpl; import com.ibm.wala.classLoader.IClassLoader; import com.ibm.wala.ipa.callgraph.AnalysisScope; import com.ibm.wala.ipa.cha.IClassHierarchy; import com.ibm.wala.types.ClassLoaderReference; import com.ibm.wala.util.config.SetOfClasses; import java.io.IOException; public class JDTClassLoaderFactory extends ClassLoaderFactoryImpl { protected boolean dump; public JDTClassLoaderFactory(SetOfClasses exclusions) { this(exclusions, false); } public JDTClassLoaderFactory(SetOfClasses exclusions, boolean dump) { super(exclusions); this.dump = dump; } @Override protected IClassLoader makeNewClassLoader( ClassLoaderReference classLoaderReference, IClassHierarchy cha, IClassLoader parent, AnalysisScope scope) throws IOException { if (classLoaderReference.equals(JavaSourceAnalysisScope.SOURCE)) { ClassLoaderImpl cl = makeSourceLoader(classLoaderReference, cha, parent); cl.init(scope.getModules(classLoaderReference)); return cl; } else { return super.makeNewClassLoader(classLoaderReference, cha, parent, scope); } } protected JavaSourceLoaderImpl makeSourceLoader( ClassLoaderReference classLoaderReference, IClassHierarchy cha, IClassLoader parent) { return new JDTSourceLoaderImpl(classLoaderReference, parent, cha, dump); } }
3,532
41.059524
92
java
WALA
WALA-master/ide/jdt/src/main/java/com/ibm/wala/cast/java/translator/jdt/JDTSourceLoaderImpl.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. * * WALA JDT Frontend is Copyright (c) 2008 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.cast.java.translator.jdt; import com.ibm.wala.cast.java.loader.JavaSourceLoaderImpl; import com.ibm.wala.cast.java.translator.SourceModuleTranslator; import com.ibm.wala.classLoader.IClassLoader; import com.ibm.wala.ipa.cha.IClassHierarchy; import com.ibm.wala.types.ClassLoaderReference; public class JDTSourceLoaderImpl extends JavaSourceLoaderImpl { private final boolean dump; public JDTSourceLoaderImpl( ClassLoaderReference loaderRef, IClassLoader parent, IClassHierarchy cha) { this(loaderRef, parent, cha, false); } public JDTSourceLoaderImpl( ClassLoaderReference loaderRef, IClassLoader parent, IClassHierarchy cha, boolean dump) { super(loaderRef, parent, cha); this.dump = dump; } @Override protected SourceModuleTranslator getTranslator() { return new JDTSourceModuleTranslator(cha.getScope(), this, dump); } }
2,804
42.153846
95
java
WALA
WALA-master/ide/jdt/src/main/java/com/ibm/wala/cast/java/translator/jdt/JDTSourceModuleTranslator.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. * * WALA JDT Frontend is Copyright (c) 2008 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.cast.java.translator.jdt; import com.ibm.wala.cast.java.translator.Java2IRTranslator; import com.ibm.wala.cast.java.translator.SourceModuleTranslator; import com.ibm.wala.classLoader.DirectoryTreeModule; import com.ibm.wala.classLoader.JarFileModule; import com.ibm.wala.classLoader.Module; import com.ibm.wala.classLoader.ModuleEntry; import com.ibm.wala.ide.classloader.EclipseSourceFileModule; import com.ibm.wala.ide.util.JdtPosition; import com.ibm.wala.ipa.callgraph.AnalysisScope; import com.ibm.wala.types.ClassLoaderReference; import com.ibm.wala.util.config.SetOfClasses; import com.ibm.wala.util.debug.Assertions; import java.io.File; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IProject; import org.eclipse.jdt.core.ICompilationUnit; import org.eclipse.jdt.core.JavaCore; import org.eclipse.jdt.core.JavaModelException; import org.eclipse.jdt.core.compiler.IProblem; import org.eclipse.jdt.core.dom.AST; import org.eclipse.jdt.core.dom.ASTParser; import org.eclipse.jdt.core.dom.ASTRequestor; import org.eclipse.jdt.core.dom.CompilationUnit; /** * A SourceModuleTranslator whose implementation of loadAllSources() uses the PolyglotFrontEnd * pseudo-compiler to generate DOMO IR for the sources in the compile-time classpath. * * @author rfuhrer */ // remove me comment: Jdt little-case = not OK, upper case = OK public class JDTSourceModuleTranslator implements SourceModuleTranslator { private final class JdtAstToIR extends ASTRequestor { private final Entry<IProject, Map<ICompilationUnit, EclipseSourceFileModule>> proj; private JdtAstToIR(Entry<IProject, Map<ICompilationUnit, EclipseSourceFileModule>> proj) { this.proj = proj; } @Override public void acceptAST(ICompilationUnit source, CompilationUnit ast) { try { JDTJava2CAstTranslator<JdtPosition> jdt2cast = makeCAstTranslator( ast, proj.getValue().get(source).getIFile(), source.getUnderlyingResource().getLocation().toOSString()); final Java2IRTranslator java2ir = makeIRTranslator(); java2ir.translate(proj.getValue().get(source), jdt2cast.translateToCAst()); } catch (JavaModelException e) { e.printStackTrace(); } if (!"true".equals(System.getProperty("wala.jdt.quiet"))) { IProblem[] problems = ast.getProblems(); int length = problems.length; if (length > 0) { StringBuilder buffer = new StringBuilder(); for (IProblem problem : problems) { buffer.append(problem.getMessage()); buffer.append('\n'); } if (length != 0) System.err.println("Unexpected problems in " + source.getElementName() + buffer); } } } } protected boolean dump; protected JDTSourceLoaderImpl sourceLoader; private final SetOfClasses exclusions; public JDTSourceModuleTranslator(AnalysisScope scope, JDTSourceLoaderImpl sourceLoader) { this(scope, sourceLoader, false); } public JDTSourceModuleTranslator( AnalysisScope scope, JDTSourceLoaderImpl sourceLoader, boolean dump) { computeClassPath(scope); this.sourceLoader = sourceLoader; this.dump = dump; this.exclusions = scope.getExclusions(); } private static void computeClassPath(AnalysisScope scope) { StringBuilder buf = new StringBuilder(); ClassLoaderReference cl = scope.getApplicationLoader(); while (cl != null) { List<Module> modules = scope.getModules(cl); for (Module m : modules) { if (buf.length() > 0) buf.append(File.pathSeparator); if (m instanceof JarFileModule) { JarFileModule jarFileModule = (JarFileModule) m; buf.append(jarFileModule.getAbsolutePath()); } else if (m instanceof DirectoryTreeModule) { DirectoryTreeModule directoryTreeModule = (DirectoryTreeModule) m; buf.append(directoryTreeModule.getPath()); } else Assertions.UNREACHABLE("Module entry is neither jar file nor directory"); } cl = cl.getParent(); } } /* * Project -> AST code from org.eclipse.jdt.core.tests.performance */ @Override public void loadAllSources(Set<ModuleEntry> modules) { // TODO: we might need one AST (-> "Object" class) for all files. // TODO: group by project and send 'em in // sort files into projects Map<IProject, Map<ICompilationUnit, EclipseSourceFileModule>> projectsFiles = new HashMap<>(); for (ModuleEntry m : modules) { assert m instanceof EclipseSourceFileModule : "Expecing EclipseSourceFileModule, not " + m.getClass(); EclipseSourceFileModule entry = (EclipseSourceFileModule) m; IProject proj = entry.getIFile().getProject(); if (!projectsFiles.containsKey(proj)) { projectsFiles.put(proj, new HashMap<>()); } projectsFiles.get(proj).put(JavaCore.createCompilationUnitFrom(entry.getIFile()), entry); } final ASTParser parser = ASTParser.newParser(AST.JLS8); for (final Map.Entry<IProject, Map<ICompilationUnit, EclipseSourceFileModule>> proj : projectsFiles.entrySet()) { parser.setProject(JavaCore.create(proj.getKey())); parser.setResolveBindings(true); Set<ICompilationUnit> units = proj.getValue().keySet(); parser.createASTs( units.toArray(new ICompilationUnit[0]), new String[0], new JdtAstToIR(proj), null); } } protected Java2IRTranslator makeIRTranslator() { return new Java2IRTranslator(sourceLoader, exclusions); } protected JDTJava2CAstTranslator<JdtPosition> makeCAstTranslator( CompilationUnit cu, final IFile sourceFile, String fullPath) { return new JDTJava2CAstTranslator<>(sourceLoader, cu, fullPath, false, dump) { @Override public JdtPosition makePosition(int start, int end) { return new JdtPosition( start, end, this.cu.getLineNumber(start), this.cu.getLineNumber(end), sourceFile, this.fullPath); } }; } }
8,158
37.852381
98
java
WALA
WALA-master/ide/jdt/src/main/java/com/ibm/wala/eclipse/headless/Main.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.eclipse.headless; import com.ibm.wala.ide.util.EclipseProjectPath.AnalysisScopeType; import com.ibm.wala.ide.util.JavaEclipseProjectPath; import com.ibm.wala.ide.util.JdtUtil; import java.util.Collection; import org.eclipse.equinox.app.IApplication; import org.eclipse.equinox.app.IApplicationContext; import org.eclipse.jdt.core.IJavaProject; /** * A dummy main class that runs WALA in a headless Eclipse platform. * * <p>This is for expository purposes, and tests some WALA eclipse functionality. * * @author sjfink */ public class Main implements IApplication { @Override public Object start(IApplicationContext context) throws Exception { Collection<IJavaProject> jp = JdtUtil.getWorkspaceJavaProjects(); for (IJavaProject p : jp) { System.out.println(p); JavaEclipseProjectPath path = JavaEclipseProjectPath.make(p, AnalysisScopeType.SOURCE_FOR_PROJ_AND_LINKED_PROJS); System.out.println("Path: " + path); } return null; } @Override public void stop() {} }
1,415
30.466667
93
java
WALA
WALA-master/ide/jdt/src/main/java/com/ibm/wala/ide/AbstractJavaAnalysisAction.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.ide; import com.ibm.wala.classLoader.Module; import com.ibm.wala.ide.util.EclipseProjectPath; import com.ibm.wala.ide.util.JavaEclipseProjectPath; import com.ibm.wala.ipa.callgraph.AnalysisScope; import com.ibm.wala.types.ClassLoaderReference; import com.ibm.wala.util.collections.HashSetFactory; import com.ibm.wala.util.collections.Iterator2Iterable; import com.ibm.wala.util.debug.Assertions; import java.io.File; import java.io.IOException; import java.lang.reflect.InvocationTargetException; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import org.eclipse.core.resources.ResourcesPlugin; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.Status; import org.eclipse.core.runtime.jobs.Job; import org.eclipse.jdt.core.IJavaElement; import org.eclipse.jdt.core.IJavaProject; import org.eclipse.jface.action.IAction; import org.eclipse.jface.operation.IRunnableWithProgress; import org.eclipse.jface.viewers.ISelection; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.ui.IActionDelegate; import org.eclipse.ui.IObjectActionDelegate; import org.eclipse.ui.IWorkbenchPart; import org.eclipse.ui.PlatformUI; import org.eclipse.ui.progress.IProgressService; /** An Eclipse action that analyzes a Java selection */ public abstract class AbstractJavaAnalysisAction implements IObjectActionDelegate, IRunnableWithProgress { /** The current {@link ISelection} highlighted in the Eclipse workspace */ private ISelection currentSelection; public AbstractJavaAnalysisAction() { super(); } @Override public void setActivePart(IAction action, IWorkbenchPart targetPart) {} /** Compute an analysis scope for the current selection */ public static AnalysisScope computeScope(IStructuredSelection selection) throws IOException { return computeScope(selection, EclipseProjectPath.AnalysisScopeType.NO_SOURCE); } /** * Compute an analysis scope for the current selection * * @param scopeType should analysis use the source files in the Eclipse projects rather than the * class files. */ public static AnalysisScope computeScope( final IStructuredSelection selection, final EclipseProjectPath.AnalysisScopeType scopeType) throws IOException { if (selection == null) { throw new IllegalArgumentException("null selection"); } final Collection<EclipseProjectPath<?, ?>> projectPaths = new ArrayList<>(); Job job = new Job("Compute project paths") { @Override protected IStatus run(IProgressMonitor monitor) { for (Object object : Iterator2Iterable.make((Iterator<?>) selection.iterator())) { if (object instanceof IJavaElement) { IJavaElement e = (IJavaElement) object; IJavaProject jp = e.getJavaProject(); try { projectPaths.add(JavaEclipseProjectPath.make(jp, scopeType)); } catch (CoreException e1) { e1.printStackTrace(); // skip and continue } catch (IOException e2) { e2.printStackTrace(); return new Status(IStatus.ERROR, "", 0, "", e2); } } else { Assertions.UNREACHABLE(object.getClass()); } } return Status.OK_STATUS; } }; // lock the whole workspace job.setRule(ResourcesPlugin.getWorkspace().getRoot()); job.schedule(); try { job.join(); IStatus result = job.getResult(); if (result.getSeverity() == IStatus.ERROR) { Throwable exception = result.getException(); if (exception instanceof IOException) { throw (IOException) exception; } else if (exception instanceof RuntimeException) { throw (RuntimeException) exception; } } } catch (InterruptedException e) { e.printStackTrace(); assert false; } AnalysisScope scope = mergeProjectPaths(projectPaths); return scope; } /** compute the java projects represented by the current selection */ protected Collection<IJavaProject> computeJavaProjects() { IStructuredSelection selection = (IStructuredSelection) currentSelection; Collection<IJavaProject> projects = HashSetFactory.make(); for (Object object : Iterator2Iterable.make((Iterator<?>) selection.iterator())) { if (object instanceof IJavaElement) { IJavaElement e = (IJavaElement) object; IJavaProject jp = e.getJavaProject(); projects.add(jp); } else { Assertions.UNREACHABLE(object.getClass()); } } return projects; } /** create an analysis scope as the union of a bunch of EclipseProjectPath */ private static AnalysisScope mergeProjectPaths(Collection<EclipseProjectPath<?, ?>> projectPaths) throws IOException { AnalysisScope scope = AnalysisScope.createJavaAnalysisScope(); Collection<Module> seen = HashSetFactory.make(); // to avoid duplicates, we first add all application modules, then // extension // modules, then primordial buildScope(ClassLoaderReference.Application, projectPaths, scope, seen); buildScope(ClassLoaderReference.Extension, projectPaths, scope, seen); buildScope(ClassLoaderReference.Primordial, projectPaths, scope, seen); return scope; } /** * Enhance an {@link AnalysisScope} to include in a particular loader, elements from a set of * Eclipse projects * * @param loader the class loader in which new {@link Module}s will live * @param projectPaths Eclipse project paths to add to the analysis scope * @param scope the {@link AnalysisScope} under construction. This will be mutated. * @param seen set of {@link Module}s which have already been seen, and should not be added to the * analysis scope */ private static void buildScope( ClassLoaderReference loader, Collection<EclipseProjectPath<?, ?>> projectPaths, AnalysisScope scope, Collection<Module> seen) throws IOException { for (EclipseProjectPath<?, ?> path : projectPaths) { AnalysisScope pScope = path.toAnalysisScope((File) null); for (Module m : pScope.getModules(loader)) { if (!seen.contains(m)) { seen.add(m); scope.addToScope(loader, m); } } } } /** @see IActionDelegate#run(IAction) */ @Override public void run(IAction action) { IProgressService progressService = PlatformUI.getWorkbench().getProgressService(); try { progressService.busyCursorWhile(this); } catch (InvocationTargetException | InterruptedException e) { e.printStackTrace(); } } /** @see IActionDelegate#selectionChanged(IAction, ISelection) */ @Override public void selectionChanged(IAction action, ISelection selection) { currentSelection = selection; } /** @return The current {@link ISelection} highlighted in the Eclipse workspace */ public ISelection getCurrentSelection() { return currentSelection; } }
7,611
36.313725
100
java
WALA
WALA-master/ide/jdt/src/main/java/com/ibm/wala/ide/jdt/Activator.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.ide.jdt; import org.eclipse.ui.plugin.AbstractUIPlugin; import org.osgi.framework.BundleContext; /** The activator class controls the plug-in life cycle */ public class Activator extends AbstractUIPlugin { // The plug-in ID public static final String PLUGIN_ID = "com.ibm.wala.ide.jdt"; // $NON-NLS-1$ // The shared instance private static Activator plugin; /** The constructor */ public Activator() {} /* * (non-Javadoc) * @see org.eclipse.ui.plugin.AbstractUIPlugin#start(org.osgi.framework.BundleContext) */ @Override public void start(BundleContext context) throws Exception { super.start(context); plugin = this; } /* * (non-Javadoc) * @see org.eclipse.ui.plugin.AbstractUIPlugin#stop(org.osgi.framework.BundleContext) */ @Override public void stop(BundleContext context) throws Exception { plugin = null; super.stop(context); } /** * Returns the shared instance * * @return the shared instance */ public static Activator getDefault() { return plugin; } }
1,442
24.315789
88
java
WALA
WALA-master/ide/jdt/src/main/java/com/ibm/wala/ide/util/ASTNodeFinder.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.ide.util; import static com.ibm.wala.ide.util.JdtUtil.getAST; import static com.ibm.wala.ide.util.JdtUtil.getOriginalNode; import com.ibm.wala.util.collections.HashMapFactory; import java.lang.ref.SoftReference; import java.util.Map; import org.eclipse.core.resources.IFile; import org.eclipse.jdt.core.dom.ASTNode; public class ASTNodeFinder { private final Map<IFile, SoftReference<ASTNode>> fileASTs = HashMapFactory.make(); public ASTNode getASTNode(JdtPosition pos) { IFile sourceFile = pos.getEclipseFile(); if (!fileASTs.containsKey(sourceFile) || fileASTs.get(sourceFile).get() == null) { fileASTs.put(sourceFile, new SoftReference<>(getAST(sourceFile))); } return getOriginalNode(fileASTs.get(sourceFile).get(), pos); } }
1,154
32
86
java
WALA
WALA-master/ide/jdt/src/main/java/com/ibm/wala/ide/util/JavaEclipseProjectPath.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.ide.util; import com.ibm.wala.cast.java.ipa.callgraph.JavaSourceAnalysisScope; import com.ibm.wala.classLoader.BinaryDirectoryTreeModule; import com.ibm.wala.classLoader.Module; import com.ibm.wala.types.ClassLoaderReference; import com.ibm.wala.util.collections.MapUtil; import com.ibm.wala.util.debug.Assertions; import java.io.File; import java.io.IOException; import java.util.Arrays; import java.util.List; import org.eclipse.core.resources.IProject; import org.eclipse.core.runtime.CoreException; import org.eclipse.jdt.core.IClasspathContainer; import org.eclipse.jdt.core.IClasspathEntry; import org.eclipse.jdt.core.IJavaProject; import org.eclipse.jdt.core.JavaCore; import org.eclipse.jdt.core.JavaModelException; public class JavaEclipseProjectPath extends EclipseProjectPath<IClasspathEntry, IJavaProject> { public enum JavaSourceLoader implements ILoader { SOURCE(JavaSourceAnalysisScope.SOURCE); private final ClassLoaderReference ref; JavaSourceLoader(ClassLoaderReference ref) { this.ref = ref; } @Override public ClassLoaderReference ref() { return ref; } } protected JavaEclipseProjectPath( com.ibm.wala.ide.util.EclipseProjectPath.AnalysisScopeType scopeType) { super(scopeType); } public static JavaEclipseProjectPath make(IJavaProject p, AnalysisScopeType scopeType) throws IOException, CoreException { JavaEclipseProjectPath path = new JavaEclipseProjectPath(scopeType); path.create(p.getProject()); return path; } @Override protected IJavaProject makeProject(IProject p) { try { if (p.hasNature(JavaCore.NATURE_ID)) { return JavaCore.create(p); } } catch (CoreException e) { // not a Java project } return null; } @Override protected IClasspathEntry resolve(IClasspathEntry entry) { return JavaCore.getResolvedClasspathEntry(entry); } @Override protected void resolveClasspathEntry( IJavaProject project, IClasspathEntry entry, ILoader loader, boolean includeSource, boolean cpeFromMainProject) { entry = JavaCore.getResolvedClasspathEntry(entry); final int entryKind = entry.getEntryKind(); switch (entryKind) { case IClasspathEntry.CPE_SOURCE: { resolveSourcePathEntry( includeSource ? JavaSourceLoader.SOURCE : Loader.APPLICATION, includeSource, cpeFromMainProject, entry.getPath(), entry.getOutputLocation(), entry.getExclusionPatterns(), "java"); break; } case IClasspathEntry.CPE_LIBRARY: { resolveLibraryPathEntry(loader, entry.getPath()); break; } case IClasspathEntry.CPE_PROJECT: { resolveProjectPathEntry(includeSource, entry.getPath()); break; } case IClasspathEntry.CPE_CONTAINER: { try { IClasspathContainer cont = JavaCore.getClasspathContainer(entry.getPath(), project); IClasspathEntry[] entries = cont.getClasspathEntries(); resolveClasspathEntries( project, Arrays.asList(entries), cont.getKind() == IClasspathContainer.K_APPLICATION ? loader : Loader.PRIMORDIAL, includeSource, false); } catch (CoreException e) { System.err.println(e); Assertions.UNREACHABLE(); } break; } default: throw new UnsupportedOperationException( String.format("unexpected classpath entry kind %s", entryKind)); } } @Override protected void resolveProjectClasspathEntries(IJavaProject project, boolean includeSource) { try { resolveClasspathEntries( project, Arrays.asList(project.getRawClasspath()), Loader.EXTENSION, includeSource, true); File output = makeAbsolute(project.getOutputLocation()).toFile(); if (!includeSource) { if (output.exists()) { List<Module> s = MapUtil.findOrCreateList(modules, Loader.APPLICATION); s.add(new BinaryDirectoryTreeModule(output)); } } } catch (JavaModelException e) { e.printStackTrace(); Assertions.UNREACHABLE(); } } }
4,724
30.5
100
java
WALA
WALA-master/ide/jdt/src/main/java/com/ibm/wala/ide/util/JdtPosition.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.ide.util; import com.ibm.wala.cast.tree.CAstSourcePositionMap.Position; import com.ibm.wala.classLoader.IMethod.SourcePosition; import com.ibm.wala.util.debug.Assertions; import java.io.IOException; import java.io.Reader; import java.net.MalformedURLException; import java.net.URL; import org.eclipse.core.resources.IFile; public final class JdtPosition implements Position { private final int firstOffset; private final int lastOffset; private final int firstLine, lastLine; private final String path; private final IFile eclipseFile; public JdtPosition( int start, int end, int startLine, int endLine, IFile eclipseFile, String path) { firstOffset = start; lastOffset = end; firstLine = startLine; lastLine = endLine; this.path = path; this.eclipseFile = eclipseFile; } @Override public int getFirstCol() { return -1; } @Override public int getFirstLine() { return firstLine; } @Override public Reader getReader() throws IOException { return null; } @Override public int getLastCol() { return -1; } @Override public int getLastLine() { return lastLine; } @Override public URL getURL() { try { return new URL("file:" + path); } catch (MalformedURLException e) { Assertions.UNREACHABLE(e.toString()); return null; } } @Override public int compareTo(SourcePosition arg0) { if (arg0 instanceof JdtPosition) { if (firstOffset != ((JdtPosition) arg0).firstOffset) { return firstOffset - ((JdtPosition) arg0).firstOffset; } else if (lastOffset != ((JdtPosition) arg0).lastOffset) { return lastOffset - ((JdtPosition) arg0).lastOffset; } } return 0; } @Override public int getFirstOffset() { return firstOffset; } @Override public int getLastOffset() { return lastOffset; } @Override public String toString() { return "[offset " + firstOffset + ':' + lastOffset + ']'; } public IFile getEclipseFile() { return eclipseFile; } @Override public boolean equals(Object obj) { if (obj instanceof JdtPosition) { JdtPosition jp = (JdtPosition) obj; return jp.getEclipseFile().equals(eclipseFile) && jp.getFirstOffset() == firstOffset && jp.getLastOffset() == lastOffset; } else { return false; } } @Override public int hashCode() { return firstOffset + 12432 * lastOffset; } }
2,859
21.519685
87
java
WALA
WALA-master/ide/jdt/src/main/java/com/ibm/wala/ide/util/JdtUtil.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.ide.util; import com.ibm.wala.types.TypeReference; import com.ibm.wala.util.collections.HashSetFactory; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Iterator; import java.util.List; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IProject; import org.eclipse.core.resources.IResource; import org.eclipse.core.resources.IWorkspaceRoot; import org.eclipse.core.resources.ResourcesPlugin; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IPath; import org.eclipse.core.runtime.NullProgressMonitor; import org.eclipse.jdt.core.ICompilationUnit; import org.eclipse.jdt.core.IJavaElement; import org.eclipse.jdt.core.IJavaModel; import org.eclipse.jdt.core.IJavaProject; import org.eclipse.jdt.core.IMethod; import org.eclipse.jdt.core.IPackageDeclaration; import org.eclipse.jdt.core.IType; import org.eclipse.jdt.core.ITypeParameter; import org.eclipse.jdt.core.JavaCore; import org.eclipse.jdt.core.JavaModelException; import org.eclipse.jdt.core.Signature; import org.eclipse.jdt.core.dom.AST; import org.eclipse.jdt.core.dom.ASTNode; import org.eclipse.jdt.core.dom.ASTParser; import org.eclipse.jdt.core.dom.NodeFinder; import org.eclipse.jdt.core.search.IJavaSearchConstants; import org.eclipse.jdt.core.search.IJavaSearchScope; import org.eclipse.jdt.core.search.SearchEngine; import org.eclipse.jdt.core.search.SearchMatch; import org.eclipse.jdt.core.search.SearchParticipant; import org.eclipse.jdt.core.search.SearchPattern; import org.eclipse.jdt.core.search.SearchRequestor; import org.eclipse.jface.viewers.StructuredSelection; /** Convenience methods to get information from JDT {@link IJavaElement} model. */ public class JdtUtil { public static String getFilePath(IJavaElement javaElt) { if (javaElt == null) { throw new IllegalArgumentException("javaElt is null"); } try { IPath p = javaElt.getPath(); if (p == null) { throw new IllegalArgumentException("javaElt has null path"); } String filePath = p.toString(); return filePath; } catch (Exception e) { throw new IllegalArgumentException("malformed javaElt: " + javaElt, e); } } public static String getPackageName(ICompilationUnit cu) { if (cu == null) { throw new IllegalArgumentException("cu is null"); } try { IPackageDeclaration[] pkgDecl = cu.getPackageDeclarations(); // TODO: handle default package? if (pkgDecl != null && pkgDecl.length > 0) { String packageName = pkgDecl[0].getElementName(); return packageName; } } catch (JavaModelException e) { } return ""; } public static String getFullyQualifiedClassName(IType type) { if (type == null) { throw new IllegalArgumentException("type is null"); } ICompilationUnit cu = (ICompilationUnit) type.getParent(); String packageName = getPackageName(cu); String className = type.getElementName(); String fullyQName = packageName + '.' + className; return fullyQName; } public static String getClassName(IType type) { if (type == null) { throw new IllegalArgumentException("type is null"); } String className = type.getElementName(); return className; } /** * Return a unique string representing the specified Java element across projects in the * workspace. The returned string can be used as a handle to create JavaElement by * 'JavaCore.create(String)' * * <p>For example, suppose we have the method 'fooPackage.barPackage.FooClass.fooMethod(int)' * which is in the 'FooProject' and source folder 'src' the handle would be * '=FooProject/src&lt;fooPackage.barPackage{FooClass.java[FooClass~fooMethod~I' * * @throws IllegalArgumentException if javaElt is null */ public static String getJdtHandleString(IJavaElement javaElt) { if (javaElt == null) { throw new IllegalArgumentException("javaElt is null"); } return javaElt.getHandleIdentifier(); } @Deprecated public static IJavaElement createJavaElementFromJdtHandle(String jdtHandle) { return JavaCore.create(jdtHandle); } public static IType[] getClasses(ICompilationUnit cu) { if (cu == null) { throw new IllegalArgumentException("cu is null"); } try { return cu.getAllTypes(); } catch (JavaModelException e) { } return null; } public static IJavaProject getProject(IJavaElement javaElt) { if (javaElt == null) { throw new IllegalArgumentException("javaElt is null"); } IJavaProject javaProject = javaElt.getJavaProject(); return javaProject; } public static String getProjectName(IJavaProject javaProject) { if (javaProject == null) { throw new IllegalArgumentException("javaProject is null"); } return javaProject.getElementName(); } /** * @param typeSignature Some of the type signatures examples are "QString;" (String) and "I" (int) * The type signatures may be either unresolved (for source types) or resolved (for binary * types), and either basic (for basic types) or rich (for parameterized types). See {@link * Signature} for details. */ public static String getHumanReadableType(String typeSignature) { String simpleName = Signature.getSignatureSimpleName(typeSignature); return simpleName; } public static IJavaProject getJavaProject(IFile appJar) { if (appJar == null) { throw new IllegalArgumentException("appJar is null"); } String projectName = appJar.getProject().getName(); return getJavaProject(projectName); } public static IJavaProject getJavaProject(String projectName) { if (projectName == null) { throw new IllegalArgumentException("null projectName"); } IWorkspaceRoot workspaceRoot = ResourcesPlugin.getWorkspace().getRoot(); IJavaModel javaModel = JavaCore.create(workspaceRoot); IJavaProject javaProject = javaModel.getJavaProject(projectName); return javaProject; } /** compute the java projects in the active workspace */ public static Collection<IJavaProject> getWorkspaceJavaProjects() { Collection<IJavaProject> result = HashSetFactory.make(); IWorkspaceRoot workspaceRoot = ResourcesPlugin.getWorkspace().getRoot(); for (IProject p : workspaceRoot.getProjects()) { try { if (p.hasNature(JavaCore.NATURE_ID)) { IJavaProject jp = JavaCore.create(p); if (jp != null) { result.add(jp); } } } catch (CoreException e) { // do nothing } } return result; } /** * Find the {@link IType} in the workspace corresponding to a class name. * * @return null if not found * @throws IllegalArgumentException if projects == null */ public static IType findJavaClassInProjects( String fullyQualifiedName, Collection<IJavaProject> projects) throws IllegalArgumentException { if (projects == null) { throw new IllegalArgumentException("projects == null"); } for (IJavaProject project : projects) { try { IType t = project.findType(fullyQualifiedName); if (t != null) { return t; } } catch (JavaModelException e) { e.printStackTrace(); } } System.err.println("failed to find " + fullyQualifiedName); return null; // IJavaElement[] arr = new IJavaElement[projects.size()]; // projects.toArray(arr); // IJavaSearchScope scope = SearchEngine.createJavaSearchScope(arr, false); // // return searchForJavaClass(className, scope); } public static IType findJavaClassInResources(String className, Collection<IResource> resources) { if (resources == null) { throw new IllegalArgumentException("null resources"); } Collection<IJavaProject> projects = HashSetFactory.make(); for (IResource r : resources) { projects.add(JavaCore.create(r).getJavaProject()); } return findJavaClassInProjects(className, projects); } // private static IType searchForJavaClass(String className, IJavaSearchScope scope) { // SearchPattern p = SearchPattern.createPattern(className, // IJavaSearchConstants.CLASS_AND_INTERFACE, // IJavaSearchConstants.DECLARATIONS, SearchPattern.R_EXACT_MATCH); // SearchEngine engine = new SearchEngine(); // final Collection<IJavaElement> kludge = HashSetFactory.make(); // SearchRequestor requestor = new SearchRequestor() { // // @Override // public void acceptSearchMatch(SearchMatch match) throws CoreException { // kludge.add((IJavaElement) match.getElement()); // } // // }; // try { // engine.search(p, new SearchParticipant[] { SearchEngine.getDefaultSearchParticipant() }, scope, // requestor, null); // } catch (CoreException e) { // e.printStackTrace(); // } // if (kludge.size() == 1) { // System.err.println("Found " + className); // return (IType) kludge.iterator().next(); // } else { // System.err.println("Failed to find " + className + " " + kludge.size()); // return null; // } // } /** * Find the IMethod in the workspace corresponding to a method selector. * * <p>TODO: this is way too slow. figure out something better. * * @return null if not found */ public static IMethod findJavaMethodInProjects( String klass, String selector, Collection<IJavaProject> projects) { if (klass == null) { throw new IllegalArgumentException("null klass"); } if (projects == null) { throw new IllegalArgumentException("null projects"); } IType type = null; try { type = findJavaClassInProjects(klass, projects); } catch (Throwable t) { return null; } if (type == null) { return null; } String name = parseForName(selector, type); String[] paramTypes = parseForParameterTypes(selector); IMethod m = type.getMethod(name, paramTypes); IMethod[] methods = type.findMethods(m); if (methods != null && methods.length == 1) { return methods[0]; } else { // methods is null. probably got screwed by generics. // i spent 5 hours trying to figure out how to fix this correctly // and failed. implementing a miserable hack instead. // Need to consult a guru to figure out how to do this. try { List<IMethod> matches = new ArrayList<>(); Collection<String> typeParameterNames = getTypeParameterNames(type); METHODS: for (IMethod x : type.getMethods()) { if (x.getElementName().equals(name)) { if (x.getParameterTypes().length == paramTypes.length) { for (int i = 0; i < x.getParameterTypes().length; i++) { String s1 = Signature.getTypeErasure( Signature.getSignatureSimpleName(x.getParameterTypes()[i])); String s2 = Signature.getTypeErasure(Signature.getSignatureSimpleName(paramTypes[i])); if (typeParameterNames.contains(s1)) { // s1 is a type parameter to the class. optimistically assume // the types match. } else { if (!s1.equals(s2)) { // no match continue METHODS; } } } matches.add(x); } } } if (matches.size() == 1) { return matches.get(0); } else { System.err.println("findJavaMethodInWorkspace FAILED TO MATCH " + m); return null; } } catch (JavaModelException e) { e.printStackTrace(); return null; } } } public static Collection<String> getTypeParameterNames(IType type) throws IllegalArgumentException, JavaModelException { if (type == null) { throw new IllegalArgumentException("type == null"); } ITypeParameter[] tp = type.getTypeParameters(); Collection<String> typeParameterNames = HashSetFactory.make(tp.length); for (ITypeParameter p : tp) { typeParameterNames.add(p.getElementName()); } return typeParameterNames; } public static String parseForName(String selector, IType type) { if (selector == null) { throw new IllegalArgumentException("selector is null"); } try { String result = selector.substring(0, selector.indexOf('(')); if (result.equals("<init>")) { return type.getElementName(); } else { return result; } } catch (StringIndexOutOfBoundsException e) { throw new IllegalArgumentException("invalid selector: " + selector, e); } } public static final String[] parseForParameterTypes(String selector) throws IllegalArgumentException { try { if (selector == null) { throw new IllegalArgumentException("selector is null"); } String d = selector.substring(selector.indexOf('(')); if (d.length() <= 2) { throw new IllegalArgumentException("invalid descriptor: " + d); } if (d.charAt(0) != '(') { throw new IllegalArgumentException("invalid descriptor: " + d); } ArrayList<String> sigs = new ArrayList<>(10); int i = 1; while (true) { switch (d.charAt(i++)) { case TypeReference.VoidTypeCode: sigs.add(TypeReference.VoidName.toString()); continue; case TypeReference.BooleanTypeCode: sigs.add(TypeReference.BooleanName.toString()); continue; case TypeReference.ByteTypeCode: sigs.add(TypeReference.ByteName.toString()); continue; case TypeReference.ShortTypeCode: sigs.add(TypeReference.ShortName.toString()); continue; case TypeReference.IntTypeCode: sigs.add(TypeReference.IntName.toString()); continue; case TypeReference.LongTypeCode: sigs.add(TypeReference.LongName.toString()); continue; case TypeReference.FloatTypeCode: sigs.add(TypeReference.FloatName.toString()); continue; case TypeReference.DoubleTypeCode: sigs.add(TypeReference.DoubleName.toString()); continue; case TypeReference.CharTypeCode: sigs.add(TypeReference.CharName.toString()); continue; case TypeReference.ArrayTypeCode: { int off = i - 1; while (d.charAt(i) == TypeReference.ArrayTypeCode) { ++i; } if (d.charAt(i++) == TypeReference.ClassTypeCode) { while (d.charAt(i++) != ';') ; sigs.add(d.substring(off, i).replaceAll("/", ".")); } else { sigs.add(d.substring(off, i)); } continue; } case (byte) ')': // end of parameter list return toArray(sigs); default: { // a class int off = i - 1; char c; do { c = d.charAt(i++); } while (c != ',' && c != ')'); sigs.add('L' + d.substring(off, i - 1) + ';'); if (c == ')') { return toArray(sigs); } continue; } } } } catch (StringIndexOutOfBoundsException e) { throw new IllegalArgumentException("error parsing selector " + selector, e); } } private static String[] toArray(ArrayList<String> sigs) { int size = sigs.size(); if (size == 0) { return new String[0]; } Iterator<String> it = sigs.iterator(); String[] result = new String[size]; for (int j = 0; j < size; j++) { result[j] = it.next(); } return result; } /** * Find the IMethod in the workspace corresponding to a method signature. * * <p>This doesn't work for elements declared in inner classes. It's possible this is a 3.2 bug * fixed in 3.3 * * @return null if not found */ @Deprecated public static IMethod findJavaMethodInWorkspaceBrokenForInnerClasses(String methodSig) { // dammit ... this doesn't work for inner classes. System.err.println("Search for " + methodSig); SearchPattern p = SearchPattern.createPattern( methodSig, IJavaSearchConstants.METHOD, IJavaSearchConstants.DECLARATIONS, SearchPattern.R_EXACT_MATCH); IJavaSearchScope scope = SearchEngine.createWorkspaceScope(); SearchEngine engine = new SearchEngine(); final Collection<IJavaElement> kludge = HashSetFactory.make(); SearchRequestor requestor = new SearchRequestor() { @Override public void acceptSearchMatch(SearchMatch match) throws CoreException { kludge.add((IJavaElement) match.getElement()); } }; try { engine.search( p, new SearchParticipant[] {SearchEngine.getDefaultSearchParticipant()}, scope, requestor, null); } catch (CoreException e) { e.printStackTrace(); } if (kludge.size() == 1) { return (IMethod) kludge.iterator().next(); } else { System.err.println("RETURNED " + kludge.size() + ' ' + kludge); return null; } } /** Use the search engine to find all methods in a java element */ public static Collection<IMethod> findMethods(IJavaElement elt) { if (elt instanceof ICompilationUnit) { Collection<IMethod> result = HashSetFactory.make(); for (IType type : getClasses((ICompilationUnit) elt)) { try { result.addAll(Arrays.asList(type.getMethods())); } catch (JavaModelException e) { e.printStackTrace(); } } return result; } else { final Collection<IMethod> result = HashSetFactory.make(); SearchPattern p = SearchPattern.createPattern( "*", IJavaSearchConstants.METHOD, IJavaSearchConstants.DECLARATIONS, SearchPattern.R_PATTERN_MATCH); SearchPattern p2 = SearchPattern.createPattern( "*", IJavaSearchConstants.CONSTRUCTOR, IJavaSearchConstants.DECLARATIONS, SearchPattern.R_PATTERN_MATCH); IJavaSearchScope scope = SearchEngine.createJavaSearchScope(new IJavaElement[] {elt}, IJavaSearchScope.SOURCES); SearchEngine engine = new SearchEngine(); SearchRequestor requestor = new SearchRequestor() { @Override public void acceptSearchMatch(SearchMatch match) throws CoreException { if (match.getElement() instanceof IMethod) { result.add((IMethod) match.getElement()); } } }; try { engine.search( p, new SearchParticipant[] {SearchEngine.getDefaultSearchParticipant()}, scope, requestor, null); engine.search( p2, new SearchParticipant[] {SearchEngine.getDefaultSearchParticipant()}, scope, requestor, null); } catch (CoreException e) { e.printStackTrace(); } return result; } } /** get a {@link StructuredSelection} corresponding to the named projects */ public static StructuredSelection getStructuredSelectionForProjectNames( Collection<String> projectNames) { if (projectNames == null) { throw new IllegalArgumentException("null projectNames"); } Object[] projects = new Object[projectNames.size()]; int i = 0; for (String projectName : projectNames) { projects[i++] = getJavaProject(projectName); } StructuredSelection selection = new StructuredSelection(projects); return selection; } public static IJavaProject getNamedProject(String projectName) { IWorkspaceRoot workspaceRoot = ResourcesPlugin.getWorkspace().getRoot(); IJavaModel javaModel = JavaCore.create(workspaceRoot); IJavaProject helloWorldProject = javaModel.getJavaProject(projectName); return helloWorldProject; } public static ASTNode getAST(IFile javaSourceFile) { ASTParser parser = ASTParser.newParser(AST.JLS3); parser.setSource(JavaCore.createCompilationUnitFrom(javaSourceFile)); parser.setProject(JavaCore.create(javaSourceFile.getProject())); parser.setResolveBindings(true); return parser.createAST(new NullProgressMonitor()); } public static ASTNode getOriginalNode(JdtPosition pos) { ASTNode root = getAST(pos.getEclipseFile()); return getOriginalNode(root, pos); } public static ASTNode getOriginalNode(ASTNode root, JdtPosition pos) { return NodeFinder.perform( root, pos.getFirstOffset(), pos.getLastOffset() - pos.getFirstOffset()); } }
21,459
33.117647
100
java
WALA
WALA-master/ide/jdt/test/src/test/java/com/ibm/wala/cast/java/jdt/test/Activator.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. * * WALA JDT Frontend is Copyright (c) 2008 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.cast.java.jdt.test; import org.eclipse.core.runtime.Plugin; import org.osgi.framework.BundleContext; /** The activator class controls the plug-in life cycle */ public class Activator extends Plugin { // The plug-in ID public static final String PLUGIN_ID = "com.ibm.wala.cast.java.jdt.test"; // The shared instance private static Activator plugin; /** The constructor */ public Activator() {} /* * (non-Javadoc) * * @see org.eclipse.core.runtime.Plugins#start(org.osgi.framework.BundleContext) */ @Override public void start(BundleContext context) throws Exception { super.start(context); plugin = this; } /* * (non-Javadoc) * * @see org.eclipse.core.runtime.Plugin#stop(org.osgi.framework.BundleContext) */ @Override public void stop(BundleContext context) throws Exception { plugin = null; super.stop(context); } /** * Returns the shared instance * * @return the shared instance */ public static Activator getDefault() { return plugin; } }
2,971
33.55814
82
java
WALA
WALA-master/ide/jdt/test/src/test/java/com/ibm/wala/cast/java/test/JDTJavaTest.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.cast.java.test; import com.ibm.wala.cast.java.client.JDTJavaSourceAnalysisEngine; import com.ibm.wala.cast.java.ipa.callgraph.JavaSourceAnalysisScope; import com.ibm.wala.client.AbstractAnalysisEngine; import com.ibm.wala.core.tests.callGraph.CallGraphTestUtil; import com.ibm.wala.ide.tests.util.EclipseTestUtil.ZippedProjectData; 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.cha.IClassHierarchy; import com.ibm.wala.util.io.TemporaryFile; import java.io.File; import java.io.IOException; import java.util.Collection; import java.util.List; import org.junit.Assert; public abstract class JDTJavaTest extends IRTests { static { System.setProperty("wala.jdt.quiet", "true"); } private final ZippedProjectData project; public JDTJavaTest(ZippedProjectData project) { super(project.projectName); this.project = project; this.dump = Boolean.parseBoolean(System.getProperty("wala.cast.dump", "false")); } @Override protected AbstractAnalysisEngine<InstanceKey, CallGraphBuilder<InstanceKey>, ?> getAnalysisEngine( final String[] mainClassDescriptors, Collection<String> sources, List<String> libs) { return makeAnalysisEngine(mainClassDescriptors, project); } static AbstractAnalysisEngine<InstanceKey, CallGraphBuilder<InstanceKey>, ?> makeAnalysisEngine( final String[] mainClassDescriptors, ZippedProjectData project) { AbstractAnalysisEngine<InstanceKey, CallGraphBuilder<InstanceKey>, ?> engine; engine = new JDTJavaSourceAnalysisEngine(project.projectName) { { setDump(Boolean.parseBoolean(System.getProperty("wala.cast.dump", "false"))); } @Override protected Iterable<Entrypoint> makeDefaultEntrypoints(IClassHierarchy cha) { return Util.makeMainEntrypoints( JavaSourceAnalysisScope.SOURCE, cha, mainClassDescriptors); } }; try { File tf = TemporaryFile.urlToFile( "exclusions.txt", CallGraphTestUtil.class .getClassLoader() .getResource(CallGraphTestUtil.REGRESSION_EXCLUSIONS)); engine.setExclusionsFile(tf.getAbsolutePath()); tf.deleteOnExit(); } catch (IOException e) { Assert.fail("Cannot find exclusions file: " + e); } return engine; } }
2,908
34.47561
100
java
WALA
WALA-master/ide/jdt/test/src/test/java/com/ibm/wala/cast/java/test/TestPlugin.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.cast.java.test; import org.eclipse.core.runtime.Plugin; import org.osgi.framework.BundleContext; /** The main plugin class to be used in the desktop. */ public class TestPlugin extends Plugin { // The shared instance. private static TestPlugin plugin; /** The constructor. */ public TestPlugin() { plugin = this; } /** This method is called upon plug-in activation */ @Override public void start(BundleContext context) throws Exception { super.start(context); } /** This method is called when the plug-in is stopped */ @Override public void stop(BundleContext context) throws Exception { super.stop(context); plugin = null; } /** Returns the shared instance. */ public static TestPlugin getDefault() { return plugin; } }
1,176
25.155556
72
java
WALA
WALA-master/ide/jdt/test/src/test/java/com/ibm/wala/cast/java/test/TypeInferenceAssertion.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.cast.java.test; import com.ibm.wala.cast.java.analysis.typeInference.AstJavaTypeInference; import com.ibm.wala.cast.java.test.IRTests.IRAssertion; 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.impl.Everywhere; import com.ibm.wala.ipa.cha.IClassHierarchy; import com.ibm.wala.ssa.IR; import com.ibm.wala.ssa.SSAInstruction; import com.ibm.wala.types.MethodReference; import com.ibm.wala.util.collections.Iterator2Iterable; final class TypeInferenceAssertion implements IRAssertion { private final String typeName; public TypeInferenceAssertion(String packageName) { this.typeName = packageName; } // For now just check things in the main method @Override public void check(CallGraph cg) { IR ir = getIR(cg, typeName, "main", "[Ljava/lang/String;", "V"); AstJavaTypeInference inference = new AstJavaTypeInference(ir, true); for (SSAInstruction instr : Iterator2Iterable.make(ir.iterateAllInstructions())) { // Check defs for (int def = 0; def < instr.getNumberOfDefs(); def++) { int ssaVariable = instr.getDef(def); inference.getType(ssaVariable); } // Check uses for (int def = 0; def < instr.getNumberOfUses(); def++) { int ssaVariable = instr.getUse(def); inference.getType(ssaVariable); } } } private static IR getIR( CallGraph cg, String fullyQualifiedTypeName, String methodName, String methodParameter, String methodReturnType) { IClassHierarchy classHierarchy = cg.getClassHierarchy(); MethodReference methodRef = IRTests.descriptorToMethodRef( String.format( "Source#%s#%s#(%s)%s", fullyQualifiedTypeName, methodName, methodParameter, methodReturnType), classHierarchy); IMethod method = classHierarchy.resolveMethod(methodRef); CGNode node = cg.getNode(method, Everywhere.EVERYWHERE); return node.getIR(); } }
2,450
33.521127
87
java
WALA
WALA-master/ide/jdt/test/src/test/java/com/ibm/wala/demandpa/driver/DemandCastChecker.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 */ /* * 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. * * <p>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. * * <p>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.driver; import com.ibm.wala.classLoader.Language; import com.ibm.wala.core.tests.callGraph.CallGraphTestUtil; import com.ibm.wala.core.tests.util.TestConstants; import com.ibm.wala.core.util.ProgressMaster; import com.ibm.wala.demandpa.alg.ContextSensitiveStateMachine; import com.ibm.wala.demandpa.alg.DemandRefinementPointsTo; import com.ibm.wala.demandpa.alg.DemandRefinementPointsTo.PointsToResult; import com.ibm.wala.demandpa.alg.refinepolicy.FieldRefinePolicy; import com.ibm.wala.demandpa.alg.refinepolicy.ManualFieldPolicy; import com.ibm.wala.demandpa.alg.refinepolicy.ManualRefinementPolicy; import com.ibm.wala.demandpa.alg.refinepolicy.RefinementPolicyFactory; import com.ibm.wala.demandpa.alg.refinepolicy.TunedRefinementPolicy; import com.ibm.wala.demandpa.alg.statemachine.StateMachineFactory; import com.ibm.wala.demandpa.flowgraph.IFlowLabel; import com.ibm.wala.demandpa.util.MemoryAccessMap; import com.ibm.wala.demandpa.util.SimpleMemoryAccessMap; 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.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.Util; 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.cha.ClassHierarchy; import com.ibm.wala.ipa.cha.ClassHierarchyException; import com.ibm.wala.ipa.cha.ClassHierarchyFactory; import com.ibm.wala.ipa.cha.IClassHierarchy; import com.ibm.wala.properties.WalaProperties; import com.ibm.wala.ssa.IR; import com.ibm.wala.ssa.SSACheckCastInstruction; import com.ibm.wala.ssa.SSAInstruction; import com.ibm.wala.types.ClassLoaderReference; import com.ibm.wala.types.TypeReference; import com.ibm.wala.util.CancelException; import com.ibm.wala.util.MonitorUtil.IProgressMonitor; import com.ibm.wala.util.NullProgressMonitor; import com.ibm.wala.util.WalaException; import com.ibm.wala.util.collections.Pair; import com.ibm.wala.util.debug.Assertions; import java.io.IOException; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Properties; import java.util.function.Predicate; /** * Uses a demand-driven points-to analysis to check the safety of downcasts. * * @author Manu Sridharan */ public class DemandCastChecker { // maximum number of casts to check private static final int MAX_CASTS = Integer.MAX_VALUE; public static void main(String[] args) throws IllegalArgumentException, CancelException, IOException { try { Properties p = new Properties(); p.putAll(WalaProperties.loadProperties()); } catch (WalaException e) { e.printStackTrace(); Assertions.UNREACHABLE(); } runTestCase(TestConstants.JLEX_MAIN, TestConstants.JLEX, "JLex"); // runTestCase(TestConstants.HELLO_MAIN, TestConstants.HELLO, "Hello"); } public static void runTestCase(String mainClass, String scopeFile, String benchName) throws IllegalArgumentException, CancelException, IOException { System.err.println("=====BENCHMARK " + benchName + "====="); System.err.println("analyzing " + benchName); DemandRefinementPointsTo dmp = null; try { dmp = makeDemandPointerAnalysis(scopeFile, mainClass, benchName); findFailingCasts(dmp.getBaseCallGraph(), dmp); } catch (ClassHierarchyException e) { e.printStackTrace(); } System.err.println("=*=*=*=*=*=*=*=*=*=*=*=*=*=*"); System.err.println(); System.err.println(); } private static DemandRefinementPointsTo makeDemandPointerAnalysis( String scopeFile, String mainClass, String benchName) throws ClassHierarchyException, IllegalArgumentException, CancelException, IOException { AnalysisScope scope = CallGraphTestUtil.makeJ2SEAnalysisScope(scopeFile, getExclusions(benchName)); // build a type hierarchy ClassHierarchy cha = ClassHierarchyFactory.make(scope); // set up call graph construction options; mainly what should be considered // entrypoints? Iterable<Entrypoint> entrypoints = com.ibm.wala.ipa.callgraph.impl.Util.makeMainEntrypoints(cha, mainClass); AnalysisOptions options = CallGraphTestUtil.makeAnalysisOptions(scope, entrypoints); System.err.print("constructing call graph..."); final Pair<CallGraph, PointerAnalysis<InstanceKey>> cgAndPA = buildCallGraph(cha, options); CallGraph cg = cgAndPA.fst; System.err.println("done"); System.err.println(CallGraphStats.getStats(cg)); MemoryAccessMap fam = new SimpleMemoryAccessMap(cg, cgAndPA.snd.getHeapModel(), false); DemandRefinementPointsTo fullDemandPointsTo = DemandRefinementPointsTo.makeWithDefaultFlowGraph( cg, heapModel, fam, cha, options, makeStateMachineFactory()); fullDemandPointsTo.setRefinementPolicyFactory(chooseRefinePolicyFactory(cha)); return fullDemandPointsTo; } private static String getExclusions(@SuppressWarnings("unused") String benchName) { return CallGraphTestUtil.REGRESSION_EXCLUSIONS; } // if true, construct up-front call graph cheaply (0-CFA) private static final boolean CHEAP_CG = true; private static HeapModel heapModel; /** builds a call graph, and sets the corresponding heap model for analysis */ private static Pair<CallGraph, PointerAnalysis<InstanceKey>> buildCallGraph( ClassHierarchy cha, AnalysisOptions options) throws IllegalArgumentException, CancelException { CallGraph retCG = null; PointerAnalysis<InstanceKey> retPA = null; final IAnalysisCacheView cache = new AnalysisCacheImpl(); CallGraphBuilder<InstanceKey> builder; if (CHEAP_CG) { builder = Util.makeZeroCFABuilder(Language.JAVA, options, cache, cha); // we want vanilla 0-1 CFA, which has one abstract loc per allocation heapModel = Util.makeVanillaZeroOneCFABuilder(Language.JAVA, options, cache, cha); } else { builder = Util.makeZeroOneContainerCFABuilder(options, cache, cha); heapModel = (HeapModel) builder; } IProgressMonitor master = ProgressMaster.make(new NullProgressMonitor(), 360000, false); master.beginTask("runSolver", 1); try { retCG = builder.makeCallGraph(options, master); retPA = builder.getPointerAnalysis(); } catch (CallGraphBuilderCancelException e) { System.err.println("TIMED OUT!!"); retCG = e.getPartialCallGraph(); retPA = e.getPartialPointerAnalysis(); } return Pair.make(retCG, retPA); } private static RefinementPolicyFactory chooseRefinePolicyFactory(ClassHierarchy cha) { if (true) { return new TunedRefinementPolicy.Factory(cha); } else { return new ManualRefinementPolicy.Factory(cha); } } private static StateMachineFactory<IFlowLabel> makeStateMachineFactory() { return new ContextSensitiveStateMachine.Factory(); } private static List<Pair<CGNode, SSACheckCastInstruction>> findFailingCasts( CallGraph cg, DemandRefinementPointsTo dmp) { final IClassHierarchy cha = dmp.getClassHierarchy(); List<Pair<CGNode, SSACheckCastInstruction>> failing = new ArrayList<>(); int numSafe = 0, numMightFail = 0; outer: for (CGNode node : cg) { TypeReference declaringClass = node.getMethod().getReference().getDeclaringClass(); // skip library classes if (declaringClass.getClassLoader().equals(ClassLoaderReference.Primordial)) { continue; } IR ir = node.getIR(); if (ir == null) continue; SSAInstruction[] instrs = ir.getInstructions(); for (SSAInstruction instr : instrs) { if (numSafe + numMightFail > MAX_CASTS) break outer; SSAInstruction instruction = instr; if (instruction instanceof SSACheckCastInstruction) { SSACheckCastInstruction castInstr = (SSACheckCastInstruction) instruction; final TypeReference[] declaredResultTypes = castInstr.getDeclaredResultTypes(); boolean primOnly = true; for (TypeReference t : declaredResultTypes) { if (!t.isPrimitiveType()) { primOnly = false; break; } } if (primOnly) { continue; } System.err.println("CHECKING " + castInstr + " in " + node.getMethod()); PointerKey castedPk = heapModel.getPointerKeyForLocal(node, castInstr.getUse(0)); Predicate<InstanceKey> castPred = ik -> { TypeReference ikTypeRef = ik.getConcreteType().getReference(); for (TypeReference t : declaredResultTypes) { if (cha.isAssignableFrom(cha.lookupClass(t), cha.lookupClass(ikTypeRef))) { return true; } } return false; }; long startTime = System.currentTimeMillis(); Pair<PointsToResult, Collection<InstanceKey>> queryResult = dmp.getPointsTo(castedPk, castPred); long runningTime = System.currentTimeMillis() - startTime; System.err.println("running time: " + runningTime + "ms"); final FieldRefinePolicy fieldRefinePolicy = dmp.getRefinementPolicy().getFieldRefinePolicy(); switch (queryResult.fst) { case SUCCESS: System.err.println("SAFE: " + castInstr + " in " + node.getMethod()); if (fieldRefinePolicy instanceof ManualFieldPolicy) { ManualFieldPolicy hackedFieldPolicy = (ManualFieldPolicy) fieldRefinePolicy; System.err.println(hackedFieldPolicy.getHistory()); } System.err.println("TRAVERSED " + dmp.getNumNodesTraversed() + " nodes"); numSafe++; break; case NOMOREREFINE: if (queryResult.snd != null) { System.err.println( "MIGHT FAIL: no more refinement possible for " + castInstr + " in " + node.getMethod()); } else { System.err.println( "MIGHT FAIL: exceeded budget for " + castInstr + " in " + node.getMethod()); } failing.add(Pair.make(node, castInstr)); numMightFail++; break; case BUDGETEXCEEDED: System.err.println( "MIGHT FAIL: exceeded budget for " + castInstr + " in " + node.getMethod()); failing.add(Pair.make(node, castInstr)); numMightFail++; break; default: Assertions.UNREACHABLE(); } } } // break outer; } System.err.println("TOTAL SAFE: " + numSafe); System.err.println("TOTAL MIGHT FAIL: " + numMightFail); return failing; } }
13,313
43.086093
100
java
WALA
WALA-master/ide/jsdt/src/main/java/com/ibm/wala/cast/js/client/EclipseJavaScriptAnalysisEngine.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.cast.js.client; import com.ibm.wala.cast.ipa.callgraph.CAstAnalysisScope; import com.ibm.wala.cast.ir.ssa.AstIRFactory; import com.ibm.wala.cast.js.callgraph.fieldbased.FieldBasedCallGraphBuilder; import com.ibm.wala.cast.js.callgraph.fieldbased.FieldBasedCallGraphBuilder.CallGraphResult; import com.ibm.wala.cast.js.callgraph.fieldbased.OptimisticCallgraphBuilder; import com.ibm.wala.cast.js.callgraph.fieldbased.PessimisticCallGraphBuilder; import com.ibm.wala.cast.js.callgraph.fieldbased.flowgraph.FilteredFlowGraphBuilder; import com.ibm.wala.cast.js.callgraph.fieldbased.flowgraph.FlowGraph; import com.ibm.wala.cast.js.callgraph.fieldbased.flowgraph.FlowGraphBuilder; import com.ibm.wala.cast.js.callgraph.fieldbased.flowgraph.vertices.ObjectVertex; import com.ibm.wala.cast.js.client.impl.ZeroCFABuilderFactory; import com.ibm.wala.cast.js.html.IncludedPosition; import com.ibm.wala.cast.js.ipa.callgraph.JSAnalysisOptions; import com.ibm.wala.cast.js.ipa.callgraph.JSCallGraph; import com.ibm.wala.cast.js.ipa.callgraph.JSCallGraphUtil; import com.ibm.wala.cast.js.loader.JavaScriptLoader; import com.ibm.wala.cast.js.loader.JavaScriptLoaderFactory; import com.ibm.wala.cast.js.translator.CAstRhinoTranslatorFactory; import com.ibm.wala.cast.js.types.JavaScriptTypes; import com.ibm.wala.cast.loader.AstMethod; import com.ibm.wala.cast.tree.CAstSourcePositionMap.Position; import com.ibm.wala.classLoader.ClassLoaderFactory; import com.ibm.wala.classLoader.IMethod; import com.ibm.wala.ide.client.EclipseProjectSourceAnalysisEngine; import com.ibm.wala.ide.util.JavaScriptEclipseProjectPath; 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.CallGraphBuilder; import com.ibm.wala.ipa.callgraph.Entrypoint; import com.ibm.wala.ipa.callgraph.IAnalysisCacheView; 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.types.ClassLoaderReference; import com.ibm.wala.util.CancelException; import com.ibm.wala.util.NullProgressMonitor; import com.ibm.wala.util.collections.HashSetFactory; import com.ibm.wala.util.collections.Pair; import com.ibm.wala.util.config.SetOfClasses; import java.io.IOException; import java.util.Collections; import java.util.Set; import java.util.function.Function; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.Plugin; import org.eclipse.wst.jsdt.core.IJavaScriptProject; public class EclipseJavaScriptAnalysisEngine extends EclipseProjectSourceAnalysisEngine<IJavaScriptProject, InstanceKey> { public enum BuilderType { PESSIMISTIC, OPTIMISTIC, REFLECTIVE } private final BuilderType builderType; public EclipseJavaScriptAnalysisEngine(IJavaScriptProject project, BuilderType builderType) { super(project, "js"); this.builderType = builderType; } @Override public AnalysisOptions getDefaultOptions(Iterable<Entrypoint> entrypoints) { return JSCallGraphUtil.makeOptions(getScope(), getClassHierarchy(), entrypoints); } @Override public String getExclusionsFile() { return null; } @Override protected Iterable<Entrypoint> makeDefaultEntrypoints(IClassHierarchy cha) { return JSCallGraphUtil.makeScriptRoots(cha); } @Override protected ClassLoaderFactory makeClassLoaderFactory(SetOfClasses exclusions) { return JSCallGraphUtil.makeLoaders(); } @Override protected AnalysisScope makeAnalysisScope() { return new CAstAnalysisScope( new JavaScriptLoaderFactory(new CAstRhinoTranslatorFactory()), Collections.singleton(JavaScriptLoader.JS)); } @Override protected JavaScriptEclipseProjectPath createProjectPath(IJavaScriptProject project) throws IOException, CoreException { return JavaScriptEclipseProjectPath.make(project, Collections.<Pair<String, Plugin>>emptySet()); } @Override protected ClassLoaderReference getSourceLoader() { return JavaScriptTypes.jsLoader; } @Override public IAnalysisCacheView makeDefaultCache() { return new AnalysisCacheImpl(AstIRFactory.makeDefaultFactory()); } @Override protected CallGraphBuilder<InstanceKey> getCallGraphBuilder( IClassHierarchy cha, AnalysisOptions options, IAnalysisCacheView cache) { return new ZeroCFABuilderFactory().make((JSAnalysisOptions) options, cache, cha); } public Pair<JSCallGraph, PointerAnalysis<ObjectVertex>> getFieldBasedCallGraph() throws CancelException { return getFieldBasedCallGraph(JSCallGraphUtil.makeScriptRoots(getClassHierarchy())); } public Pair<JSCallGraph, PointerAnalysis<ObjectVertex>> getFieldBasedCallGraph(String scriptName) throws CancelException { Set<Entrypoint> eps = HashSetFactory.make(); eps.add(JSCallGraphUtil.makeScriptRoots(getClassHierarchy()).make(scriptName)); eps.add(JSCallGraphUtil.makeScriptRoots(getClassHierarchy()).make("Lprologue.js")); return getFieldBasedCallGraph(eps); } private static String getScriptName(AstMethod m) { // we want the original including file, since that will be the "script" Position p = m.getSourcePosition(); while (p instanceof IncludedPosition) { p = ((IncludedPosition) p).getIncludePosition(); } String fileName = p.getURL().getFile(); return fileName.substring(fileName.lastIndexOf('/') + 1); } protected Pair<JSCallGraph, PointerAnalysis<ObjectVertex>> getFieldBasedCallGraph( Iterable<Entrypoint> roots) throws CancelException { final Set<String> scripts = HashSetFactory.make(); for (Entrypoint e : roots) { String scriptName = getScriptName(((AstMethod) e.getMethod())); scripts.add(scriptName); } final Function<IMethod, Boolean> filter = object -> { if (object instanceof AstMethod) { return scripts.contains(getScriptName((AstMethod) object)); } else { return true; } }; AnalysisOptions options = getDefaultOptions(roots); if (builderType.equals(BuilderType.OPTIMISTIC)) { ((JSAnalysisOptions) options).setHandleCallApply(false); } FieldBasedCallGraphBuilder builder = builderType.equals(BuilderType.PESSIMISTIC) ? new PessimisticCallGraphBuilder( getClassHierarchy(), options, makeDefaultCache(), false) { @Override protected FlowGraph flowGraphFactory() { FlowGraphBuilder b = new FilteredFlowGraphBuilder(cha, cache, true, filter); return b.buildFlowGraph(); } @Override protected boolean filterFunction(IMethod function) { return super.filterFunction(function) && filter.apply(function); } } : new OptimisticCallgraphBuilder( getClassHierarchy(), options, makeDefaultCache(), true) { @Override protected FlowGraph flowGraphFactory() { FlowGraphBuilder b = new FilteredFlowGraphBuilder(cha, cache, true, filter); return b.buildFlowGraph(); } }; CallGraphResult result = builder.buildCallGraph(roots, new NullProgressMonitor()); return Pair.make(result.getCallGraph(), result.getPointerAnalysis()); } }
7,857
38.094527
100
java
WALA
WALA-master/ide/jsdt/src/main/java/com/ibm/wala/cast/js/client/EclipseWebAnalysisEngine.java
package com.ibm.wala.cast.js.client; import com.ibm.wala.cast.ipa.callgraph.CAstAnalysisScope; import com.ibm.wala.cast.js.callgraph.fieldbased.flowgraph.vertices.ObjectVertex; import com.ibm.wala.cast.js.html.WebPageLoaderFactory; import com.ibm.wala.cast.js.ipa.callgraph.JSCallGraph; import com.ibm.wala.cast.js.ipa.callgraph.JSCallGraphUtil; import com.ibm.wala.cast.js.loader.JavaScriptLoader; import com.ibm.wala.cast.js.translator.CAstRhinoTranslatorFactory; import com.ibm.wala.classLoader.ClassLoaderFactory; import com.ibm.wala.ide.jsdt.Activator; import com.ibm.wala.ide.util.EclipseWebProjectPath; import com.ibm.wala.ide.util.JavaScriptEclipseProjectPath; import com.ibm.wala.ipa.callgraph.AnalysisScope; import com.ibm.wala.ipa.callgraph.Entrypoint; import com.ibm.wala.ipa.callgraph.propagation.PointerAnalysis; 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.config.SetOfClasses; import java.io.IOException; import java.util.Collection; import java.util.Collections; import java.util.Set; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.Plugin; import org.eclipse.wst.jsdt.core.IJavaScriptProject; public class EclipseWebAnalysisEngine extends EclipseJavaScriptAnalysisEngine { private final Set<Pair<String, Plugin>> models = HashSetFactory.make(); public EclipseWebAnalysisEngine( IJavaScriptProject project, Collection<Pair<String, Plugin>> models, BuilderType builderType) { super(project, builderType); // core DOM model this.models.add(Pair.make("preamble.js", (Plugin) Activator.getDefault())); this.models.addAll(models); } @Override protected ClassLoaderFactory makeClassLoaderFactory(SetOfClasses exclusions) { return new WebPageLoaderFactory(new CAstRhinoTranslatorFactory()); } @Override protected AnalysisScope makeAnalysisScope() { return new CAstAnalysisScope( new WebPageLoaderFactory(new CAstRhinoTranslatorFactory()), Collections.singleton(JavaScriptLoader.JS)); } @Override protected JavaScriptEclipseProjectPath createProjectPath(IJavaScriptProject project) throws IOException, CoreException { return EclipseWebProjectPath.make(project, models); } @Override public Pair<JSCallGraph, PointerAnalysis<ObjectVertex>> getFieldBasedCallGraph(String scriptName) throws CancelException { Set<Entrypoint> eps = HashSetFactory.make(); eps.add(JSCallGraphUtil.makeScriptRoots(getClassHierarchy()).make(scriptName)); eps.add(JSCallGraphUtil.makeScriptRoots(getClassHierarchy()).make("Lprologue.js")); for (Pair<String, Plugin> model : models) { eps.add(JSCallGraphUtil.makeScriptRoots(getClassHierarchy()).make('L' + model.fst)); } return getFieldBasedCallGraph(eps); } }
2,887
37.506667
99
java
WALA
WALA-master/ide/jsdt/src/main/java/com/ibm/wala/ide/jsdt/Activator.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.ide.jsdt; import org.eclipse.ui.plugin.AbstractUIPlugin; import org.osgi.framework.BundleContext; /** The activator class controls the plug-in life cycle */ public class Activator extends AbstractUIPlugin { // The plug-in ID public static final String PLUGIN_ID = "com.ibm.wala.ide.jsdt"; // $NON-NLS-1$ // The shared instance private static Activator plugin; /** The constructor */ public Activator() {} /* * (non-Javadoc) * @see org.eclipse.ui.plugin.AbstractUIPlugin#start(org.osgi.framework.BundleContext) */ @Override public void start(BundleContext context) throws Exception { super.start(context); plugin = this; } /* * (non-Javadoc) * @see org.eclipse.ui.plugin.AbstractUIPlugin#stop(org.osgi.framework.BundleContext) */ @Override public void stop(BundleContext context) throws Exception { plugin = null; super.stop(context); } /** * Returns the shared instance * * @return the shared instance */ public static Activator getDefault() { return plugin; } }
1,444
24.350877
88
java
WALA
WALA-master/ide/jsdt/src/main/java/com/ibm/wala/ide/util/EclipseWebProjectPath.java
package com.ibm.wala.ide.util; import com.ibm.wala.cast.ir.translator.TranslatorToCAst.Error; import com.ibm.wala.cast.js.html.DefaultSourceExtractor; import com.ibm.wala.cast.js.html.MappedSourceModule; import com.ibm.wala.cast.js.html.WebUtil; import com.ibm.wala.classLoader.FileModule; import com.ibm.wala.classLoader.Module; import com.ibm.wala.ide.classloader.EclipseSourceDirectoryTreeModule; import com.ibm.wala.util.collections.MapUtil; import com.ibm.wala.util.collections.Pair; import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; import java.util.Iterator; import java.util.List; import java.util.Set; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IPath; import org.eclipse.core.runtime.Plugin; import org.eclipse.wst.jsdt.core.IJavaScriptProject; public class EclipseWebProjectPath extends JavaScriptEclipseProjectPath { public EclipseWebProjectPath(Set<Pair<String, Plugin>> models) { super(models); } public static EclipseWebProjectPath make(IJavaScriptProject p, Set<Pair<String, Plugin>> models) throws IOException, CoreException { EclipseWebProjectPath path = new EclipseWebProjectPath(models); path.create(p.getProject()); return path; } @Override protected void resolveSourcePathEntry( com.ibm.wala.ide.util.EclipseProjectPath.ILoader loader, boolean includeSource, boolean cpeFromMainProject, IPath p, IPath o, IPath[] excludePaths, String fileExtension) { List<Module> s = MapUtil.findOrCreateList(modules, loader); Iterator<FileModule> htmlPages = new EclipseSourceDirectoryTreeModule(p, excludePaths, "html").getEntries(); while (htmlPages.hasNext()) { FileModule htmlPage = htmlPages.next(); Set<MappedSourceModule> scripts; String urlString = "file://" + htmlPage.getAbsolutePath(); try { scripts = WebUtil.extractScriptFromHTML(new URL(urlString), DefaultSourceExtractor.factory).fst; s.addAll(scripts); } catch (MalformedURLException e1) { assert false : "internal error constructing URL " + urlString; } catch (Error e1) { System.err.print("skipping " + htmlPage.getAbsolutePath() + ": " + e1.warning); } } } }
2,301
34.96875
98
java
WALA
WALA-master/ide/jsdt/src/main/java/com/ibm/wala/ide/util/JavaScriptEclipseProjectPath.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.ide.util; import com.ibm.wala.cast.js.ipa.callgraph.JSCallGraphUtil; import com.ibm.wala.cast.js.types.JavaScriptTypes; import com.ibm.wala.classLoader.Module; import com.ibm.wala.ide.jsdt.Activator; import com.ibm.wala.types.ClassLoaderReference; import com.ibm.wala.util.collections.HashSetFactory; import com.ibm.wala.util.collections.Pair; import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.util.Arrays; import java.util.Collection; import java.util.Set; import org.eclipse.core.resources.IProject; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.Plugin; import org.eclipse.wst.jsdt.core.IIncludePathEntry; import org.eclipse.wst.jsdt.core.IJavaScriptProject; import org.eclipse.wst.jsdt.core.JavaScriptCore; import org.eclipse.wst.jsdt.core.JavaScriptModelException; public class JavaScriptEclipseProjectPath extends EclipseProjectPath<IIncludePathEntry, IJavaScriptProject> { public enum JSLoader implements ILoader { JAVASCRIPT(JavaScriptTypes.jsLoader); private final ClassLoaderReference ref; JSLoader(ClassLoaderReference ref) { this.ref = ref; } @Override public ClassLoaderReference ref() { return ref; } } private final Set<Pair<String, Plugin>> models = HashSetFactory.make(); protected JavaScriptEclipseProjectPath(Set<Pair<String, Plugin>> models) { super(AnalysisScopeType.SOURCE_FOR_PROJ_AND_LINKED_PROJS); this.models.addAll(models); this.models.add(Pair.make("prologue.js", (Plugin) Activator.getDefault())); } public static JavaScriptEclipseProjectPath make( IJavaScriptProject p, Set<Pair<String, Plugin>> models) throws IOException, CoreException { JavaScriptEclipseProjectPath path = new JavaScriptEclipseProjectPath(models); path.create(p.getProject()); return path; } @Override public EclipseProjectPath<IIncludePathEntry, IJavaScriptProject> create(IProject project) throws CoreException, IOException { EclipseProjectPath<IIncludePathEntry, IJavaScriptProject> path = super.create(project); Collection<Module> s = modules.get(JSLoader.JAVASCRIPT); for (Pair<String, Plugin> model : models) { URL modelFile = JsdtUtil.getPrologueFile(model.fst, model.snd); assert modelFile != null : "cannot find file for " + model; try (InputStream openStream = modelFile.openStream()) { s.add(new JSCallGraphUtil.Bootstrap(model.fst, openStream, modelFile)); } } return path; } @Override protected IJavaScriptProject makeProject(IProject p) { try { if (p.hasNature(JavaScriptCore.NATURE_ID)) { return JavaScriptCore.create(p); } else { return null; } } catch (CoreException e) { return null; } } @Override protected IIncludePathEntry resolve(IIncludePathEntry entry) { return JavaScriptCore.getResolvedIncludepathEntry(entry); } @Override protected void resolveClasspathEntry( IJavaScriptProject project, IIncludePathEntry entry, ILoader loader, boolean includeSource, boolean cpeFromMainProject) { IIncludePathEntry e = JavaScriptCore.getResolvedIncludepathEntry(entry); final int entryKind = e.getEntryKind(); switch (entryKind) { case IIncludePathEntry.CPE_SOURCE: resolveSourcePathEntry( JSLoader.JAVASCRIPT, true, cpeFromMainProject, e.getPath(), null, e.getExclusionPatterns(), "js"); break; default: // do nothing } } @Override protected void resolveProjectClasspathEntries(IJavaScriptProject project, boolean includeSource) { try { resolveClasspathEntries( project, Arrays.asList(project.getRawIncludepath()), Loader.EXTENSION, includeSource, true); } catch (JavaScriptModelException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
4,423
30.15493
100
java
WALA
WALA-master/ide/jsdt/src/main/java/com/ibm/wala/ide/util/JavaScriptHeadlessUtil.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.ide.util; import org.eclipse.core.runtime.CoreException; import org.eclipse.wst.jsdt.core.IJavaScriptProject; import org.eclipse.wst.jsdt.core.JavaScriptCore; public class JavaScriptHeadlessUtil extends HeadlessUtil { public static IJavaScriptProject getJavaScriptProjectFromWorkspace(final String projectName) { IJavaScriptProject jp = getProjectFromWorkspace( p -> { try { if (p.hasNature(JavaScriptCore.NATURE_ID)) { IJavaScriptProject jp1 = JavaScriptCore.create(p); if (jp1 != null && jp1.getElementName().equals(projectName)) { return jp1; } } } catch (CoreException e) { } // failed to match return null; }); return jp; } }
1,243
31.736842
96
java
WALA
WALA-master/ide/jsdt/src/main/java/com/ibm/wala/ide/util/JsdtUtil.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.ide.util; import com.ibm.wala.cast.ipa.callgraph.CAstAnalysisScope; import com.ibm.wala.cast.js.ipa.callgraph.JSCallGraphUtil; import com.ibm.wala.cast.js.loader.JavaScriptLoader; import com.ibm.wala.cast.js.translator.CAstRhinoTranslatorFactory; import com.ibm.wala.cast.js.types.JavaScriptTypes; import com.ibm.wala.classLoader.Module; import com.ibm.wala.classLoader.ModuleEntry; import com.ibm.wala.ide.classloader.EclipseSourceFileModule; import com.ibm.wala.ide.jsdt.Activator; import com.ibm.wala.ide.util.HeadlessUtil.EclipseCompiler; import com.ibm.wala.ide.util.HeadlessUtil.Parser; import com.ibm.wala.ipa.callgraph.AnalysisScope; import com.ibm.wala.util.collections.HashSetFactory; import com.ibm.wala.util.collections.Iterator2Iterable; import com.ibm.wala.util.collections.Pair; import com.ibm.wala.util.graph.Graph; import com.ibm.wala.util.graph.impl.SlowSparseNumberedGraph; import java.io.IOException; import java.net.URL; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Set; import java.util.function.Function; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IProject; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.NullProgressMonitor; import org.eclipse.core.runtime.Plugin; import org.eclipse.wst.jsdt.core.IFunction; import org.eclipse.wst.jsdt.core.IJavaScriptElement; import org.eclipse.wst.jsdt.core.IJavaScriptProject; import org.eclipse.wst.jsdt.core.IJavaScriptUnit; import org.eclipse.wst.jsdt.core.IMember; import org.eclipse.wst.jsdt.core.JavaScriptCore; import org.eclipse.wst.jsdt.core.dom.AST; import org.eclipse.wst.jsdt.core.dom.ASTNode; import org.eclipse.wst.jsdt.core.dom.ASTParser; import org.eclipse.wst.jsdt.core.dom.ASTRequestor; import org.eclipse.wst.jsdt.core.dom.ASTVisitor; import org.eclipse.wst.jsdt.core.dom.FunctionDeclaration; import org.eclipse.wst.jsdt.core.dom.FunctionInvocation; import org.eclipse.wst.jsdt.core.dom.FunctionRef; import org.eclipse.wst.jsdt.core.dom.JavaScriptUnit; import org.eclipse.wst.jsdt.internal.corext.callhierarchy.CallHierarchy; import org.eclipse.wst.jsdt.internal.corext.callhierarchy.MethodWrapper; public class JsdtUtil { public static URL getPrologueFile(String file, Plugin plugin) { plugin = plugin != null ? plugin : Activator.getDefault(); JavaScriptLoader.addBootstrapFile(file); return plugin.getClass().getClassLoader().getResource(file); } private static final boolean useCreateASTs = false; public static class CGInfo { public final Graph<IMember> cg = SlowSparseNumberedGraph.make(); public final Set<FunctionInvocation> calls = HashSetFactory.make(); } public static Set<ModuleEntry> getJavaScriptCodeFromProject(String project) throws IOException, CoreException { IJavaScriptProject p = JavaScriptHeadlessUtil.getJavaScriptProjectFromWorkspace(project); JSCallGraphUtil.setTranslatorFactory(new CAstRhinoTranslatorFactory()); AnalysisScope s = JavaScriptEclipseProjectPath.make(p, Collections.<Pair<String, Plugin>>emptySet()) .toAnalysisScope( new CAstAnalysisScope( JSCallGraphUtil.makeLoaders(), Collections.singleton(JavaScriptLoader.JS))); List<Module> modules = s.getModules(JavaScriptTypes.jsLoader); Set<ModuleEntry> mes = HashSetFactory.make(); for (Module m : modules) { for (ModuleEntry entry : Iterator2Iterable.make(m.getEntries())) { mes.add(entry); } } return mes; } public static CGInfo buildJSDTCallGraph(Set<ModuleEntry> mes) { final CGInfo info = new CGInfo(); HeadlessUtil.parseModules( mes, new EclipseCompiler<IJavaScriptUnit>() { @Override public IJavaScriptUnit getCompilationUnit(IFile file) { return JavaScriptCore.createCompilationUnitFrom(file); } @Override public Parser<IJavaScriptUnit> getParser() { return new Parser<>() { IJavaScriptProject project; @Override public void setProject(IProject project) { this.project = JavaScriptCore.create(project); } @Override public void processASTs( Map<IJavaScriptUnit, EclipseSourceFileModule> files, Function<Object[], Boolean> errors) { final ASTVisitor visitor = new ASTVisitor() { private final CallHierarchy ch = CallHierarchy.getDefault(); @Override public boolean visit(FunctionDeclaration node) { try { if (node.resolveBinding() != null) { IJavaScriptElement elt = node.resolveBinding().getJavaElement(); if (elt instanceof IFunction) try { MethodWrapper mw = ch.getCallerRoot((IFunction) elt); MethodWrapper calls[] = mw.getCalls(new NullProgressMonitor()); if (calls != null && calls.length > 0) { System.err.println("calls: for " + elt); for (MethodWrapper call : calls) { System.err.println("calls: " + call.getMember()); if (!info.cg.containsNode((IFunction) elt)) { info.cg.addNode((IFunction) elt); } if (!info.cg.containsNode(call.getMember())) { info.cg.addNode(call.getMember()); } info.cg.addEdge(call.getMember(), (IFunction) elt); } } } catch (Throwable e) { // Eclipse does whatever it wants, and we ignore stuff :) } } } catch (RuntimeException e) { } // TODO Auto-generated method stub return super.visit(node); } @Override public boolean visit(FunctionRef node) { System.err.println(node.resolveBinding().getJavaElement()); // TODO Auto-generated method stub return super.visit(node); } @Override public boolean visit(FunctionInvocation node) { info.calls.add(node); return super.visit(node); } }; if (useCreateASTs) { ASTParser parser = ASTParser.newParser(AST.JLS3); parser.setProject(project); parser.setResolveBindings(true); parser.createASTs( files.keySet().toArray(new IJavaScriptUnit[0]), new String[0], new ASTRequestor() { @Override public void acceptAST(IJavaScriptUnit source, JavaScriptUnit ast) { ast.accept(visitor); } }, null); } else { for (Map.Entry<IJavaScriptUnit, EclipseSourceFileModule> f : files.entrySet()) { ASTParser parser = ASTParser.newParser(AST.JLS3); parser.setProject(project); parser.setResolveBindings(true); parser.setSource(f.getKey()); try { ASTNode ast = parser.createAST(null); ast.accept(visitor); } catch (Throwable e) { System.err.println("trouble with " + f.getValue() + ": " + e.getMessage()); } } } } }; } }); return info; } }
8,754
41.707317
98
java
WALA
WALA-master/ide/jsdt/tests/src/test/java/com/ibm/wala/ide/jsdt/tests/AbstractJSProjectScopeTest.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.ide.jsdt.tests; import com.ibm.wala.cast.ipa.callgraph.CAstAnalysisScope; import com.ibm.wala.cast.js.client.EclipseJavaScriptAnalysisEngine; import com.ibm.wala.cast.js.client.EclipseJavaScriptAnalysisEngine.BuilderType; import com.ibm.wala.cast.js.ipa.callgraph.JSCallGraphUtil; import com.ibm.wala.cast.js.loader.JavaScriptLoader; import com.ibm.wala.cast.js.translator.CAstRhinoTranslatorFactory; import com.ibm.wala.cast.js.types.JavaScriptTypes; import com.ibm.wala.classLoader.ModuleEntry; import com.ibm.wala.ide.tests.util.EclipseTestUtil.ZippedProjectData; import com.ibm.wala.ide.util.JavaScriptEclipseProjectPath; import com.ibm.wala.ide.util.JavaScriptHeadlessUtil; import com.ibm.wala.ide.util.JsdtUtil; import com.ibm.wala.ide.util.JsdtUtil.CGInfo; import com.ibm.wala.ipa.callgraph.AnalysisScope; import com.ibm.wala.ipa.cha.IClassHierarchy; import com.ibm.wala.util.collections.Pair; import java.io.IOException; import java.util.Collections; import java.util.Set; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.Plugin; import org.eclipse.wst.jsdt.core.IJavaScriptProject; import org.junit.Assert; import org.junit.Ignore; import org.junit.Test; public abstract class AbstractJSProjectScopeTest { protected final ZippedProjectData project; public AbstractJSProjectScopeTest(ZippedProjectData project) { this.project = project; } @Test public void testOpenProject() { IJavaScriptProject p = JavaScriptHeadlessUtil.getJavaScriptProjectFromWorkspace(project.projectName); System.err.println(p); Assert.assertNotNull("cannot find project", p); } @Test public void testProjectScope() throws IOException, CoreException { IJavaScriptProject p = JavaScriptHeadlessUtil.getJavaScriptProjectFromWorkspace(project.projectName); JSCallGraphUtil.setTranslatorFactory(new CAstRhinoTranslatorFactory()); AnalysisScope s = makeProjectPath(p) .toAnalysisScope( new CAstAnalysisScope( JSCallGraphUtil.makeLoaders(), Collections.singleton(JavaScriptLoader.JS))); System.err.println(s); Assert.assertNotNull("cannot make scope", s); Assert.assertFalse("cannot find files", s.getModules(JavaScriptTypes.jsLoader).isEmpty()); } protected JavaScriptEclipseProjectPath makeProjectPath(IJavaScriptProject p) throws IOException, CoreException { return JavaScriptEclipseProjectPath.make(p, Collections.<Pair<String, Plugin>>emptySet()); } @Ignore("works for me on Eclipse Luna, but I cannot make it work with maven") @Test public void testParsing() throws IOException, CoreException { Set<ModuleEntry> mes = JsdtUtil.getJavaScriptCodeFromProject(project.projectName); CGInfo info = JsdtUtil.buildJSDTCallGraph(mes); System.err.println(info.calls.size()); System.err.println("call graph:\n" + info.cg); Assert.assertTrue("cannot find any function calls", info.calls.size() > 0); Assert.assertTrue("cannot find any cg nodes", info.cg.getNumberOfNodes() > 0); } @Test public void testEngine() throws IOException, IllegalArgumentException { IJavaScriptProject p = JavaScriptHeadlessUtil.getJavaScriptProjectFromWorkspace(project.projectName); EclipseJavaScriptAnalysisEngine e = makeAnalysisEngine(p); JSCallGraphUtil.setTranslatorFactory(new CAstRhinoTranslatorFactory()); e.buildAnalysisScope(); IClassHierarchy cha = e.getClassHierarchy(); // System.err.println(cha); Assert.assertNotNull(cha); } protected EclipseJavaScriptAnalysisEngine makeAnalysisEngine(IJavaScriptProject p) { return new EclipseJavaScriptAnalysisEngine(p, BuilderType.REFLECTIVE); } }
4,103
38.84466
96
java
WALA
WALA-master/ide/jsdt/tests/src/test/java/com/ibm/wala/ide/jsdt/tests/Activator.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.ide.jsdt.tests; import org.eclipse.core.runtime.Plugin; import org.osgi.framework.BundleContext; public class Activator extends Plugin { // The plug-in ID public static final String PLUGIN_ID = "com.ibm.wala.ide.jsdt.tests"; // The shared instance private static Activator plugin; /** The constructor */ public Activator() {} /* * (non-Javadoc) * * @see org.eclipse.core.runtime.Plugins#start(org.osgi.framework.BundleContext) */ @Override public void start(BundleContext context) throws Exception { super.start(context); plugin = this; } /* * (non-Javadoc) * * @see org.eclipse.core.runtime.Plugin#stop(org.osgi.framework.BundleContext) */ @Override public void stop(BundleContext context) throws Exception { plugin = null; super.stop(context); } /** * Returns the shared instance * * @return the shared instance */ public static Activator getDefault() { return plugin; } }
1,361
22.894737
82
java
WALA
WALA-master/ide/jsdt/tests/src/test/java/com/ibm/wala/ide/jsdt/tests/JSProjectScopeTest.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.ide.jsdt.tests; import com.ibm.wala.ide.tests.util.EclipseTestUtil.ZippedProjectData; import java.io.IOException; public class JSProjectScopeTest extends AbstractJSProjectScopeTest { public static final String PROJECT_NAME = "com.ibm.wala.cast.js"; public static final String PROJECT_ZIP = "test_js_project.zip"; public static final ZippedProjectData PROJECT; static { try { PROJECT = new ZippedProjectData(Activator.getDefault(), PROJECT_NAME, PROJECT_ZIP); } catch (IOException e) { throw new RuntimeException(e); } } public JSProjectScopeTest() { super(PROJECT); } }
1,008
27.027778
89
java
WALA
WALA-master/ide/src/main/java/com/ibm/wala/ide/classloader/EclipseSourceDirectoryTreeModule.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.ide.classloader; import com.ibm.wala.classLoader.FileModule; import com.ibm.wala.classLoader.SourceDirectoryTreeModule; import com.ibm.wala.ide.util.EclipseProjectPath; import java.io.File; import java.util.regex.Pattern; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IWorkspace; import org.eclipse.core.resources.IWorkspaceRoot; import org.eclipse.core.resources.ResourcesPlugin; import org.eclipse.core.runtime.IPath; public class EclipseSourceDirectoryTreeModule extends SourceDirectoryTreeModule { private final IPath rootIPath; private final Pattern[] excludePatterns; private static Pattern interpretPattern(IPath pattern) { return Pattern.compile( '^' + pattern .toString() .replace(".", "\\.") .replace("**", "~~~") .replace("*", "[^/]*") .replace("~~~", ".*") + '$'); } private static Pattern[] interpretExcludes(IPath[] excludes) { if (excludes == null) { return null; } else { Pattern[] stuff = new Pattern[excludes.length]; for (int i = 0; i < excludes.length; i++) { stuff[i] = interpretPattern(excludes[i]); } return stuff; } } public EclipseSourceDirectoryTreeModule(IPath root, IPath[] excludePaths) { super(EclipseProjectPath.makeAbsolute(root).toFile()); this.rootIPath = root; this.excludePatterns = interpretExcludes(excludePaths); } public EclipseSourceDirectoryTreeModule(IPath root, IPath[] excludePaths, String fileExt) { super(EclipseProjectPath.makeAbsolute(root).toFile(), fileExt); this.rootIPath = root; this.excludePatterns = interpretExcludes(excludePaths); } @Override protected FileModule makeFile(File file) { IPath p = rootIPath.append(file.getPath().substring(root.getPath().length())); IWorkspace ws = ResourcesPlugin.getWorkspace(); IWorkspaceRoot root = ws.getRoot(); IFile ifile = root.getFile(p); assert ifile.exists(); return EclipseSourceFileModule.createEclipseSourceFileModule(ifile); } @Override protected boolean includeFile(File file) { if (!super.includeFile(file)) { return false; } else { if (excludePatterns != null) { IPath p = rootIPath.append(file.getPath().substring(root.getPath().length())); for (Pattern exclude : excludePatterns) { if (exclude.matcher(p.toOSString()).matches()) { return false; } } } return true; } } @Override public String toString() { return "EclipseSourceDirectoryTreeModule:" + rootIPath; } }
3,051
30.463918
93
java
WALA
WALA-master/ide/src/main/java/com/ibm/wala/ide/classloader/EclipseSourceFileModule.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.ide.classloader; import com.ibm.wala.classLoader.SourceFileModule; import java.io.File; import org.eclipse.core.resources.IFile; /** A module which is a wrapper around a .java file */ public class EclipseSourceFileModule extends SourceFileModule { private final IFile f; public static EclipseSourceFileModule createEclipseSourceFileModule(IFile f) { if (f == null) { throw new IllegalArgumentException("null f"); } return new EclipseSourceFileModule(f); } private EclipseSourceFileModule(IFile f) { super(new File(f.getFullPath().toOSString()), f.getName(), null); this.f = f; } public IFile getIFile() { return f; } @Override public String toString() { return "EclipseSourceFileModule:" + getFile().toString(); } }
1,173
26.302326
80
java
WALA
WALA-master/ide/src/main/java/com/ibm/wala/ide/client/EclipseProjectAnalysisEngine.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.ide.client; import com.ibm.wala.client.AbstractAnalysisEngine; import com.ibm.wala.core.util.io.FileProvider; import com.ibm.wala.ide.util.EclipseProjectPath; 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.IAnalysisCacheView; import com.ibm.wala.ipa.callgraph.propagation.InstanceKey; import com.ibm.wala.ipa.cha.IClassHierarchy; import com.ibm.wala.util.config.FileOfClasses; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import org.eclipse.core.resources.ResourcesPlugin; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IPath; public abstract class EclipseProjectAnalysisEngine<P, I extends InstanceKey> extends AbstractAnalysisEngine<I, CallGraphBuilder<I>, Void> { protected final P project; protected final IPath workspaceRootPath; protected EclipseProjectPath<?, P> ePath; public EclipseProjectAnalysisEngine(P project) { this.project = project; this.workspaceRootPath = ResourcesPlugin.getWorkspace().getRoot().getLocation(); assert project != null; assert workspaceRootPath != null; } protected abstract EclipseProjectPath<?, P> createProjectPath(P project) throws IOException, CoreException; @Override protected abstract CallGraphBuilder<I> getCallGraphBuilder( IClassHierarchy cha, AnalysisOptions options, IAnalysisCacheView cache); protected abstract AnalysisScope makeAnalysisScope(); @Override public void buildAnalysisScope() throws IOException { try { ePath = createProjectPath(project); super.scope = ePath.toAnalysisScope(makeAnalysisScope()); if (getExclusionsFile() != null) { try (final InputStream is = new File(getExclusionsFile()).exists() ? new FileInputStream(getExclusionsFile()) : FileProvider.class.getClassLoader().getResourceAsStream(getExclusionsFile())) { scope.setExclusions(new FileOfClasses(is)); } } } catch (CoreException e) { assert false : e.getMessage(); } } public EclipseProjectPath<?, P> getEclipseProjectPath() { return ePath; } @Override public IClassHierarchy getClassHierarchy() { if (super.getClassHierarchy() == null) { setClassHierarchy(buildClassHierarchy()); } return super.getClassHierarchy(); } }
2,894
32.275862
97
java
WALA
WALA-master/ide/src/main/java/com/ibm/wala/ide/client/EclipseProjectSourceAnalysisEngine.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.ide.client; import com.ibm.wala.ipa.callgraph.AnalysisOptions; import com.ibm.wala.ipa.callgraph.Entrypoint; import com.ibm.wala.ipa.callgraph.IAnalysisCacheView; import com.ibm.wala.ipa.callgraph.propagation.InstanceKey; import com.ibm.wala.ssa.SSAOptions; import com.ibm.wala.ssa.SymbolTable; import com.ibm.wala.types.ClassLoaderReference; /** An {@link EclipseProjectAnalysisEngine} specialized for source code analysis */ public abstract class EclipseProjectSourceAnalysisEngine<P, I extends InstanceKey> extends EclipseProjectAnalysisEngine<P, I> { public static final String defaultFileExt = "java"; /** file extension for source files in this Eclipse project */ final String fileExt; public EclipseProjectSourceAnalysisEngine(P project) { this(project, defaultFileExt); } public EclipseProjectSourceAnalysisEngine(P project, String fileExt) { super(project); this.fileExt = fileExt; } /** * we don't provide a default implementation of this method to avoid introducing a dependence on * com.ibm.wala.cast from this project */ @Override public abstract IAnalysisCacheView makeDefaultCache(); protected abstract ClassLoaderReference getSourceLoader(); @Override public AnalysisOptions getDefaultOptions(Iterable<Entrypoint> entrypoints) { AnalysisOptions options = new AnalysisOptions(getScope(), entrypoints); SSAOptions ssaOptions = new SSAOptions(); ssaOptions.setDefaultValues(SymbolTable::getDefaultValue); options.setSSAOptions(ssaOptions); return options; } }
1,954
31.583333
98
java
WALA
WALA-master/ide/src/main/java/com/ibm/wala/ide/plugin/CorePlugin.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.ide.plugin; import org.eclipse.core.runtime.Platform; import org.eclipse.core.runtime.Plugin; import org.osgi.framework.Bundle; import org.osgi.framework.BundleContext; /** The main plugin class to be used in the desktop. */ public class CorePlugin extends Plugin { public static final boolean IS_ECLIPSE_RUNNING; static { boolean result = false; try { result = Platform.isRunning(); } catch (Throwable exception) { // Assume that we aren't running. } IS_ECLIPSE_RUNNING = result; } public static final boolean IS_RESOURCES_BUNDLE_AVAILABLE; static { boolean result = false; if (IS_ECLIPSE_RUNNING) { try { Bundle resourcesBundle = Platform.getBundle("org.eclipse.core.resources"); result = resourcesBundle != null && (resourcesBundle.getState() & (Bundle.ACTIVE | Bundle.STARTING | Bundle.RESOLVED)) != 0; } catch (Throwable exception) { // Assume that it's not available. } } IS_RESOURCES_BUNDLE_AVAILABLE = result; } // The shared instance. private static CorePlugin plugin; /** The constructor. */ public CorePlugin() { plugin = this; } /** * This method is called upon plug-in activation * * @throws IllegalArgumentException if context is null */ @Override public void start(BundleContext context) throws Exception { if (context == null) { throw new IllegalArgumentException("context is null"); } super.start(context); } /** This method is called when the plug-in is stopped */ @Override public void stop(BundleContext context) throws Exception { super.stop(context); plugin = null; } /** Returns the shared instance. */ public static CorePlugin getDefault() { return plugin; } }
2,244
25.411765
82
java
WALA
WALA-master/ide/src/main/java/com/ibm/wala/ide/ui/AbstractJFaceRunner.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.ide.ui; import org.eclipse.jface.window.ApplicationWindow; /** * abstract base class for launching a JFace application * * <p>TODO: unify with other launchers? */ public abstract class AbstractJFaceRunner { protected ApplicationWindow applicationWindow = null; protected boolean blockInput = false; protected AbstractJFaceRunner() { super(); } public ApplicationWindow getApplicationWindow() { return applicationWindow; } public void setApplicationWindow(ApplicationWindow newApplicationWindow) { applicationWindow = newApplicationWindow; } public boolean isBlockInput() { return blockInput; } public void setBlockInput(boolean newBlockInput) { blockInput = newBlockInput; } @Override public String toString() { return super.toString() + " (applicationWindow: " + applicationWindow + ", blockInput: " + blockInput + ')'; } }
1,329
22.75
76
java
WALA
WALA-master/ide/src/main/java/com/ibm/wala/ide/ui/IFDSExplorer.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.ide.ui; import com.ibm.wala.dataflow.IFDS.TabulationResult; import com.ibm.wala.properties.WalaProperties; 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.InferGraphRoots; import com.ibm.wala.util.viz.DotUtil; import com.ibm.wala.util.viz.NodeDecorator; import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; import java.util.Collection; import java.util.Properties; /** Explore the result of an IFDS problem with an SWT viewer and ghostview. */ public class IFDSExplorer { /** absolute path name to invoke dot */ protected static String dotExe = null; /** Absolute path name to invoke viewer */ protected static String viewerExe = null; private static final boolean PRINT_DOMAIN = true; public static void setDotExe(String newDotExe) { dotExe = newDotExe; } public static void setGvExe(String newGvExe) { viewerExe = newGvExe; } public static <T, P, F> void viewIFDS(TabulationResult<T, P, F> r, Collection<? extends P> roots) throws WalaException { viewIFDS(r, roots, null); } public static <T, P, F> void viewIFDS( TabulationResult<T, P, F> r, Collection<? extends P> roots, NodeDecorator<T> labels) throws WalaException { Properties p = null; try { p = WalaProperties.loadProperties(); } catch (WalaException e) { e.printStackTrace(); Assertions.UNREACHABLE(); } String scratch = p.getProperty(WalaProperties.OUTPUT_DIR); try { Files.createDirectories(Paths.get(scratch)); } catch (IOException e) { throw new WalaException("could not create output directory " + scratch, e); } viewIFDS(r, roots, labels, scratch); } public static <T, P, F> void viewIFDS( TabulationResult<T, P, F> r, Collection<? extends P> roots, NodeDecorator<T> labels, String scratchDirectory) throws WalaException { if (r == null) { throw new IllegalArgumentException("r is null"); } assert dotExe != null; // dump the domain to stderr if (PRINT_DOMAIN) { System.err.println("Domain:\n" + r.getProblem().getDomain().toString()); } String irFileName = "ir." + DotUtil.getOutputType().suffix; String outputFile = scratchDirectory + File.separatorChar + irFileName; String dotFile = scratchDirectory + File.separatorChar + "ir.dt"; final SWTTreeViewer<P> v = new SWTTreeViewer<>(); Graph<P> g = r.getProblem().getSupergraph().getProcedureGraph(); v.setGraphInput(g); v.setBlockInput(true); v.setRootsInput(roots); ViewIFDSLocalAction<T, P, F> action = (labels == null ? new ViewIFDSLocalAction<>(v, r, outputFile, dotFile, dotExe, viewerExe) : new ViewIFDSLocalAction<>(v, r, outputFile, dotFile, dotExe, viewerExe, labels)); v.getPopUpActions().add(action); v.run(); } /** * Calls {@link #viewIFDS(TabulationResult, Collection)} with roots computed by {@link * InferGraphRoots}. */ public static <T, P, F> void viewIFDS(TabulationResult<T, P, F> r) throws WalaException { if (r == null) { throw new IllegalArgumentException("null r"); } Collection<? extends P> roots = InferGraphRoots.inferRoots(r.getProblem().getSupergraph().getProcedureGraph()); viewIFDS(r, roots); } public static String getDotExe() { return dotExe; } public static String getGvExe() { return viewerExe; } }
3,948
30.592
99
java
WALA
WALA-master/ide/src/main/java/com/ibm/wala/ide/ui/SWTTreeViewer.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.ide.ui; import com.ibm.wala.util.PlatformUtil; import com.ibm.wala.util.WalaException; import com.ibm.wala.util.collections.Iterator2Iterable; import com.ibm.wala.util.debug.Assertions; import com.ibm.wala.util.graph.Graph; import com.ibm.wala.util.viz.NodeDecorator; import java.util.ArrayList; import java.util.Collection; import java.util.List; import org.eclipse.jface.action.IAction; import org.eclipse.jface.action.MenuManager; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.jface.viewers.ITreeContentProvider; import org.eclipse.jface.viewers.LabelProvider; import org.eclipse.jface.viewers.TreeViewer; import org.eclipse.jface.viewers.Viewer; import org.eclipse.jface.window.ApplicationWindow; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Display; import org.eclipse.ui.PlatformUI; /** A class to view a WALA {@link Graph} with an SWT {@link TreeViewer} */ @SuppressWarnings("unchecked") public class SWTTreeViewer<T> extends AbstractJFaceRunner { protected Graph<T> graphInput; protected Collection<?> rootsInput = null; protected NodeDecorator<Object> nodeDecoratorInput = null; protected final List<IAction> popUpActions = new ArrayList<>(); public SWTTreeViewer() { super(); } public Graph<T> getGraphInput() { return graphInput; } public void setGraphInput(Graph<T> newGraphInput) { graphInput = newGraphInput; } public Collection<?> getRootsInput() { return rootsInput; } public void setRootsInput(Collection<?> newRootsInput) { rootsInput = newRootsInput; } public NodeDecorator<Object> getNodeDecoratorInput() { return nodeDecoratorInput; } public void setNodeDecoratorInput(NodeDecorator<Object> newNodeDecoratorInput) { nodeDecoratorInput = newNodeDecoratorInput; } public List<IAction> getPopUpActions() { return popUpActions; } @Override public String toString() { return super.toString() + ", graphInput: " + graphInput + ", rootsInput: " + rootsInput + ", NodeDecoratorInput: " + nodeDecoratorInput + ", popUpActions: " + popUpActions + ')'; } public void run() throws WalaException { if (getRootsInput() == null) { throw new WalaException("null roots input in " + getClass()); } final ApplicationWindow w = new GraphViewer(getGraphInput()); setApplicationWindow(w); w.setBlockOnOpen(true); if (PlatformUI.isWorkbenchRunning()) { // run the code on the UI thread Display d = PlatformUI.getWorkbench().getDisplay(); Runnable r = () -> { try { w.open(); } catch (Exception e) { e.printStackTrace(); } }; if (isBlockInput()) { d.syncExec(r); } else { d.asyncExec(r); } } else { if (PlatformUtil.onMacOSX()) { // the Mac does not like running the Window code in another thread // side-effect: we always block input on Mac w.open(); Display.getCurrent().dispose(); } else { Runnable r = () -> { w.open(); Display.getCurrent().dispose(); }; Thread t = new Thread(r); t.start(); if (isBlockInput()) { try { t.join(); } catch (InterruptedException e) { throw new WalaException("unexpected interruption", e); } } } } } /** * For testing purposes, open the tree viewer window and then immediately close it. Useful for * testing that there is no failure while opening the window. */ public void justOpenForTest() throws WalaException { if (getRootsInput() == null) { throw new IllegalStateException("null roots input in " + getClass()); } final ApplicationWindow w = new GraphViewer(getGraphInput()); setApplicationWindow(w); if (PlatformUI.isWorkbenchRunning()) { throw new IllegalStateException("not designed to run inside workbench"); } w.open(); Display.getCurrent().dispose(); } public IStructuredSelection getSelection() throws IllegalStateException { GraphViewer viewer = (GraphViewer) getApplicationWindow(); if (viewer == null || viewer.treeViewer == null) { throw new IllegalStateException(); } return (IStructuredSelection) viewer.treeViewer.getSelection(); } /** * @author sfink * <p>An SWT window to visualize a graph */ private class GraphViewer extends ApplicationWindow { /** Graph to visualize */ private final Graph<T> graph; /** JFace component implementing the tree viewer */ private TreeViewer treeViewer; public GraphViewer(Graph<T> graph) throws WalaException { super(null); this.graph = graph; if (graph == null) { throw new WalaException("null graph for SWT viewer"); } } /** @see org.eclipse.jface.window.Window#createContents(org.eclipse.swt.widgets.Composite) */ @Override protected Control createContents(Composite parent) { treeViewer = new TreeViewer(parent); treeViewer.setContentProvider(new GraphContentProvider()); treeViewer.setLabelProvider(new GraphLabelProvider()); treeViewer.setInput(getGraphInput()); // create a pop-up menu if (getPopUpActions().size() > 0) { MenuManager mm = new MenuManager(); treeViewer.getTree().setMenu(mm.createContextMenu(treeViewer.getTree())); for (IAction iAction : getPopUpActions()) { mm.add(iAction); } } return treeViewer.getTree(); } /** * @author sfink * <p>Simple wrapper around an EObjectGraph to provide content for a tree viewer. */ private class GraphContentProvider implements ITreeContentProvider { /* * @see org.eclipse.jface.viewers.IContentProvider#dispose() */ @Override public void dispose() { // do nothing for now } /* * @see org.eclipse.jface.viewers.IContentProvider#inputChanged(org.eclipse.jface.viewers.Viewer, * java.lang.Object, java.lang.Object) */ @Override public void inputChanged(Viewer viewer, Object oldInput, Object newInput) { // for now do nothing, since we're not dealing with listeners } /* * @see org.eclipse.jface.viewers.ITreeContentProvider#getChildren(java.lang.Object) */ @Override public Object[] getChildren(Object parentElement) { Object[] result = new Object[graph.getSuccNodeCount((T) parentElement)]; int i = 0; for (Object o : Iterator2Iterable.make(graph.getSuccNodes((T) parentElement))) { result[i++] = o; } return result; } /* * @see org.eclipse.jface.viewers.ITreeContentProvider#getParent(java.lang.Object) */ @Override public Object getParent(Object element) { // TODO Auto-generated method stub Assertions.UNREACHABLE(); return null; } /* * @see org.eclipse.jface.viewers.ITreeContentProvider#hasChildren(java.lang.Object) */ @Override public boolean hasChildren(Object element) { return graph.getSuccNodeCount((T) element) > 0; } /* * @see org.eclipse.jface.viewers.IStructuredContentProvider#getElements(java.lang.Object) */ @Override public Object[] getElements(Object inputElement) { Collection<?> roots = getRootsInput(); Assertions.productionAssertion(roots != null); Assertions.productionAssertion(roots.size() >= 1); return roots.toArray(); } } /** Simple graph label provider. TODO: finish this implementation. */ private class GraphLabelProvider extends LabelProvider { final NodeDecorator<Object> d = getNodeDecoratorInput(); @Override public String getText(Object element) { try { return (d == null) ? super.getText(element) : d.getLabel(element); } catch (WalaException e) { e.printStackTrace(); Assertions.UNREACHABLE(); return null; } } } } }
8,725
28.579661
103
java
WALA
WALA-master/ide/src/main/java/com/ibm/wala/ide/ui/ViewIFDSLocalAction.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.ide.ui; import com.ibm.wala.core.viz.PDFViewUtil; import com.ibm.wala.dataflow.IFDS.ISupergraph; import com.ibm.wala.dataflow.IFDS.TabulationResult; import com.ibm.wala.ipa.cfg.BasicBlockInContext; import com.ibm.wala.ssa.SSAAbstractInvokeInstruction; import com.ibm.wala.ssa.SSAGetInstruction; import com.ibm.wala.ssa.SSAInstruction; import com.ibm.wala.ssa.SSAPhiInstruction; import com.ibm.wala.ssa.analysis.IExplodedBasicBlock; import com.ibm.wala.util.WalaException; import com.ibm.wala.util.collections.Iterator2Iterable; 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.viz.DotUtil; import com.ibm.wala.util.viz.NodeDecorator; import java.util.function.Predicate; import org.eclipse.jface.action.Action; import org.eclipse.jface.viewers.IStructuredSelection; /** * An SWT action that spawns spawns a ghostview to see the local supergraph for a procedure node * which is the current selection in a tree viewer. * * @author sfink */ public class ViewIFDSLocalAction<T, P, F> extends Action { /** Governing tree viewer */ private final SWTTreeViewer<P> viewer; /** Governing supergraph */ private final ISupergraph<T, P> supergraph; /** name of PDF file to generate */ private final String pdfFile; /** name of dot file to generate */ private final String dotFile; /** path to dot.exe */ private final String dotExe; /** path to pdf view executable */ private final String pdfViewExe; private final NodeDecorator<T> labels; public ViewIFDSLocalAction( SWTTreeViewer<P> viewer, TabulationResult<T, P, F> result, String pdfFile, String dotFile, String dotExe, String pdfViewExe, NodeDecorator<T> labels) { if (result == null) { throw new IllegalArgumentException("null result"); } this.viewer = viewer; this.supergraph = result.getProblem().getSupergraph(); this.pdfFile = pdfFile; this.dotFile = dotFile; this.dotExe = dotExe; this.pdfViewExe = pdfViewExe; this.labels = labels; setText("View Local Supergraph"); } public ViewIFDSLocalAction( SWTTreeViewer<P> viewer, TabulationResult<T, P, F> result, String psFile, String dotFile, String dotExe, String gvExe) { if (result == null) { throw new IllegalArgumentException("null result"); } this.viewer = viewer; this.supergraph = result.getProblem().getSupergraph(); this.pdfFile = psFile; this.dotFile = dotFile; this.dotExe = dotExe; this.pdfViewExe = gvExe; this.labels = new Labels<>(result); setText("View Local Supergraph"); } private static class Labels<T, P, F> implements NodeDecorator<T> { private final TabulationResult<T, P, F> result; Labels(TabulationResult<T, P, F> result) { this.result = result; } @Override @SuppressWarnings("unchecked") public String getLabel(Object o) throws WalaException { T t = (T) o; if (t instanceof BasicBlockInContext) { BasicBlockInContext<?> bb = (BasicBlockInContext<?>) t; if (bb.getDelegate() instanceof IExplodedBasicBlock) { IExplodedBasicBlock delegate = (IExplodedBasicBlock) bb.getDelegate(); final StringBuilder s = new StringBuilder(delegate.getNumber()) .append(' ') .append(result.getResult(t)) .append("\\n") .append(stringify(delegate.getInstruction())); for (SSAPhiInstruction phi : Iterator2Iterable.make(delegate.iteratePhis())) { s.append(' ').append(phi); } if (delegate.isCatchBlock()) { s.append(' ').append(delegate.getCatchInstruction()); } return s.toString(); } } return t + " " + result.getResult(t); } } /** Print a short-ish representation of s as a String */ public static String stringify(SSAInstruction s) { if (s == null) { return null; } if (s instanceof SSAAbstractInvokeInstruction) { SSAAbstractInvokeInstruction call = (SSAAbstractInvokeInstruction) s; String def = call.hasDef() ? call.getDef() + "=" : ""; final StringBuilder result = new StringBuilder(def) .append("call ") .append(call.getDeclaredTarget().getDeclaringClass().getName().getClassName()) .append('.') .append(call.getDeclaredTarget().getName()); result.append(" exc:").append(call.getException()); for (int i = 0; i < s.getNumberOfUses(); i++) { result.append(' ').append(s.getUse(i)); } return result.toString(); } if (s instanceof SSAGetInstruction) { SSAGetInstruction g = (SSAGetInstruction) s; String fieldName = g.getDeclaredField().getName().toString(); StringBuilder result = new StringBuilder(); result.append(g.getDef()); result.append(":="); result.append(g.isStatic() ? "getstatic " : "getfield "); result.append(fieldName); if (!g.isStatic()) { result.append(' '); result.append(g.getUse(0)); } return result.toString(); } return s.toString(); } /** @see org.eclipse.jface.action.IAction#run() */ @Override public void run() { try { final P proc = getProcedureForSelection(); Predicate<T> filter = o -> supergraph.getProcOf(o).equals(proc); Graph<T> localGraph = GraphSlicer.prune(supergraph, filter); // spawn the viewer System.err.println("Spawn Viewer for " + proc); DotUtil.dotify(localGraph, labels, dotFile, pdfFile, dotExe); if (DotUtil.getOutputType() == DotUtil.DotOutputType.PDF) { PDFViewUtil.launchPDFView(pdfFile, pdfViewExe); } } catch (WalaException e) { e.printStackTrace(); Assertions.UNREACHABLE(); } } @SuppressWarnings("unchecked") protected P getProcedureForSelection() { // we assume the tree viewer's current selection is a P IStructuredSelection selection = viewer.getSelection(); if (selection.size() != 1) { throw new UnsupportedOperationException( "did not expect selection of size " + selection.size()); } P first = (P) selection.getFirstElement(); return first; } protected SWTTreeViewer<P> getViewer() { return viewer; } protected ISupergraph<T, P> getSupergraph() { return supergraph; } protected String getDotExe() { return dotExe; } protected String getDotFile() { return dotFile; } protected String getGvExe() { return pdfViewExe; } protected String getPsFile() { return pdfFile; } }
7,147
29.810345
96
java
WALA
WALA-master/ide/src/main/java/com/ibm/wala/ide/ui/ViewIRAction.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.ide.ui; import com.ibm.wala.core.viz.PDFViewUtil; import com.ibm.wala.ipa.callgraph.CGNode; import com.ibm.wala.ipa.callgraph.CallGraph; import com.ibm.wala.ssa.IR; import com.ibm.wala.util.WalaException; import org.eclipse.jface.action.Action; import org.eclipse.jface.viewers.IStructuredSelection; /** * An SWT action that spawns spawns a ghostview to see the IR for a call graph node which is the * current selection in a tree viewer. */ public class ViewIRAction<P> extends Action { /** Governing tree viewer */ private final SWTTreeViewer<P> viewer; /** Governing call graph */ private final CallGraph cg; /** name of postscript file to generate */ private final String psFile; /** name of dot file to generate */ private final String dotFile; /** path to dot.exe */ private final String dotExe; /** path to ghostview executable */ private final String gvExe; /** * @param viewer Governing tree viewer * @param cg Governing call graph */ public ViewIRAction( SWTTreeViewer<P> viewer, CallGraph cg, String psFile, String dotFile, String dotExe, String gvExe) { if (viewer == null) { throw new IllegalArgumentException("null viewer"); } this.viewer = viewer; this.cg = cg; this.psFile = psFile; this.dotFile = dotFile; this.dotExe = dotExe; this.gvExe = gvExe; setText("View IR"); } /** * @see org.eclipse.jface.action.IAction#run() * @throws IllegalStateException if the viewer is not running */ @Override public void run() { IR ir = getIRForSelection(); // spawn the viewer System.err.println("Spawn IR Viewer for " + ir.getMethod()); try { PDFViewUtil.ghostviewIR(cg.getClassHierarchy(), ir, psFile, dotFile, dotExe, gvExe); } catch (WalaException e) { e.printStackTrace(); } } /** @throws IllegalStateException if the viewer is not running */ protected IR getIRForSelection() { // we assume the tree viewer's current selection is a CGNode IStructuredSelection selection = viewer.getSelection(); if (selection.size() != 1) { throw new UnsupportedOperationException( "did not expect selection of size " + selection.size()); } CGNode first = (CGNode) selection.getFirstElement(); // get the IR for the node return first.getIR(); } protected CGNode getNodeForSelection() { // we assume the tree viewer's current selection is a CGNode IStructuredSelection selection = viewer.getSelection(); if (selection.size() != 1) { throw new UnsupportedOperationException( "did not expect selection of size " + selection.size()); } CGNode first = (CGNode) selection.getFirstElement(); return first; } protected SWTTreeViewer<P> getViewer() { return viewer; } protected CallGraph getCg() { return cg; } protected String getDotExe() { return dotExe; } protected String getDotFile() { return dotFile; } protected String getGvExe() { return gvExe; } protected String getPsFile() { return psFile; } }
3,515
25.636364
96
java
WALA
WALA-master/ide/src/main/java/com/ibm/wala/ide/util/EclipseAnalysisScopeReader.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.ide.util; import com.ibm.wala.core.util.config.AnalysisScopeReader; import com.ibm.wala.ide.plugin.CorePlugin; import com.ibm.wala.ipa.callgraph.AnalysisScope; import com.ibm.wala.types.ClassLoaderReference; import java.io.File; import java.io.IOException; import org.eclipse.core.runtime.Plugin; public class EclipseAnalysisScopeReader extends AnalysisScopeReader { public AnalysisScope readJavaScopeFromPlugin( String scopeFileName, File exclusionsFile, ClassLoader javaLoader) throws IOException { return readJavaScopeFromPlugin( scopeFileName, exclusionsFile, javaLoader, CorePlugin.getDefault()); } public AnalysisScope readJavaScopeFromPlugin( String scopeFileName, File exclusionsFile, ClassLoader javaLoader, @SuppressWarnings("unused") Plugin plugIn) throws IOException { AnalysisScope scope = AnalysisScope.createJavaAnalysisScope(); return read(scope, scopeFileName, exclusionsFile, javaLoader); } public AnalysisScope makePrimordialScopeFromPlugin(File exclusionsFile) throws IOException { return makePrimordialScopeFromPlugin(exclusionsFile, CorePlugin.getDefault()); } /** * @param exclusionsFile file holding class hierarchy exclusions. may be null * @throws IllegalStateException if there are problmes reading wala properties */ public AnalysisScope makePrimordialScopeFromPlugin( File exclusionsFile, @SuppressWarnings("unused") Plugin plugIn) throws IOException { return read( AnalysisScope.createJavaAnalysisScope(), BASIC_FILE, exclusionsFile, EclipseAnalysisScopeReader.class.getClassLoader()); } public AnalysisScope makeJavaBinaryAnalysisScopeFromPlugin(String classPath, File exclusionsFile) throws IOException { return makeJavaBinaryAnalysisScopeFromPlugin( classPath, exclusionsFile, CorePlugin.getDefault()); } /** * @param classPath class path to analyze, delimited by File.pathSeparator * @param exclusionsFile file holding class hierarchy exclusions. may be null * @throws IllegalStateException if there are problems reading wala properties */ public AnalysisScope makeJavaBinaryAnalysisScopeFromPlugin( String classPath, File exclusionsFile, Plugin plugIn) throws IOException { if (classPath == null) { throw new IllegalArgumentException("classPath null"); } AnalysisScope scope = makePrimordialScopeFromPlugin(exclusionsFile, plugIn); ClassLoaderReference loader = scope.getLoader(AnalysisScope.APPLICATION); addClassPathToScope(classPath, scope, loader); return scope; } }
3,009
37.101266
99
java
WALA
WALA-master/ide/src/main/java/com/ibm/wala/ide/util/EclipseFileProvider.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.ide.util; import com.ibm.wala.classLoader.JarFileModule; import com.ibm.wala.classLoader.Module; import com.ibm.wala.core.util.io.FileProvider; import com.ibm.wala.ide.plugin.CorePlugin; import com.ibm.wala.util.debug.Assertions; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.lang.reflect.Method; import java.net.MalformedURLException; import java.net.URL; import java.util.jar.JarFile; import org.eclipse.core.runtime.FileLocator; import org.eclipse.core.runtime.IPath; import org.eclipse.core.runtime.Path; import org.eclipse.core.runtime.Platform; import org.eclipse.core.runtime.Plugin; import org.osgi.framework.Bundle; public class EclipseFileProvider extends FileProvider { /** the plug-in to use. If {@code null}, {@link CorePlugin#getDefault()} is used. */ private final Plugin plugIn; public EclipseFileProvider() { this(null); } public EclipseFileProvider(Plugin plugIn) { this.plugIn = plugIn; } /** * This class uses reflection to access classes and methods that are only available when Eclipse * is running as an IDE environment. The choice to use reflection is related to builds: with this * design the build doesn't need to provide IDE bundles during compilation and hence can spot * invalid uses of such classes through this bundle. * * <p>Because of this class, this bundle must OPTIONALY require 'org.eclipse.core.resources'. */ private static final class EclipseUtil { private static Object workspaceRoot = null; private static Method workspaceRoot_getFile = null; public static Module getJarFileModule(String fileName) { // Using reflection to enable this code to be built without the // org.eclipse.core.resources bundle // try { if (workspaceRoot_getFile == null) { Class<?> cls = Class.forName("org.eclipse.core.resources.ResourcesPlugin"); Method getWorkspaceMethod = cls.getDeclaredMethod("getWorkspace"); Object workspace = getWorkspaceMethod.invoke(null); Method getRoot = workspace.getClass().getDeclaredMethod("getRoot"); workspaceRoot = getRoot.invoke(workspace); workspaceRoot_getFile = workspaceRoot.getClass().getMethod("getFile", IPath.class); } IPath path = new Path(fileName); if (workspaceRoot_getFile.invoke(workspaceRoot, path) != null) { try (final JarFile jar = new JarFile(fileName, false)) { return new JarFileModule(jar); } } } catch (Exception e) { } return null; } } @Override public Module getJarFileModule(String fileName, ClassLoader loader) throws IOException { if (CorePlugin.getDefault() == null) { return getJarFileFromClassLoader(fileName, loader); } else if (plugIn != null) { return getFromPlugin(plugIn, fileName); } else if (CorePlugin.IS_RESOURCES_BUNDLE_AVAILABLE) { Module module = EclipseUtil.getJarFileModule(fileName); if (module != null) { return module; } } return getFromPlugin(CorePlugin.getDefault(), fileName); } /** @return the jar file packaged with this plug-in of the given name, or null if not found. */ private JarFileModule getFromPlugin(Plugin p, String fileName) throws IOException { URL url = getFileURLFromPlugin(p, fileName); if (url == null) return null; try (final JarFile jar = new JarFile(filePathFromURL(url))) { return new JarFileModule(jar); } } /** * get a file URL for a file from a plugin * * @param fileName the file name * @return the URL, or {@code null} if the file is not found */ private static URL getFileURLFromPlugin(Plugin p, String fileName) throws IOException { try { URL url = FileLocator.find(p.getBundle(), new Path(fileName), null); if (url == null) { // try lib/fileName String libFileName = "lib/" + fileName; url = FileLocator.find(p.getBundle(), new Path(libFileName), null); if (url == null) { // try bin/fileName String binFileName = "bin/" + fileName; url = FileLocator.find(p.getBundle(), new Path(binFileName), null); if (url == null) { // try it as an absolute path? File f = new File(fileName); if (!f.exists()) { // give up return null; } else { url = f.toURI().toURL(); } } } } url = FileLocator.toFileURL(url); url = fixupFileURLSpaces(url); return url; } catch (ExceptionInInitializerError e) { throw new IOException("failure to get file URL for " + fileName, e); } } /** * escape spaces in a URL, primarily to work around a bug in {@link File#toURL()} * * @return an escaped version of the URL */ @SuppressWarnings("javadoc") private static URL fixupFileURLSpaces(URL url) { String urlString = url.toExternalForm(); StringBuilder fixedUpUrl = new StringBuilder(); int lastIndex = 0; while (true) { int spaceIndex = urlString.indexOf(' ', lastIndex); if (spaceIndex < 0) { fixedUpUrl.append(urlString.substring(lastIndex)); break; } fixedUpUrl.append(urlString, lastIndex, spaceIndex); fixedUpUrl.append("%20"); lastIndex = spaceIndex + 1; } try { return new URL(fixedUpUrl.toString()); } catch (MalformedURLException e) { e.printStackTrace(); Assertions.UNREACHABLE(); } return null; } @Override public URL getResource(String fileName, ClassLoader loader) { if (fileName == null) { throw new IllegalArgumentException("null fileName"); } Plugin p = plugIn == null ? CorePlugin.getDefault() : plugIn; if (p == null && loader == null) { throw new IllegalArgumentException("null loader"); } return (p == null) ? loader.getResource(fileName) : FileLocator.find(p.getBundle(), new Path(fileName), null); } @Override public File getFile(String fileName, ClassLoader loader) throws IOException { Plugin p = plugIn == null ? CorePlugin.getDefault() : plugIn; if (p == null) { return getFileFromClassLoader(fileName, loader); } else { try { return getFileFromPlugin(p, fileName); } catch (IOException e) { return getFileFromClassLoader(fileName, loader); } } } /** * @return the jar file packaged with this plug-in of the given name, or null if not found. * @throws IllegalArgumentException if p is null */ public File getFileFromPlugin(Plugin p, String fileName) throws IOException { if (p == null) { throw new IllegalArgumentException("p is null"); } if (fileName == null) { throw new IllegalArgumentException("null fileName"); } URL url = getFileURLFromPlugin(p, fileName); if (url == null) { throw new FileNotFoundException(fileName); } return new File(filePathFromURL(url)); } /** * This is fragile. Use with care. * * @return a String representing the path to the wala.core plugin installation */ public static String getWalaCorePluginHome() { if (CorePlugin.getDefault() == null) { return null; } String install = Platform.getInstallLocation().getURL().getPath(); Bundle b = Platform.getBundle("com.ibm.wala.core"); String l = b.getLocation(); if (l.startsWith("update@")) { l = l.replace("update@", ""); } if (l.startsWith("reference:file:")) { return l.replace("reference:file:", ""); } else { return install + File.separator + l; } } }
8,110
32.378601
99
java
WALA
WALA-master/ide/src/main/java/com/ibm/wala/ide/util/EclipseProjectPath.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.ide.util; import com.ibm.wala.classLoader.BinaryDirectoryTreeModule; import com.ibm.wala.classLoader.JarFileModule; import com.ibm.wala.classLoader.Module; import com.ibm.wala.client.AbstractAnalysisEngine; import com.ibm.wala.core.util.config.AnalysisScopeReader; import com.ibm.wala.ide.classloader.EclipseSourceDirectoryTreeModule; import com.ibm.wala.ipa.callgraph.AnalysisScope; import com.ibm.wala.types.ClassLoaderReference; import com.ibm.wala.util.collections.HashSetFactory; import com.ibm.wala.util.collections.MapUtil; import com.ibm.wala.util.debug.Assertions; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.jar.JarFile; import org.eclipse.core.resources.IProject; import org.eclipse.core.resources.IResource; import org.eclipse.core.resources.IWorkspace; import org.eclipse.core.resources.IWorkspaceRoot; import org.eclipse.core.resources.ResourcesPlugin; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IPath; import org.eclipse.jdt.core.IClasspathEntry; import org.eclipse.osgi.service.resolver.BundleDescription; import org.eclipse.osgi.service.resolver.ImportPackageSpecification; import org.eclipse.pde.core.plugin.IPluginModelBase; import org.eclipse.pde.internal.core.ClasspathUtilCore; import org.eclipse.pde.internal.core.PDECore; /** * Representation of an analysis scope from an Eclipse project. * * <p>We set up classloaders as follows: * * <ul> * <li>The project being analyzed is in the Application Loader * <li>Frameworks, application libraries, and linked projects on which the main project depends * are in the Extension loader * <li>System libraries are in the primordial loader. * <li>All source modules go in a special Source loader. This includes source from linked projects * if SOURCE_FOR_PROJ_AND_LINKED_PROJS is specified. * </ul> */ public abstract class EclipseProjectPath<E, P> { protected abstract P makeProject(IProject p); protected abstract E resolve(E entry); protected abstract void resolveClasspathEntry( P project, E entry, ILoader loader, boolean includeSource, boolean cpeFromMainProject); protected abstract void resolveProjectClasspathEntries(P project, boolean includeSource); public interface ILoader { ClassLoaderReference ref(); } /** Eclipse projects are modeled with 3 loaders, as described above. */ public enum Loader implements ILoader { APPLICATION(ClassLoaderReference.Application), EXTENSION(ClassLoaderReference.Extension), PRIMORDIAL(ClassLoaderReference.Primordial); private final ClassLoaderReference ref; Loader(ClassLoaderReference ref) { this.ref = ref; } @Override public ClassLoaderReference ref() { return ref; } } public enum AnalysisScopeType { NO_SOURCE, SOURCE_FOR_PROJ, SOURCE_FOR_PROJ_AND_LINKED_PROJS } /** names of OSGi bundles already processed. */ private final Set<String> bundlesProcessed = HashSetFactory.make(); // SJF: Intentionally do not use HashMapFactory, since the Loader keys in the following must use // identityHashCode. TODO: fix this source of non-determinism? protected final Map<ILoader, List<Module>> modules = new HashMap<>(); /** Classpath entries that have already been resolved and added to the scope. */ protected final Collection<E> alreadyResolved = HashSetFactory.make(); /** Which source files, if any, should be included in the analysis scope. */ private final AnalysisScopeType scopeType; protected EclipseProjectPath(AnalysisScopeType scopeType) { this.scopeType = scopeType; for (ILoader loader : Loader.values()) { MapUtil.findOrCreateList(modules, loader); } } public EclipseProjectPath<E, P> create(IProject project) throws CoreException, IOException { if (project == null) { throw new IllegalArgumentException("null project"); } boolean includeSource = (scopeType != AnalysisScopeType.NO_SOURCE); resolveProjectClasspathEntries(makeProject(project), includeSource); if (isPluginProject(project)) { resolvePluginClassPath(project, includeSource); } return this; } protected void resolveLibraryPathEntry(ILoader loader, IPath p) { File file = makeAbsolute(p).toFile(); JarFile j; try { j = new JarFile(file); } catch (IOException z) { // may be a corrupted zip file or a directory. ignore it. return; } if (isPrimordialJarFile(j)) { List<Module> s = MapUtil.findOrCreateList(modules, loader); s.add( file.isDirectory() ? (Module) new BinaryDirectoryTreeModule(file) : (Module) new JarFileModule(j)); } } protected void resolveSourcePathEntry( ILoader loader, boolean includeSource, boolean cpeFromMainProject, IPath p, IPath o, IPath[] excludePaths, String fileExtension) { if (includeSource) { List<Module> s = MapUtil.findOrCreateList(modules, loader); s.add(new EclipseSourceDirectoryTreeModule(p, excludePaths, fileExtension)); } else if (o != null) { File output = makeAbsolute(o).toFile(); List<Module> s = MapUtil.findOrCreateList(modules, cpeFromMainProject ? Loader.APPLICATION : loader); s.add(new BinaryDirectoryTreeModule(output)); } } protected void resolveProjectPathEntry(boolean includeSource, IPath p) { IPath projectPath = makeAbsolute(p); IWorkspace ws = ResourcesPlugin.getWorkspace(); IWorkspaceRoot root = ws.getRoot(); IProject project = (IProject) root.getContainerForLocation(projectPath); try { P javaProject = makeProject(project); if (javaProject != null) { if (isPluginProject(project)) { resolvePluginClassPath(project, includeSource); } resolveProjectClasspathEntries( javaProject, scopeType == AnalysisScopeType.SOURCE_FOR_PROJ_AND_LINKED_PROJS ? includeSource : false); } } catch (CoreException | IOException e1) { e1.printStackTrace(); Assertions.UNREACHABLE(); } } /** * traverse the bundle description for an Eclipse project and populate the analysis scope * accordingly */ private void resolvePluginClassPath(IProject p, boolean includeSource) throws CoreException, IOException { IPluginModelBase model = findModel(p); if (!model.isInSync() || model.isDisposed()) { model.load(); } BundleDescription bd = model.getBundleDescription(); if (bd == null) { // temporary debugging code; remove once we figure out what the heck is going on here --MS System.err.println("model.isDisposed(): " + model.isDisposed()); System.err.println("model.isInSync(): " + model.isInSync()); System.err.println("model.isEnabled(): " + model.isEnabled()); System.err.println("model.isLoaded(): " + model.isLoaded()); System.err.println("model.isValid(): " + model.isValid()); } for (int i = 0; i < 3 && bd == null; i++) { // Uh oh. bd is null. Go to sleep, cross your fingers, and try again. // This is horrible. We can't figure out the race condition yet which causes this to happen. try { Thread.sleep(5000); } catch (InterruptedException e) { // whatever. } bd = findModel(p).getBundleDescription(); } if (bd == null) { throw new IllegalStateException("bundle description was null for " + p); } resolveBundleDescriptionClassPath(makeProject(p), bd, Loader.APPLICATION, includeSource); } /** traverse a bundle description and populate the analysis scope accordingly */ private void resolveBundleDescriptionClassPath( P project, BundleDescription bd, Loader loader, boolean includeSource) throws CoreException, IOException { assert bd != null; if (alreadyProcessed(bd)) { return; } bundlesProcessed.add(bd.getName()); // handle the classpath entries for bd ArrayList<IClasspathEntry> l = new ArrayList<>(); ClasspathUtilCore.addLibraries(findModel(bd), l); @SuppressWarnings("unchecked") List<E> entries = (List<E>) l; resolveClasspathEntries(project, entries, loader, includeSource, false); // recurse to handle dependencies. put these in the Extension loader for (ImportPackageSpecification b : bd.getImportPackages()) { resolveBundleDescriptionClassPath(project, b.getBundle(), Loader.EXTENSION, includeSource); } for (BundleDescription b : bd.getResolvedRequires()) { resolveBundleDescriptionClassPath(project, b, Loader.EXTENSION, includeSource); } for (BundleDescription b : bd.getFragments()) { resolveBundleDescriptionClassPath(project, b, Loader.EXTENSION, includeSource); } } /** have we already processed a particular bundle description? */ private boolean alreadyProcessed(BundleDescription bd) { return bundlesProcessed.contains(bd.getName()); } /** Is javaProject a plugin project? */ private static boolean isPluginProject(IProject project) { IPluginModelBase model = findModel(project); if (model == null) { return false; } if (model.getPluginBase().getId() == null) { return false; } return true; } /** * @param j The jar file in question. * @return true if the given jar file should be handled by the Primordial loader. If false, other * provisions should be made to add the jar file to the appropriate component of the * AnalysisScope. Subclasses can override this method. */ protected boolean isPrimordialJarFile(JarFile j) { return true; } protected void resolveClasspathEntries( P project, List<E> l, ILoader loader, boolean includeSource, boolean entriesFromTopLevelProject) { for (final E entry : l) { resolveClasspathEntry( project, resolve(entry), loader, includeSource, entriesFromTopLevelProject); } } public static IPath makeAbsolute(IPath p) { IPath absolutePath = p; if (p.toFile().exists()) { return p; } IResource resource = ResourcesPlugin.getWorkspace().getRoot().findMember(p); if (resource != null && resource.exists()) { absolutePath = resource.getLocation(); } return absolutePath; } /** Convert this path to a WALA analysis scope */ public AnalysisScope toAnalysisScope(ClassLoader classLoader, File exclusionsFile) throws IOException { AnalysisScope scope = AnalysisScopeReader.instance.readJavaScope( AbstractAnalysisEngine.SYNTHETIC_J2SE_MODEL, exclusionsFile, classLoader); return toAnalysisScope(scope); } public AnalysisScope toAnalysisScope(AnalysisScope scope) { for (Map.Entry<ILoader, List<Module>> entry : modules.entrySet()) { for (Module m : entry.getValue()) { scope.addToScope(entry.getKey().ref(), m); } } return scope; } public AnalysisScope toAnalysisScope(final File exclusionsFile) throws IOException { return toAnalysisScope(getClass().getClassLoader(), exclusionsFile); } public AnalysisScope toAnalysisScope() throws IOException { return toAnalysisScope(getClass().getClassLoader(), null); } public Collection<Module> getModules(ILoader loader) { return Collections.unmodifiableCollection(modules.get(loader)); } @Override public String toString() { try { return toAnalysisScope((File) null).toString(); } catch (IOException e) { e.printStackTrace(); return "Error in toString()"; } } private static IPluginModelBase findModel(IProject p) { // PluginRegistry is specific to Eclipse 3.3+. Use PDECore for compatibility with 3.2 // return PluginRegistry.findModel(p); return PDECore.getDefault().getModelManager().findModel(p); } private static IPluginModelBase findModel(BundleDescription bd) { // PluginRegistry is specific to Eclipse 3.3+. Use PDECore for compatibility with 3.2 // return PluginRegistry.findModel(bd); return PDECore.getDefault().getModelManager().findModel(bd); } }
12,736
33.611413
100
java
WALA
WALA-master/ide/src/main/java/com/ibm/wala/ide/util/HeadlessUtil.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.ide.util; import com.ibm.wala.classLoader.ModuleEntry; import com.ibm.wala.ide.classloader.EclipseSourceFileModule; import com.ibm.wala.util.debug.Assertions; import com.ibm.wala.util.io.CommandLine; import java.util.HashMap; import java.util.Map; import java.util.Properties; import java.util.Set; import java.util.function.Function; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IProject; import org.eclipse.core.resources.IWorkspaceRoot; import org.eclipse.core.resources.ResourcesPlugin; import org.eclipse.core.runtime.IPath; public class HeadlessUtil { /** * create a Properties object representing the properties set by the command line args. if args[i] * is "-foo" and args[i+1] is "bar", then the result will define a property with key "foo" and * value "bar" */ public static Properties parseCommandLine(String[] cmdLine) { if (cmdLine == null) { throw new IllegalArgumentException("null cmdLine"); } if (cmdLine.length == 0) { throw new IllegalArgumentException("cmdLine must have at least one parameter"); } Properties p = null; assert cmdLine[0].equals("-pdelaunch"); String[] x = new String[cmdLine.length - 1]; System.arraycopy(cmdLine, 1, x, 0, x.length); try { p = CommandLine.parse(x); } catch (IllegalArgumentException e) { e.printStackTrace(); System.err.println("Length " + x.length); for (String s : x) { System.err.println(s); } Assertions.UNREACHABLE(); } return p; } protected static <X> X getProjectFromWorkspace(Function<IProject, X> pred) { IWorkspaceRoot workspaceRoot = ResourcesPlugin.getWorkspace().getRoot(); IPath workspaceRootPath = workspaceRoot.getLocation(); System.out.println("workspace: " + workspaceRootPath.toOSString()); for (IProject p : workspaceRoot.getProjects()) { X result = pred.apply(p); if (result != null) { return result; } } Assertions.UNREACHABLE(); return null; } public interface EclipseCompiler<Unit> { Unit getCompilationUnit(IFile file); Parser<Unit> getParser(); } public interface Parser<Unit> { void setProject(IProject project); void processASTs(Map<Unit, EclipseSourceFileModule> files, Function<Object[], Boolean> errors); } public static <Unit> void parseModules(Set<ModuleEntry> modules, EclipseCompiler<Unit> compiler) { // sort files into projects Map<IProject, Map<Unit, EclipseSourceFileModule>> projectsFiles = new HashMap<>(); for (ModuleEntry m : modules) { if (m instanceof EclipseSourceFileModule) { EclipseSourceFileModule entry = (EclipseSourceFileModule) m; IProject proj = entry.getIFile().getProject(); if (!projectsFiles.containsKey(proj)) { projectsFiles.put(proj, new HashMap<>()); } projectsFiles.get(proj).put(compiler.getCompilationUnit(entry.getIFile()), entry); } } final Parser<Unit> parser = compiler.getParser(); for (final Map.Entry<IProject, Map<Unit, EclipseSourceFileModule>> proj : projectsFiles.entrySet()) { parser.setProject(proj.getKey()); parser.processASTs( proj.getValue(), problems -> { int length = problems.length; if (length > 0) { StringBuilder buffer = new StringBuilder(); for (Object problem : problems) { buffer.append(problem.toString()); buffer.append('\n'); } if (length != 0) { System.err.println(buffer); return true; } } return false; }); } } }
4,127
32.024
100
java
WALA
WALA-master/ide/src/main/java/com/ibm/wala/ide/util/ProgressMonitorDelegate.java
/* * Copyright (c) 2011 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package com.ibm.wala.ide.util; import com.ibm.wala.util.MonitorUtil.IProgressMonitor; /** A Wrapper around an Eclipse IProgressMonitor */ public class ProgressMonitorDelegate implements IProgressMonitor { public static ProgressMonitorDelegate createProgressMonitorDelegate( org.eclipse.core.runtime.IProgressMonitor d) { if (d == null) { throw new IllegalArgumentException("d is null"); } return new ProgressMonitorDelegate(d); } private final org.eclipse.core.runtime.IProgressMonitor delegate; private ProgressMonitorDelegate(org.eclipse.core.runtime.IProgressMonitor d) { this.delegate = d; } @Override public void beginTask(String task, int totalWork) { delegate.beginTask(task, totalWork); } @Override public boolean isCanceled() { return delegate.isCanceled(); } @Override public void done() { delegate.done(); } @Override public void worked(int units) { delegate.worked(units); } /* BEGIN Custom change: subtasks and canceling */ @Override public void subTask(String subTask) { delegate.subTask(subTask); } @Override public void cancel() { delegate.setCanceled(true); } /* END Custom change: subtasks and canceling */ @Override public String getCancelMessage() { return "cancelled by eclipse monitor: " + delegate.toString(); } }
1,728
24.426471
80
java
WALA
WALA-master/ide/tests/src/test/java/com/ibm/wala/examples/drivers/IFDSExplorerExample.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.Language; import com.ibm.wala.core.tests.callGraph.CallGraphTestUtil; import com.ibm.wala.core.tests.util.TestConstants; import com.ibm.wala.dataflow.IFDS.TabulationResult; import com.ibm.wala.examples.analysis.dataflow.ContextSensitiveReachingDefs; import com.ibm.wala.ide.ui.IFDSExplorer; 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.CallGraphBuilderCancelException; import com.ibm.wala.ipa.callgraph.Entrypoint; import com.ibm.wala.ipa.callgraph.IAnalysisCacheView; import com.ibm.wala.ipa.callgraph.impl.Util; import com.ibm.wala.ipa.callgraph.propagation.InstanceKey; import com.ibm.wala.ipa.cfg.BasicBlockInContext; import com.ibm.wala.ipa.cha.ClassHierarchyFactory; import com.ibm.wala.ipa.cha.IClassHierarchy; import com.ibm.wala.ssa.analysis.IExplodedBasicBlock; import com.ibm.wala.util.WalaException; import com.ibm.wala.util.collections.Pair; import com.ibm.wala.util.io.CommandLine; import java.io.IOException; import java.util.Properties; /** * An example of using {@link IFDSExplorer}. We visualize the result of running {@link * ContextSensitiveReachingDefs} on a simple test example. * * <p>NOTE: On Mac OS X, this class must be run with the JVM argument `-XstartOnFirstThread`, as * that is required for SWT applications on the Mac. */ public class IFDSExplorerExample { /** * Usage: {@code IFDSExplorerExample -dotExe <path_to_dot_exe> -viewerExe <path_to_viewer_exe>} */ public static void main(String[] args) throws IOException, IllegalArgumentException, CallGraphBuilderCancelException, WalaException { Properties p = CommandLine.parse(args); AnalysisScope scope = CallGraphTestUtil.makeJ2SEAnalysisScope( TestConstants.WALA_TESTDATA, "Java60RegressionExclusions.txt"); IClassHierarchy cha = ClassHierarchyFactory.make(scope); Iterable<Entrypoint> entrypoints = com.ibm.wala.ipa.callgraph.impl.Util.makeMainEntrypoints(cha, "Ldataflow/StaticDataflow"); AnalysisOptions options = CallGraphTestUtil.makeAnalysisOptions(scope, entrypoints); IAnalysisCacheView cache = new AnalysisCacheImpl(); CallGraphBuilder<InstanceKey> builder = Util.makeZeroOneCFABuilder(Language.JAVA, options, cache, cha); System.out.println("building CG"); CallGraph cg = builder.makeCallGraph(options, null); System.out.println("done with CG"); System.out.println("computing reaching defs"); ContextSensitiveReachingDefs reachingDefs = new ContextSensitiveReachingDefs(cg); TabulationResult<BasicBlockInContext<IExplodedBasicBlock>, CGNode, Pair<CGNode, Integer>> result = reachingDefs.analyze(); System.out.println("done with reaching defs"); IFDSExplorer.setDotExe(p.getProperty("dotExe")); IFDSExplorer.setGvExe(p.getProperty("viewerExe")); IFDSExplorer.viewIFDS(result); } }
3,533
44.307692
100
java
WALA
WALA-master/ide/tests/src/test/java/com/ibm/wala/examples/drivers/SWTCallGraph.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.examples.properties.WalaExamplesProperties; import com.ibm.wala.ide.ui.SWTTreeViewer; import com.ibm.wala.ide.ui.ViewIRAction; import com.ibm.wala.ipa.callgraph.AnalysisCacheImpl; import com.ibm.wala.ipa.callgraph.AnalysisOptions; import com.ibm.wala.ipa.callgraph.AnalysisOptions.ReflectionOptions; import com.ibm.wala.ipa.callgraph.AnalysisScope; import com.ibm.wala.ipa.callgraph.CGNode; import com.ibm.wala.ipa.callgraph.CallGraph; import com.ibm.wala.ipa.callgraph.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.cha.ClassHierarchy; import com.ibm.wala.ipa.cha.ClassHierarchyFactory; import com.ibm.wala.properties.WalaProperties; import com.ibm.wala.util.WalaException; import com.ibm.wala.util.debug.Assertions; import com.ibm.wala.util.graph.GraphIntegrity; import com.ibm.wala.util.graph.InferGraphRoots; import com.ibm.wala.util.io.CommandLine; import java.io.File; import java.util.Properties; import java.util.jar.JarFile; import org.eclipse.jface.window.ApplicationWindow; /** * This application is a WALA client: it invokes an SWT TreeViewer to visualize a Call Graph * * @author sfink */ public class SWTCallGraph { private static final boolean CHECK_GRAPH = false; /** * Usage: SWTCallGraph -appJar [jar file name] * * <p>The "jar file name" should be something like "c:/temp/testdata/java_cup.jar" * * <p>If it's a directory, then we'll try to find all jar files under that directory. */ public static void main(String[] args) { Properties p = CommandLine.parse(args); PDFCallGraph.validateCommandLine(p); run(p); } /** * @param p should contain at least the following properties: * <ul> * <li>appJar should be something like "c:/temp/testdata/java_cup.jar" * <li>algorithm (optional) can be one of: * <ul> * <li>"ZERO_CFA" (default value) * <li>"RTA" * </ul> * </ul> */ public static ApplicationWindow run(Properties p) { try { String appJar = p.getProperty("appJar"); if (PDFCallGraph.isDirectory(appJar)) { appJar = PDFCallGraph.findJarFiles(new String[] {appJar}); } String exclusionFile = p.getProperty("exclusions"); AnalysisScope scope = AnalysisScopeReader.instance.makeJavaBinaryAnalysisScope( appJar, exclusionFile != null ? new File(exclusionFile) : new FileProvider().getFile(CallGraphTestUtil.REGRESSION_EXCLUSIONS)); ClassHierarchy cha = ClassHierarchyFactory.make(scope); Iterable<Entrypoint> entrypoints = null; try (final JarFile jar = new JarFile(appJar)) { if (jar.getManifest() != null) { String mainClass = jar.getManifest().getMainAttributes().getValue("Main-Class"); if (mainClass != null) { entrypoints = com.ibm.wala.ipa.callgraph.impl.Util.makeMainEntrypoints( cha, 'L' + mainClass.replace('.', '/')); } } } if (entrypoints == null) { entrypoints = com.ibm.wala.ipa.callgraph.impl.Util.makeMainEntrypoints(cha); } AnalysisOptions options = new AnalysisOptions(scope, entrypoints); options.setReflectionOptions(ReflectionOptions.ONE_FLOW_TO_CASTS_NO_METHOD_INVOKE); // // // build the call graph // // com.ibm.wala.ipa.callgraph.CallGraphBuilder<InstanceKey> builder = Util.makeZeroCFABuilder(Language.JAVA, options, new AnalysisCacheImpl(), cha, null, null); CallGraph cg = builder.makeCallGraph(options, null); System.out.println(CallGraphStats.getStats(cg)); if (CHECK_GRAPH) { GraphIntegrity.check(cg); } 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); // create and run the viewer final SWTTreeViewer<CGNode> v = new SWTTreeViewer<>(); v.setGraphInput(cg); v.setRootsInput(InferGraphRoots.inferRoots(cg)); v.getPopUpActions().add(new ViewIRAction<>(v, cg, psFile, dotFile, dotExe, gvExe)); v.run(); return v.getApplicationWindow(); } catch (Exception e) { e.printStackTrace(); return null; } } }
5,595
34.643312
100
java
WALA
WALA-master/ide/tests/src/test/java/com/ibm/wala/examples/drivers/SWTPointsTo.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.analysis.pointers.BasicHeapGraph; 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.ide.ui.SWTTreeViewer; import com.ibm.wala.ipa.callgraph.AnalysisCacheImpl; import com.ibm.wala.ipa.callgraph.AnalysisOptions; import com.ibm.wala.ipa.callgraph.AnalysisScope; import com.ibm.wala.ipa.callgraph.CallGraph; import com.ibm.wala.ipa.callgraph.Entrypoint; import com.ibm.wala.ipa.callgraph.impl.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.util.CancelException; import com.ibm.wala.util.WalaException; import com.ibm.wala.util.graph.Graph; import com.ibm.wala.util.graph.InferGraphRoots; import com.ibm.wala.util.io.CommandLine; import java.io.IOException; import java.util.Properties; import org.eclipse.jface.window.ApplicationWindow; /** * This application is a WALA client: it invokes an SWT TreeViewer to visualize a Points-To solution * * @author sfink */ public class SWTPointsTo { /** * Usage: SWTPointsTo -appJar [jar file name] The "jar file name" should be something like * "c:/temp/testdata/java_cup.jar" */ public static void main(String[] args) { Properties p = CommandLine.parse(args); PDFCallGraph.validateCommandLine(p); run(p.getProperty("appJar")); } /** @param appJar should be something like "c:/temp/testdata/java_cup.jar" */ public static ApplicationWindow run(String appJar) { try { Graph<Object> g = buildPointsTo(appJar); // create and run the viewer final SWTTreeViewer<Object> v = new SWTTreeViewer<>(); v.setGraphInput(g); v.setRootsInput(InferGraphRoots.inferRoots(g)); v.run(); return v.getApplicationWindow(); } catch (Exception e) { e.printStackTrace(); return null; } } public static Graph<Object> buildPointsTo(String appJar) throws WalaException, IllegalArgumentException, CancelException, IOException { AnalysisScope scope = AnalysisScopeReader.instance.makeJavaBinaryAnalysisScope( appJar, new FileProvider().getFile(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.makeVanillaZeroOneCFABuilder( Language.JAVA, options, new AnalysisCacheImpl(), cha, null, null); CallGraph cg = builder.makeCallGraph(options, null); PointerAnalysis<InstanceKey> pointerAnalysis = builder.getPointerAnalysis(); System.err.println(pointerAnalysis); return new BasicHeapGraph<>(pointerAnalysis, cg); } }
3,570
34.71
100
java
WALA
WALA-master/ide/tests/src/test/java/com/ibm/wala/examples/drivers/SWTTypeHierarchy.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.ide.ui.SWTTreeViewer; 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.types.ClassLoaderReference; import com.ibm.wala.util.collections.CollectionFilter; import com.ibm.wala.util.graph.Graph; import com.ibm.wala.util.graph.GraphSlicer; import com.ibm.wala.util.graph.InferGraphRoots; import com.ibm.wala.util.graph.impl.SlowSparseNumberedGraph; import java.util.Collection; import java.util.function.Predicate; import org.eclipse.jface.viewers.TreeViewer; import org.eclipse.jface.window.ApplicationWindow; /** * This is a simple example WALA application. It's neither efficient nor concise, but is intended to * demonstrate some basic framework concepts. * * <p>This application builds a type hierarchy visualizes it with an SWT {@link TreeViewer}. */ public class SWTTypeHierarchy { // This example takes one command-line argument, so args[1] should be the "-classpath" parameter static final int CLASSPATH_INDEX = 1; /** Usage: SWTTypeHierarchy -classpath [classpath] */ public static void main(String[] args) { // check that the command-line is kosher validateCommandLine(args); run(args[CLASSPATH_INDEX]); } public static ApplicationWindow run(String classpath) { try { 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); // create and run the viewer final SWTTreeViewer<IClass> v = new SWTTreeViewer<>(); v.setGraphInput(g); Collection<IClass> roots = InferGraphRoots.inferRoots(g); if (roots.size() < 1) { System.err.println("PANIC: roots.size()=" + roots.size()); System.exit(-1); } v.setRootsInput(roots); v.run(); return v.getApplicationWindow(); } catch (Exception e) { e.printStackTrace(); return null; } } /** * 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; } /** Restrict g to nodes from the Application loader */ static Graph<IClass> pruneForAppLoader(Graph<IClass> g) { Predicate<IClass> f = c -> c.getClassLoader().getReference().equals(ClassLoaderReference.Application); return pruneGraph(g, f); } /** Remove from a graph g any nodes that are not accepted by a {@link Predicate} */ 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)); } /** * 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. */ 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]); } } }
4,653
33.992481
100
java
WALA
WALA-master/ide/tests/src/test/java/com/ibm/wala/ide/test/Activator.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. * * WALA JDT Frontend is Copyright (c) 2008 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.ide.test; import org.eclipse.core.runtime.Plugin; import org.osgi.framework.BundleContext; /** The activator class controls the plug-in life cycle */ public class Activator extends Plugin { // The plug-in ID public static final String PLUGIN_ID = "com.ibm.wala.ide.tests"; // The shared instance private static Activator plugin; /** The constructor */ public Activator() {} /* * (non-Javadoc) * * @see org.eclipse.core.runtime.Plugins#start(org.osgi.framework.BundleContext) */ @Override public void start(BundleContext context) throws Exception { super.start(context); plugin = this; } /* * (non-Javadoc) * * @see org.eclipse.core.runtime.Plugin#stop(org.osgi.framework.BundleContext) */ @Override public void stop(BundleContext context) throws Exception { plugin = null; super.stop(context); } /** * Returns the shared instance * * @return the shared instance */ public static Activator getDefault() { return plugin; } }
2,952
33.337209
82
java
WALA
WALA-master/ide/tests/src/test/java/com/ibm/wala/ide/tests/SWTTreeViewerTest.java
/* * Copyright (c) 2021 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Manu Sridharan - initial API and implementation */ package com.ibm.wala.ide.tests; import com.ibm.wala.ide.ui.SWTTreeViewer; import com.ibm.wala.util.WalaException; import com.ibm.wala.util.collections.Pair; import com.ibm.wala.util.graph.Graph; import com.ibm.wala.util.graph.impl.BasicGraph; import java.util.Collection; import java.util.Collections; import org.junit.Test; public class SWTTreeViewerTest { @Test public void testJustOpen() throws WalaException { Pair<Graph<String>, Collection<String>> testGraphAndRoots = makeTestGraphAndRoots(); final SWTTreeViewer<String> v = new SWTTreeViewer<>(); v.setGraphInput(testGraphAndRoots.fst); v.setRootsInput(testGraphAndRoots.snd); v.justOpenForTest(); } private static Pair<Graph<String>, Collection<String>> makeTestGraphAndRoots() { String root = "root"; String leaf = "leaf"; Graph<String> result = new BasicGraph<>(); result.addNode(root); result.addNode(leaf); result.addEdge(root, leaf); return Pair.make(result, Collections.singleton(root)); } }
1,385
31.232558
88
java
WALA
WALA-master/ide/tests/src/testFixtures/java/com/ibm/wala/ide/tests/util/EclipseTestUtil.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.ide.tests.util; import java.io.File; import java.io.IOException; import java.lang.reflect.InvocationTargetException; import java.net.URL; import java.util.zip.ZipFile; import org.eclipse.core.resources.IProject; import org.eclipse.core.resources.IWorkspaceRoot; import org.eclipse.core.resources.ResourcesPlugin; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.FileLocator; import org.eclipse.core.runtime.IPath; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.NullProgressMonitor; import org.eclipse.core.runtime.Path; import org.eclipse.core.runtime.Plugin; import org.eclipse.ui.dialogs.IOverwriteQuery; import org.eclipse.ui.wizards.datatransfer.FileSystemStructureProvider; import org.eclipse.ui.wizards.datatransfer.IImportStructureProvider; import org.eclipse.ui.wizards.datatransfer.ImportOperation; import org.eclipse.ui.wizards.datatransfer.ZipFileStructureProvider; import org.osgi.framework.Bundle; public class EclipseTestUtil { public static class ZippedProjectData { public final Plugin sourcePlugin; public final String projectName; public final String zipFileName; public ZippedProjectData(Plugin sourcePlugin, String projectName, String zipFileName) throws IOException { this.sourcePlugin = sourcePlugin; this.projectName = projectName; this.zipFileName = zipFileName; open(); } private void open() throws IOException { importZippedProject(sourcePlugin, projectName, zipFileName, new NullProgressMonitor()); } public void close() { destroyProject(projectName); } } public static void importZippedProject( Plugin plugin, String projectName, String zipFileName, IProgressMonitor monitor) throws IOException { try (final ZipFile zipFile = getZipFile(plugin, zipFileName)) { createOpenProject(projectName); importZipfile(projectName, zipFile, monitor); } } public static void createOpenProject(String projectName) { IWorkspaceRoot root = getWorkspace(); IProject project = root.getProject(projectName); try { project.create(null); project.open(null); } catch (CoreException e) { e.printStackTrace(); } } public static void destroyProject(String projectName) { IWorkspaceRoot root = getWorkspace(); IProject project = root.getProject(projectName); try { project.delete(true, null); } catch (CoreException e) { e.printStackTrace(); } } public static void importProjectFromFilesystem( String projectName, File root, IProgressMonitor monitor) { FileSystemStructureProvider fs = FileSystemStructureProvider.INSTANCE; importProject(fs, monitor, projectName, root); } public static void importZipfile(String projectName, ZipFile zipFile, IProgressMonitor monitor) { ZipFileStructureProvider provider = new ZipFileStructureProvider(zipFile); importProject(provider, monitor, projectName, provider.getRoot()); try { zipFile.close(); } catch (IOException e) { e.printStackTrace(); } } protected static <T> void importProject( IImportStructureProvider provider, IProgressMonitor monitor, String projectName, T root) { IPath containerPath = getWorkspacePath().append(projectName).addTrailingSeparator(); ImportOperation importOp = new ImportOperation(containerPath, root, provider, pathString -> IOverwriteQuery.ALL); importOp.setCreateContainerStructure(false); importOp.setOverwriteResources(true); try { importOp.run(monitor); } catch (InvocationTargetException | InterruptedException e) { e.printStackTrace(); } } public static File getTestDataFile(Plugin plugin, String filename) { Bundle bundle = plugin.getBundle(); IPath path = new Path("src/test/resources").append(filename); URL url = FileLocator.find(bundle, path, null); assert url != null : bundle.toString() + " path " + path.toString(); try { URL fileURL = FileLocator.toFileURL(url); File file = new File(fileURL.getPath()); return file; } catch (IOException e) { reportException(e); } return null; } public static ZipFile getZipFile(Plugin plugin, String testArchive) { File file = getTestDataFile(plugin, testArchive); if (file != null) { try { return new ZipFile(file); } catch (IOException e) { reportException(e); } } return null; } public static IWorkspaceRoot getWorkspace() { return ResourcesPlugin.getWorkspace().getRoot(); } private static IPath getWorkspacePath() { return ResourcesPlugin.getWorkspace().getRoot().getFullPath(); } private static void reportException(Exception e) { // TODO: add to appropriate error log? Report differently ?? e.printStackTrace(); } }
5,284
30.837349
99
java
WALA
WALA-master/scandroid/src/main/java/org/scandroid/domain/CodeElement.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 under the terms listed below. * */ /* * * Copyright (c) 2009-2012, * * Adam Fuchs <afuchs@cs.umd.edu> * Avik Chaudhuri <avik@cs.umd.edu> * * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The names of the contributors may not be used to endorse or promote * products derived from this software without specific prior written * permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * */ package org.scandroid.domain; import java.util.Collections; import java.util.Set; public abstract class CodeElement { /* For a given value number, and enclosing call graph node, yield * the set of all CodeElements that that it may refer to (i.e., the * associated local variable and any instances it may refer to). */ public static Set<CodeElement> valueElements(int valueNumber) { // System.out.println("ValueNumber: " + valueNumber + ", Node: " + // node.getMethod().getSignature()); Set<CodeElement> elements = Collections.singleton(new LocalElement(valueNumber)); // PointerKey pk = new LocalPointerKey(node, valueNumber); // OrdinalSet<InstanceKey> m = pa.getPointsToSet(pk); // if(m != null) { // for(Iterator<InstanceKey> keyIter = m.iterator();keyIter.hasNext();) { // elements.add(new InstanceKeyElement(keyIter.next())); // } // } return elements; } @Override public abstract boolean equals(Object obj); @Override public abstract int hashCode(); }
3,027
38.324675
88
java
WALA
WALA-master/scandroid/src/main/java/org/scandroid/domain/DomainElement.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 under the terms listed below. * */ /* * * Copyright (c) 2009-2012, * * Adam Fuchs <afuchs@cs.umd.edu> * Avik Chaudhuri <avik@cs.umd.edu> * * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The names of the contributors may not be used to endorse or promote * products derived from this software without specific prior written * permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * */ package org.scandroid.domain; import org.scandroid.flow.types.FlowType; @SuppressWarnings("rawtypes") public class DomainElement { // the code element in question // alternate framing: the /current/ fact about the element public final CodeElement codeElement; // the taint (probably from some other point in the code) that affects the // code element in question // alternate framing: the /initial/ fact about the element public final FlowType taintSource; public DomainElement(CodeElement codeElement, FlowType taintSource) { this.codeElement = codeElement; this.taintSource = taintSource; } /* @Override public boolean equals(Object other) { if (other == null || !(other instanceof DomainElement)) return false; DomainElement otherDE = (DomainElement) other; if (taintSource != null) { return codeElement.equals(otherDE.codeElement) && taintSource.equals(otherDE.taintSource); } return codeElement.equals(otherDE.codeElement) && otherDE.taintSource == null; } @Override public int hashCode() { if (taintSource == null) return codeElement.hashCode(); return codeElement.hashCode() ^ taintSource.hashCode(); } */ @Override public String toString() { return codeElement.toString() + ", " + taintSource; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((codeElement == null) ? 0 : codeElement.hashCode()); result = prime * result + ((taintSource == null) ? 0 : taintSource.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; DomainElement other = (DomainElement) obj; if (codeElement == null) { if (other.codeElement != null) return false; } else if (!codeElement.equals(other.codeElement)) return false; if (taintSource == null) { if (other.taintSource != null) return false; } else if (!taintSource.equals(other.taintSource)) return false; return true; } }
4,061
33.717949
83
java