repo
stringlengths
1
191
file
stringlengths
23
351
code
stringlengths
0
5.32M
file_length
int64
0
5.32M
avg_line_length
float64
0
2.9k
max_line_length
int64
0
288k
extension_type
stringclasses
1 value
WALA
WALA-master/core/src/testSubjects/java/slice/TestCD2.java
/* * Copyright (c) 2006 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package slice; public class TestCD2 { static void doNothing(Object o) {} public static void main(String[] args) { Integer I = (Integer) new A().foo(); int i = I; if (i > 0) { System.out.println("X"); doNothing(I); if (i > 1) { System.out.println("Y"); } } } }
685
22.655172
72
java
WALA
WALA-master/core/src/testSubjects/java/slice/TestCD3.java
/* * Copyright (c) 2006 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package slice; public class TestCD3 { static void doNothing(Object o) {} public static void main(String[] args) { Integer I = (Integer) new A().foo(); int i = I; try { if (i > 0) { System.out.println("X"); if (i > 1) { System.out.println("Y"); } } } catch (Throwable e) { } doNothing(I); } }
739
22.125
72
java
WALA
WALA-master/core/src/testSubjects/java/slice/TestCD4.java
/* * Copyright (c) 2006 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package slice; public class TestCD4 { static void doNothing(int i) {} public static void main(String[] args) { int i = 3; int j = 4; int k = foo(i, j); doNothing(k); } static int foo(int i, int j) { int k = 0; if (i == 3) { k = 9; if (j != 4) { k = k + 1; } k = 8; } return k; } }
728
18.702703
72
java
WALA
WALA-master/core/src/testSubjects/java/slice/TestCD5.java
/* * Copyright (c) 2006 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package slice; public class TestCD5 { public static void main(String[] args) { int i = 0; while (someBool()) { ++i; if (i >= 3) { return; } } } public static boolean someBool() { return false; } }
618
20.344828
72
java
WALA
WALA-master/core/src/testSubjects/java/slice/TestCD6.java
/* * Copyright (c) 2006 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package slice; public class TestCD6 { public static void main(String[] args) { int i = 0; if (someBool()) { i = 3; } else { i = 4; } doNothing(i); } public static void doNothing(int i) {} public static boolean someBool() { return false; } }
659
20.290323
72
java
WALA
WALA-master/core/src/testSubjects/java/slice/TestFields.java
/* * Copyright (c) 2006 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package slice; public class TestFields { private static void doNothing(Object o) {} /** slice should include a1 and o1, exclude a2 and o2 */ public static void main(String[] args) { Object o1 = new Object(); Object o2 = new Object(); A a1 = new A(); A a2 = new A(); a1.f = o1; a2.f = o2; Object o3 = a1.f; doNothing(o3); } }
736
24.413793
72
java
WALA
WALA-master/core/src/testSubjects/java/slice/TestGlobal.java
/* * Copyright (c) 2006 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package slice; public class TestGlobal { static Object global1; static Object global2; static void copyGlobals() { global2 = global1; } static void doNothing(Object o) {} /** make sure global variables are being properly handled */ public static void main(String[] args) { global1 = new Object(); copyGlobals(); Object x = global2; doNothing(x); } }
760
22.060606
72
java
WALA
WALA-master/core/src/testSubjects/java/slice/TestId.java
/* * Copyright (c) 2006 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package slice; public class TestId { static Object id(Object x) { return x; } static void doNothing(Object o) {} /** check for context-sensitive handling of the identity function. o2 should be excluded */ public static void main(String[] args) { Object o1 = new Object(), o2 = new Object(); Object o3 = id(o1); id(o2); doNothing(o3); } }
742
24.62069
93
java
WALA
WALA-master/core/src/testSubjects/java/slice/TestInetAddr.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 slice; import java.net.InetAddress; import java.net.UnknownHostException; public class TestInetAddr { public static void main(String[] args) throws UnknownHostException { InetAddress.getLocalHost(); } }
590
25.863636
72
java
WALA
WALA-master/core/src/testSubjects/java/slice/TestIntegerValueOf.java
package slice; public class TestIntegerValueOf { static int getInt() { return 0; } static void doNothing(Object o) {} public static void main(String[] args) { Integer i = Integer.valueOf(getInt()); doNothing(i); } }
242
14.1875
42
java
WALA
WALA-master/core/src/testSubjects/java/slice/TestList.java
package slice; import java.util.ArrayList; import java.util.List; public class TestList { static void doNothing(Object o) {} public static void main(String[] args) { List<Integer> list = new ArrayList<>(); list.add(2); list.add(3); doNothing(list.get(0)); } }
288
14.210526
43
java
WALA
WALA-master/core/src/testSubjects/java/slice/TestListIterator.java
package slice; import java.util.ArrayList; import java.util.List; public class TestListIterator { static void doNothing(Object o) {} public static void main(String[] args) { List<Integer> list = new ArrayList<>(); list.add(1); for (Integer i : list) { doNothing(i); } } }
304
15.944444
43
java
WALA
WALA-master/core/src/testSubjects/java/slice/TestMessageFormat.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 slice; import java.text.MessageFormat; public class TestMessageFormat { public static void main(String args[]) { MessageFormat.format(null, (Object[]) null); } }
549
25.190476
72
java
WALA
WALA-master/core/src/testSubjects/java/slice/TestMultiTarget.java
/* * Copyright (c) 2006 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package slice; public class TestMultiTarget { static void doNothing(Object o) {} /** test a virtual call with multiple targets. slice should include statements assigning to a */ public static void main(String[] args) { A a = null; if (args[0] == null) { a = new A(); } else { a = new B(); } Object x = a.foo(); doNothing(x); } }
744
24.689655
98
java
WALA
WALA-master/core/src/testSubjects/java/slice/TestPrimGetterSetter.java
/* * Copyright (c) 2006 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package slice; public class TestPrimGetterSetter { static class IntWrapper { int i; int getI() { return i; } void setI(int i) { this.i = i; } } public static void doNothing(int i) {} public static void main(String[] args) { IntWrapper w = new IntWrapper(); test(w); } public static void test(IntWrapper w) { int x = 3; w.setI(x); int y = w.getI(); doNothing(y); // slice on y } }
825
19.146341
72
java
WALA
WALA-master/core/src/testSubjects/java/slice/TestPrimGetterSetter2.java
/* * Copyright (c) 2006 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package slice; public class TestPrimGetterSetter2 { static class IntWrapper { int i; int getI() { return i; } void setI(int i) { this.i = i; } } public static void doNothing(int i) {} public static void main(String[] args) { IntWrapper w1 = new IntWrapper(); w1.setI(4); IntWrapper w2 = new IntWrapper(); w2.setI(5); w2.getI(); doNothing(w1.getI()); } }
794
19.921053
72
java
WALA
WALA-master/core/src/testSubjects/java/slice/TestRecursion.java
/* * Copyright (c) 2006 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package slice; public class TestRecursion { static Object find(A a, Object o) { if (o == null) { return a; } else { return find((A) a.f, o); } } static void doNothing(Object o) {} /** test of recursion. Everything for a1, a2, and a3 should be included */ public static void main(String[] args) { A a1 = new A(), a2 = new A(), a3 = new A(); a1.f = a2; a2.f = a3; Object x = find(a1, args[0]); doNothing(x); } }
838
23.676471
76
java
WALA
WALA-master/core/src/testSubjects/java/slice/TestThin1.java
/* * Copyright (c) 2006 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package slice; public class TestThin1 { private static void doNothing(Object o) {} /** slice should not include any statements relating to base pointers */ public static void main(String[] args) { Object o1 = new Object(); A a1 = new A(); A a2 = new A(); a1.f = a2; a2.g = o1; A a3 = (A) a1.f; Object o3 = a3.g; doNothing(o3); } }
742
24.62069
74
java
WALA
WALA-master/core/src/testSubjects/java/slice/TestThrowCatch.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 slice; public class TestThrowCatch { static class MyException extends Exception { int state; MyException(int state) { this.state = state; } } public static void callee(int x) throws MyException { if (x < 3) { MyException exp = new MyException(x); throw exp; } } public static void doNothing(int x) {} public static void main(String args[]) { try { callee(7); } catch (MyException e) { int x = e.state; doNothing(x); } } }
887
20.142857
72
java
WALA
WALA-master/core/src/testSubjects/java/special/A.java
package special; class A { String name; A() { setX("silly"); } public void setX(String name) { this.name = name; } @Override public String toString() { return name; } interface Ctor<T> { T make(); } public static void main(String[] args) { Ctor<A> o = A::new; Object a = o.make(); a.toString(); } }
357
11.344828
42
java
WALA
WALA-master/core/src/testSubjects/java/staticInit/TestStaticInit.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 staticInit; /** @author manu */ public class TestStaticInit { private static class A { static { doNothing(); } private static void doNothing() {} } public static void main(String[] args) { new A(); } }
613
20.172414
72
java
WALA
WALA-master/core/src/testSubjects/java/staticInit/TestStaticInitOrder.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 staticInit; public class TestStaticInitOrder { private static class A { static int f; static { doNothing(); } private static void doNothing() { B.b = 3; } } private static class B { static int b; static { foo(); } private static void foo() {} } private static class C extends B { static int c = 5; public static void dostuff() { c++; } } public static void main(String[] args) { A.f = 3; A.f++; C.dostuff(); B.b = 13; B.b = 14; C.dostuff(); A.f++; } }
956
15.789474
72
java
WALA
WALA-master/core/src/testSubjects/java/staticInit/TestSystemProperties.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 staticInit; public class TestSystemProperties { public static void main(String[] args) { char sep = System.getProperty("file.separator").toCharArray()[0]; } }
545
27.736842
72
java
WALA
WALA-master/core/src/testSubjects/java/staticInterfaceMethod/InterfaceWithStaticMethod.java
package staticInterfaceMethod; public interface InterfaceWithStaticMethod { static void test() {} }
103
16.333333
44
java
WALA
WALA-master/core/src/testSubjects/java/string/SimpleStringOps.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 string; public class SimpleStringOps { private static void whatever(String s) { System.out.println(s.substring(5) + " and other garbage"); } public static void main(String[] args) { if (args.length > 0) { String s = args[0]; for (int i = 1; i < args.length; i++) { s = s + args[i]; } if (s.length() < 6) { s = "a silly prefix " + s; } whatever(s); } } }
807
22.764706
72
java
WALA
WALA-master/core/src/testSubjects/java/stringConcat/StringConcat.java
package stringConcat; public class StringConcat { String testConcat() { String s1 = "thing 1"; String s2 = "thing 2"; String s3 = s1 + s2; return s3 + "foobar"; } public void main(String[] args) { testConcat(); } }
247
13.588235
35
java
WALA
WALA-master/core/src/testSubjects/java/typeInference/TI.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 typeInference; public class TI { public static void foo() { int[] x = new int[0]; System.out.println(x[0]); } public void bar(int x) { if (x > Integer.MIN_VALUE) { Integer.toString(x); throw new Error(); } } public void inferInt() { if (time() < time()) { throw new Error(); } } private static long time() { return System.currentTimeMillis(); } public void useCast(Object o) { String s = (String) o; System.out.println(s); } }
882
20.536585
72
java
WALA
WALA-master/dalvik/models/src/ActivityModelActivity.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, * * Steve Suh <suhsteve@gmail.com> * * 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 activity.model; import android.app.Activity; /** @deprecated building the Android-Livecycle is done in the class AndroidModel now */ @Deprecated public class ActivityModelActivity extends Activity { /* |, /, \ flow down * ^ flow up , <= flow left, => flow right * * onCreate(...) * | * ================> onStart() * ^ / \ * ^ onStop() <==== onResume() <====== * ^ / \ ^<==== | ^ * ^ <= onRestart() onDestroy() ^<= onPause() => ^ * | * (kill) * */ public void ActivityModel() { // is null correct for savedInstanceState? // com.galois.ReadsContactApp.ReadsContactApp rca = new // com.galois.ReadsContactApp.ReadsContactApp(); } }
2,770
35.946667
87
java
WALA
WALA-master/dalvik/src/main/java/com/ibm/wala/dalvik/analysis/typeInference/DalvikTypeInference.java
package com.ibm.wala.dalvik.analysis.typeInference; import com.ibm.wala.analysis.typeInference.TypeAbstraction; import com.ibm.wala.analysis.typeInference.TypeInference; import com.ibm.wala.analysis.typeInference.TypeVariable; import com.ibm.wala.fixpoint.AbstractOperator; import com.ibm.wala.ssa.IR; import com.ibm.wala.ssa.SSAPhiInstruction; import com.ibm.wala.ssa.SymbolTable; public class DalvikTypeInference extends TypeInference { @Override protected TypeVariable[] makeStmtRHS(int size) { return new DalvikTypeVariable[size]; } private static final AbstractOperator<TypeVariable> dalvikPhiOp = new DalvikPhiOperator(); protected DalvikTypeInference(IR ir, boolean doPrimitives) { super(ir, doPrimitives); } @Override protected void initialize() { init(ir, this.new DalvikTypeVarFactory(), this.new TypeOperatorFactory()); } public static DalvikTypeInference make(IR ir, boolean doPrimitives) { return new DalvikTypeInference(ir, doPrimitives); } public class DalvikTypeVarFactory extends TypeInference.TypeVarFactory { @Override public TypeVariable makeVariable(int valueNumber) { SymbolTable st = ir.getSymbolTable(); if (st.isIntegerConstant(valueNumber) && st.isZero(valueNumber)) { return new DalvikTypeVariable(language.getPrimitive(language.getConstantType(0)), true); } else { if (doPrimitives) { if (st.isConstant(valueNumber)) { if (st.isBooleanConstant(valueNumber)) { return new DalvikTypeVariable( language.getPrimitive(language.getConstantType(Boolean.TRUE))); } } } return new DalvikTypeVariable(TypeAbstraction.TOP); } } } protected class TypeOperatorFactory extends TypeInference.TypeOperatorFactory { @Override public void visitPhi(SSAPhiInstruction instruction) { assert dalvikPhiOp != null; this.result = dalvikPhiOp; } } private static final class DalvikPhiOperator extends AbstractOperator<TypeVariable> { private DalvikPhiOperator() {} @Override public byte evaluate(TypeVariable _lhs, TypeVariable[] _rhs) { /* * TODO: Find a better solution than downcasting. Downcasting is really ugly, although I can * be sure here that it succeeds because I control what type the parameters have. There must * be a cleaner solution which does not cause tons of changes in WALA's code, but I don't see * it yet... */ assert _lhs instanceof DalvikTypeVariable; assert _rhs instanceof DalvikTypeVariable[]; DalvikTypeVariable lhs = (DalvikTypeVariable) _lhs; DalvikTypeVariable[] rhs = (DalvikTypeVariable[]) _rhs; TypeAbstraction lhsType = lhs.getType(); TypeAbstraction meet = TypeAbstraction.TOP; boolean ignoreZero = containsNonPrimitiveAndZero(rhs); for (DalvikTypeVariable rh : rhs) { if (rh != null && rh.getType() != null && !(ignoreZero && rh.isIntZeroConstant())) { meet = meet.meet(rh.getType()); } } if (lhsType.equals(meet)) { return NOT_CHANGED; } else { lhs.setType(meet); return CHANGED; } } private static boolean containsNonPrimitiveAndZero(DalvikTypeVariable[] types) { boolean containsNonPrimitive = false; boolean containsZero = false; for (DalvikTypeVariable type : types) { if (type != null) { if (type.getType() != null && type.getType().getTypeReference() != null && !type.getType().getTypeReference().isPrimitiveType()) { containsNonPrimitive = true; } if (type.isIntZeroConstant()) { containsZero = true; } } } return containsNonPrimitive && containsZero; } @Override public String toString() { return "phi meet (dalvik)"; } @Override public int hashCode() { return 2297; } @Override public boolean equals(Object o) { return (o instanceof DalvikPhiOperator); } } }
4,121
31.456693
99
java
WALA
WALA-master/dalvik/src/main/java/com/ibm/wala/dalvik/analysis/typeInference/DalvikTypeVariable.java
package com.ibm.wala.dalvik.analysis.typeInference; import com.ibm.wala.analysis.typeInference.TypeAbstraction; import com.ibm.wala.analysis.typeInference.TypeVariable; public class DalvikTypeVariable extends TypeVariable { private final boolean isIntZeroConstant; public DalvikTypeVariable(TypeAbstraction type, boolean isIntZeroConstant) { super(type); this.isIntZeroConstant = isIntZeroConstant; } public DalvikTypeVariable(TypeAbstraction type) { this(type, false); } public boolean isIntZeroConstant() { return isIntZeroConstant; } }
574
25.136364
78
java
WALA
WALA-master/dalvik/src/main/java/com/ibm/wala/dalvik/classLoader/DexCFG.java
/* * Copyright (c) 2002 - 2006, 2011 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 * Steve Suh <suhsteve@gmail.com> - Modified to handle dalvik instructions */ package com.ibm.wala.dalvik.classLoader; import com.ibm.wala.cfg.AbstractCFG; import com.ibm.wala.cfg.BytecodeCFG; import com.ibm.wala.cfg.IBasicBlock; import com.ibm.wala.classLoader.BytecodeLanguage; import com.ibm.wala.classLoader.IClass; import com.ibm.wala.classLoader.IClassLoader; import com.ibm.wala.classLoader.IMethod; import com.ibm.wala.classLoader.JavaLanguage; import com.ibm.wala.core.util.shrike.ShrikeUtil; import com.ibm.wala.core.util.warnings.Warning; import com.ibm.wala.core.util.warnings.Warnings; import com.ibm.wala.dalvik.dex.instructions.Instruction; import com.ibm.wala.dalvik.dex.instructions.Invoke; import com.ibm.wala.dalvik.dex.instructions.Return; import com.ibm.wala.dalvik.dex.instructions.Throw; import com.ibm.wala.ipa.callgraph.Context; import com.ibm.wala.ipa.cha.IClassHierarchy; import com.ibm.wala.shrike.shrikeBT.ExceptionHandler; import com.ibm.wala.shrike.shrikeCT.InvalidClassFileException; import com.ibm.wala.types.ClassLoaderReference; import com.ibm.wala.types.MethodReference; import com.ibm.wala.types.TypeReference; import com.ibm.wala.util.collections.ArrayIterator; import com.ibm.wala.util.collections.HashSetFactory; import com.ibm.wala.util.debug.Assertions; import com.ibm.wala.util.graph.impl.NodeWithNumber; import com.ibm.wala.util.intset.BitVector; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Iterator; import java.util.Set; public class DexCFG extends AbstractCFG<Instruction, DexCFG.BasicBlock> implements BytecodeCFG { private static final boolean DEBUG = false; private int[] instruction2Block; private final DexIMethod dexMethod; private final Context context; private static int totalEdges = 0; /** Cache this here for efficiency */ private final int hashBase; /** Set of Shrike {@link ExceptionHandler} objects that cover this method. */ private final Set<ExceptionHandler> exceptionHandlers = HashSetFactory.make(10); protected DexCFG(DexIMethod method, Context context) throws IllegalArgumentException { super(method); if (method == null) { throw new IllegalArgumentException("method cannot be null"); } this.dexMethod = method; this.context = context; this.hashBase = method.hashCode() * 9967; makeBasicBlocks(); init(); computeI2BMapping(); computeEdges(); } public DexIMethod getDexMethod() { return dexMethod; } public static int getTotalEdges() { return totalEdges; } @Override public int hashCode() { return 9511 * getMethod().hashCode(); } @Override public boolean equals(Object o) { // return (o instanceof DexCFG) && getMethod().equals(((DexCFG) o).getMethod()); return o instanceof DexCFG && ((DexCFG) o).dexMethod.equals(dexMethod) && ((DexCFG) o).context.equals(context); } @Override public Instruction[] getInstructions() { return dexMethod.getDexInstructions(); } /** * Compute a mapping from instruction to basic block. Also, compute the blocks that end with a * 'normal' return. */ private void computeI2BMapping() { instruction2Block = new int[getInstructions().length]; for (BasicBlock b : this) { for (int j = b.getFirstInstructionIndex(); j <= b.getLastInstructionIndex(); j++) { instruction2Block[j] = getNumber(b); } } } /** Compute outgoing edges in the control flow graph. */ private void computeEdges() { for (BasicBlock b : this) { if (b.equals(exit())) { continue; } else if (b.equals(entry())) { BasicBlock bb0 = getBlockForInstruction(0); assert bb0 != null; addNormalEdge(b, bb0); } else { b.computeOutgoingEdges(); } } } private void makeBasicBlocks() { ExceptionHandler[][] handlers; handlers = dexMethod.getHandlers(); boolean[] r = new boolean[getInstructions().length]; boolean[] catchers = new boolean[getInstructions().length]; // we initially start with both the entry and exit block. @SuppressWarnings("UnusedVariable") int blockCount = 2; // Compute r so r[i] == true iff instruction i begins a basic block. // While doing so count the number of blocks. r[0] = true; Instruction[] instructions = getInstructions(); for (int i = 0; i < instructions.length; i++) { int[] targets = instructions[i].getBranchTargets(); // if there are any targets, then break the basic block here. // also break the basic block after a return if (targets.length > 0 || !instructions[i].isFallThrough()) { if (i + 1 < instructions.length && !r[i + 1]) { r[i + 1] = true; blockCount++; } } for (int target : targets) { if (!r[target]) { r[target] = true; blockCount++; } } if (instructions[i].isPEI()) { ExceptionHandler[] hs = handlers[i]; // break the basic block here. if (i + 1 < instructions.length && !r[i + 1]) { r[i + 1] = true; blockCount++; } if (hs != null) { for (ExceptionHandler h : hs) { exceptionHandlers.add(h); if (!r[h.getHandler()]) { // we have not discovered the catch block yet. // form a new basic block r[h.getHandler()] = true; blockCount++; } catchers[h.getHandler()] = true; } } } } BasicBlock entry = new BasicBlock(-1); addNode(entry); int j = 1; for (int i = 0; i < r.length; i++) { if (r[i]) { BasicBlock b = new BasicBlock(i); addNode(b); if (catchers[i]) { setCatchBlock(j); } j++; } } BasicBlock exit = new BasicBlock(-1); addNode(exit); } /** * Return an instruction's basic block in the CFG given the index of the instruction in the CFG's * instruction array. */ @Override public BasicBlock getBlockForInstruction(int index) { return getNode(instruction2Block[index]); } public final class BasicBlock extends NodeWithNumber implements IBasicBlock<Instruction> { /** The number of the ShrikeBT instruction that begins this block. */ private final int startIndex; public BasicBlock(int startIndex) { this.startIndex = startIndex; } @Override public boolean isCatchBlock() { return DexCFG.this.isCatchBlock(getNumber()); } private void computeOutgoingEdges() { if (DEBUG) { System.err.println("Block " + this + ": computeOutgoingEdges()"); } Instruction last = getInstructions()[getLastInstructionIndex()]; int[] targets = last.getBranchTargets(); for (int target : targets) { BasicBlock b = getBlockForInstruction(target); addNormalEdgeTo(b); } addExceptionalEdges(last); if (last.isFallThrough()) { BasicBlock next = getNode(getNumber() + 1); addNormalEdgeTo(next); } if (last instanceof Return) { // link each return instruction to the exit block. BasicBlock exit = exit(); addNormalEdgeTo(exit); } } /** * Add any exceptional edges generated by the last instruction in a basic block. * * @param last the last instruction in a basic block. */ private void addExceptionalEdges(Instruction last) { IClassHierarchy cha = getMethod().getClassHierarchy(); if (last.isPEI()) { Collection<TypeReference> exceptionTypes = null; boolean goToAllHandlers = false; ExceptionHandler[] hs = getExceptionHandlers(); if (last instanceof Throw) { // this class does not have the type information needed // to determine what the athrow throws. So, add an // edge to all reachable handlers. Better information can // be obtained later with SSA type propagation. // TODO: consider pruning to only the exception types that // this method either catches or allocates, since these are // the only types that can flow to an athrow. goToAllHandlers = true; } else { if (hs != null && hs.length > 0) { IClassLoader loader = getMethod().getDeclaringClass().getClassLoader(); BytecodeLanguage l = (BytecodeLanguage) loader.getLanguage(); // exceptionTypes = l.getImplicitExceptionTypes(last); exceptionTypes = getImplicitExceptionTypes(last); if (last instanceof Invoke) { Invoke call = (Invoke) last; exceptionTypes = HashSetFactory.make(exceptionTypes); MethodReference target = MethodReference.findOrCreate( l, loader.getReference(), call.clazzName, call.methodName, call.descriptor); try { exceptionTypes.addAll(l.inferInvokeExceptions(target, cha)); } catch (InvalidClassFileException e) { e.printStackTrace(); Assertions.UNREACHABLE(); } IMethod mTarget = cha.resolveMethod(target); if (mTarget == null) { goToAllHandlers = true; } } } } if (hs != null && hs.length > 0) { // found a handler for this PEI // create a mutable copy if (!goToAllHandlers) { exceptionTypes = HashSetFactory.make(exceptionTypes); } for (ExceptionHandler element : hs) { if (DEBUG) { System.err.println(" handler " + element); } BasicBlock b = getBlockForInstruction(element.getHandler()); if (DEBUG) { System.err.println(" target " + b); } if (goToAllHandlers) { // add an edge to the catch block. if (DEBUG) { System.err.println(" gotoAllHandlers " + b); } addExceptionalEdgeTo(b); } else { TypeReference caughtException = null; if (element.getCatchClass() != null) { ClassLoaderReference loader = DexCFG.this.getMethod().getDeclaringClass().getReference().getClassLoader(); caughtException = ShrikeUtil.makeTypeReference(loader, element.getCatchClass()); if (DEBUG) { System.err.println(" caughtException " + caughtException); } IClass caughtClass = cha.lookupClass(caughtException); if (caughtClass == null) { // conservatively add the edge, and raise a warning addExceptionalEdgeTo(b); Warnings.add(FailedExceptionResolutionWarning.create(caughtException)); // null out caughtException, to avoid attempting to process it caughtException = null; } } else { if (DEBUG) { System.err.println(" catchClass() == null"); } // hs[j].getCatchClass() == null. // this means that the handler catches all exceptions. // add the edge and null out all types if (!exceptionTypes.isEmpty()) { addExceptionalEdgeTo(b); exceptionTypes.clear(); assert caughtException == null; } } if (caughtException != null) { IClass caughtClass = cha.lookupClass(caughtException); // the set "caught" should be the set of exceptions that MUST // have been caught by the handlers in scope ArrayList<TypeReference> caught = new ArrayList<>(exceptionTypes.size()); // check if we should add an edge to the catch block. for (TypeReference t : exceptionTypes) { if (t != null) { IClass klass = cha.lookupClass(t); if (klass == null) { Warnings.add(FailedExceptionResolutionWarning.create(caughtException)); // conservatively add an edge addExceptionalEdgeTo(b); } else { boolean subtype1 = cha.isSubclassOf(klass, caughtClass); if (subtype1 || cha.isSubclassOf(caughtClass, klass)) { // add the edge and null out the type from the array addExceptionalEdgeTo(b); if (subtype1) { caught.add(t); } } } } } exceptionTypes.removeAll(caught); } } } // if needed, add an edge to the exit block. if (exceptionTypes == null || !exceptionTypes.isEmpty()) { BasicBlock exit = exit(); addExceptionalEdgeTo(exit); } } else { // found no handler for this PEI ... link to the exit block. BasicBlock exit = exit(); addExceptionalEdgeTo(exit); } } } /** * @param pei a potentially-excepting instruction * @return the exception types that pei may throw, independent of the class hierarchy. null if * none. * <p>Notes * <ul> * <li>this method will <em>NOT</em> return the exception type explicitly thrown by an * athrow * <li>this method will <em>NOT</em> return the exception types that a called method may * throw * <li>this method ignores OutOfMemoryError * <li>this method ignores linkage errors * <li>this method ignores IllegalMonitorState exceptions * </ul> * * @throws IllegalArgumentException if pei is null */ public Collection<TypeReference> getImplicitExceptionTypes(Instruction pei) { if (pei == null) { throw new IllegalArgumentException("pei is null"); } switch (pei.getOpcode()) { // TODO: Make sure all the important cases and exceptions are covered. case AGET: case AGET_WIDE: case AGET_OBJECT: case AGET_BOOLEAN: case AGET_BYTE: case AGET_CHAR: case AGET_SHORT: // case OP_iaload: // case OP_laload: // case OP_faload: // case OP_daload: // case OP_aaload: // case OP_baload: // case OP_caload: // case OP_saload: case APUT: case APUT_WIDE: // case APUT_OBJECT: case APUT_BOOLEAN: case APUT_BYTE: case APUT_CHAR: case APUT_SHORT: // case OP_iastore: // case OP_lastore: // case OP_fastore: // case OP_dastore: // case OP_bastore: // case OP_castore: // case OP_sastore: return JavaLanguage.getArrayAccessExceptions(); case APUT_OBJECT: // case OP_aastore: return JavaLanguage.getAaStoreExceptions(); case IGET: case IGET_WIDE: case IGET_OBJECT: case IGET_BOOLEAN: case IGET_BYTE: case IGET_CHAR: case IGET_SHORT: // case OP_getfield: case IPUT: case IPUT_WIDE: case IPUT_OBJECT: case IPUT_BOOLEAN: case IPUT_BYTE: case IPUT_CHAR: case IPUT_SHORT: // case OP_putfield: // Shrike imp does not include the static invoke calls, so likewise will do the same case INVOKE_VIRTUAL: case INVOKE_SUPER: case INVOKE_DIRECT: // case INVOKE_STATIC: case INVOKE_INTERFACE: case INVOKE_VIRTUAL_RANGE: case INVOKE_SUPER_RANGE: case INVOKE_DIRECT_RANGE: // case INVOKE_STATIC_RANGE: case INVOKE_INTERFACE_RANGE: // case OP_invokevirtual: // case OP_invokespecial: // case OP_invokeinterface: case ARRAY_LENGTH: // case OP_arraylength: case MONITOR_ENTER: case MONITOR_EXIT: // case OP_monitorenter: // case OP_monitorexit: // we're currently ignoring MonitorStateExceptions, since J2EE stuff // should be // logically single-threaded case THROW: // case OP_athrow: // N.B: the caller must handle the explicitly-thrown exception return JavaLanguage.getNullPointerException(); case DIV_INT: case DIV_INT_2ADDR: case DIV_INT_LIT16: case DIV_INT_LIT8: case REM_INT: case REM_INT_2ADDR: case REM_INT_LIT16: case REM_INT_LIT8: case DIV_LONG: case DIV_LONG_2ADDR: case REM_LONG: case REM_LONG_2ADDR: // case OP_idiv: // case OP_irem: // case OP_ldiv: // case OP_lrem: return JavaLanguage.getArithmeticException(); case NEW_INSTANCE: // case OP_new: return JavaLanguage.getNewScalarExceptions(); case NEW_ARRAY: case FILLED_NEW_ARRAY: case FILLED_NEW_ARRAY_RANGE: // case OP_newarray: // case OP_anewarray: // case OP_multianewarray: return JavaLanguage.getNewArrayExceptions(); case CHECK_CAST: // case OP_checkcast: return JavaLanguage.getClassCastException(); // I Don't think dalvik has to worry about this? // case OP_ldc_w: // if (((ConstantInstruction) pei).getType().equals(TYPE_Class)) // return JavaLanguage.getClassNotFoundException(); // else // return null; case SGET: case SGET_BOOLEAN: case SGET_BYTE: case SGET_CHAR: case SGET_OBJECT: case SGET_SHORT: case SGET_WIDE: case SPUT: case SPUT_BOOLEAN: case SPUT_BYTE: case SPUT_CHAR: case SPUT_OBJECT: case SPUT_SHORT: case SPUT_WIDE: // case OP_getstatic: // case OP_putstatic: return JavaLanguage.getExceptionInInitializerError(); default: return Collections.emptySet(); } } private ExceptionHandler[] getExceptionHandlers() { ExceptionHandler[][] handlers; handlers = dexMethod.getHandlers(); ExceptionHandler[] hs = handlers[getLastInstructionIndex()]; return hs; } private void addNormalEdgeTo(BasicBlock b) { totalEdges++; addNormalEdge(this, b); } private void addExceptionalEdgeTo(BasicBlock b) { totalEdges++; addExceptionalEdge(this, b); } @Override public int getLastInstructionIndex() { if (this == entry() || this == exit()) { // these are the special end blocks return -2; } if (getNumber() == (getMaxNumber() - 1)) { // this is the last non-exit block return getInstructions().length - 1; } else { BasicBlock next = getNode(getNumber() + 1); return next.getFirstInstructionIndex() - 1; } } @Override public int getFirstInstructionIndex() { return startIndex; } @Override public String toString() { return "BB[Dex]" + getNumber() + " - " + dexMethod.getDeclaringClass().getReference().getName() + '.' + dexMethod.getName(); } @Override public boolean isExitBlock() { return this == DexCFG.this.exit(); } @Override public boolean isEntryBlock() { return this == DexCFG.this.entry(); } @Override public IMethod getMethod() { return DexCFG.this.getMethod(); } @Override public int hashCode() { return hashBase + getNumber(); } @Override public boolean equals(Object o) { return (o instanceof BasicBlock) && ((BasicBlock) o).getMethod().equals(getMethod()) && ((BasicBlock) o).getNumber() == getNumber(); } @Override public int getNumber() { return getGraphNodeId(); } @Override public Iterator<Instruction> iterator() { return new ArrayIterator<>( getInstructions(), getFirstInstructionIndex(), getLastInstructionIndex()); } } @Override public String toString() { StringBuilder s = new StringBuilder(); BitVector catches = this.getCatchBlocks(); for (BasicBlock bb : this) { s.append("BB").append(getNumber(bb)); if (catches.contains(bb.getNumber())) { s.append("<Handler>"); } s.append('\n'); for (int j = bb.getFirstInstructionIndex(); j <= bb.getLastInstructionIndex(); j++) { s.append(" ").append(j).append(" ").append(getInstructions()[j]).append('\n'); } Iterator<BasicBlock> succNodes = getSuccNodes(bb); while (succNodes.hasNext()) { s.append(" -> BB").append(getNumber(succNodes.next())).append('\n'); } } return s.toString(); } public int getMaxStackHeight() { return dexMethod.getMaxStackHeight(); } public int getMaxLocals() { return dexMethod.getMaxLocals(); } @Override public Set<ExceptionHandler> getExceptionHandlers() { return exceptionHandlers; } /** @see com.ibm.wala.cfg.ControlFlowGraph#getProgramCounter(int) */ @Override public int getProgramCounter(int index) { return dexMethod.getAddressFromIndex(index); // return dexMethod.getInstructionFromIndex(index).pc; } /** A warning when we fail to resolve the type of an exception */ private static class FailedExceptionResolutionWarning extends Warning { final TypeReference T; FailedExceptionResolutionWarning(TypeReference T) { super(Warning.MODERATE); this.T = T; } @Override public String getMsg() { return getClass().toString() + " : " + T; } public static FailedExceptionResolutionWarning create(TypeReference T) { return new FailedExceptionResolutionWarning(T); } } }
23,044
31.968526
99
java
WALA
WALA-master/dalvik/src/main/java/com/ibm/wala/dalvik/classLoader/DexConstants.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 com.ibm.wala.dalvik.classLoader; public interface DexConstants { int ACC_private = 0x1; int ACC_PRIVATE = 0x2; int ACC_PROTECTED = 0x4; int ACC_STATIC = 0x8; int ACC_FINAL = 0x10; int ACC_SYNCHRONIZED = 0x20; int ACC_VOLATILE = 0x40; int ACC_BRIDGE = 0x40; int ACC_TRANSIENT = 0x80; int ACC_VARARGS = 0x80; int ACC_NATIVE = 0x100; int ACC_INTERFACE = 0x200; int ACC_ABSTRACT = 0x400; int ACC_STRICT = 0x800; int ACC_SYNTHETIC = 0x1000; int ACC_ANNOTATION = 0x2000; int ACC_ENUM = 0x4000; int ACC_UNUSED = 0x8000; int ACC_CONSTRUCTOR = 0x10000; int ACC_DECLARED_SYNCHRONIZED = 0x2000; int VALUE_BYTE = 0x00; int VALUE_SHORT = 0x02; int VALUE_CHAR = 0x03; int VALUE_INT = 0x04; int VALUE_LONG = 0x06; int VALUE_FLOAT = 0x10; int VALUE_DOUBLE = 0x11; int VALUE_STRING = 0x17; int VALUE_TYPE = 0x18; int VALUE_FIELD = 0x19; int VALUE_METHOD = 0x1a; int VALUE_ENUM = 0x1b; int VALUE_ARRAY = 0x1c; int VALUE_ANNOTATION = 0x1d; int VALUE_NULL = 0x1e; int VALUE_BOOLEAN = 0x1f; }
2,990
32.606742
79
java
WALA
WALA-master/dalvik/src/main/java/com/ibm/wala/dalvik/classLoader/DexFileModule.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, * * Jonathan Bardin <astrosus@gmail.com> * Steve Suh <suhsteve@gmail.com> * * 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.classLoader; import com.ibm.wala.classLoader.Module; import com.ibm.wala.classLoader.ModuleEntry; import com.ibm.wala.util.io.TemporaryFile; import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.util.Collection; import java.util.HashSet; import java.util.Iterator; import java.util.jar.JarFile; import org.jf.dexlib2.DexFileFactory; import org.jf.dexlib2.Opcodes; import org.jf.dexlib2.iface.ClassDef; import org.jf.dexlib2.iface.DexFile; /** * A module which is a wrapper around .dex and .apk file. * * @author barjo */ public class DexFileModule implements Module { private final File f; private final DexFile dexfile; private final Collection<ModuleEntry> entries; public static final int AUTO_INFER_API_LEVEL = -1; public static DexFileModule make(File f) throws IllegalArgumentException, IOException { return make(f, AUTO_INFER_API_LEVEL); } public static DexFileModule make(File f, int apiLevel) throws IllegalArgumentException, IOException { if (f.getName().endsWith("jar")) { try (final JarFile jar = new JarFile(f)) { return new DexFileModule(jar); } } else { return new DexFileModule(f, apiLevel); } } private static File tf(JarFile f) throws IOException { String name = f.getName(); if (name.indexOf('/') >= 0) { name = name.substring(name.lastIndexOf('/') + 1); } File tf = Files.createTempFile("name", "_classes.dex").toFile(); tf.deleteOnExit(); System.err.println("using " + tf); return tf; } private DexFileModule(JarFile f) throws IllegalArgumentException, IOException { this(TemporaryFile.streamToFile(tf(f), f.getInputStream(f.getEntry("classes.dex")))); } private DexFileModule(File f) throws IllegalArgumentException { this(f, AUTO_INFER_API_LEVEL); } /** @param f the .dex or .apk file */ private DexFileModule(File f, int apiLevel) throws IllegalArgumentException { try { this.f = f; dexfile = DexFileFactory.loadDexFile( f, apiLevel == AUTO_INFER_API_LEVEL ? null : Opcodes.forApi(apiLevel)); } catch (IOException e) { throw new IllegalArgumentException(e); } // create ModuleEntries from ClassDefItem entries = new HashSet<>(); for (ClassDef cdefitems : dexfile.getClasses()) { entries.add(new DexModuleEntry(cdefitems, this)); } } /** * @param f the .oat or .apk file * @param entry the name of the .dex file inside the container file * @param apiLevel the api level wanted */ public DexFileModule(File f, String entry, int apiLevel) throws IllegalArgumentException { try { this.f = f; dexfile = DexFileFactory.loadDexEntry( f, entry, true, apiLevel == AUTO_INFER_API_LEVEL ? null : Opcodes.forApi(apiLevel)) .getDexFile(); } catch (IOException e) { throw new IllegalArgumentException(e); } // create ModuleEntries from ClassDefItem entries = new HashSet<>(); for (ClassDef cdefitems : dexfile.getClasses()) { entries.add(new DexModuleEntry(cdefitems, this)); } } public DexFileModule(File f, String entry) throws IllegalArgumentException { this(f, entry, AUTO_INFER_API_LEVEL); } /** @return The DexFile associated to this module. */ public DexFile getDexFile() { return dexfile; } /** @return The DexFile associated to this module. */ public File getFile() { return f; } /* * (non-Javadoc) * * @see com.ibm.wala.classLoader.Module#getEntries() */ @Override public Iterator<ModuleEntry> getEntries() { return entries.iterator(); } }
5,701
30.854749
92
java
WALA
WALA-master/dalvik/src/main/java/com/ibm/wala/dalvik/classLoader/DexIClass.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, * * Jonathan Bardin <astrosus@gmail.com> * Steve Suh <suhsteve@gmail.com> * * 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.classLoader; import static org.jf.dexlib2.AccessFlags.ABSTRACT; import static org.jf.dexlib2.AccessFlags.INTERFACE; import static org.jf.dexlib2.AccessFlags.PRIVATE; import static org.jf.dexlib2.AccessFlags.PUBLIC; import static org.jf.dexlib2.AccessFlags.SYNTHETIC; import com.ibm.wala.classLoader.BytecodeClass; import com.ibm.wala.classLoader.IClassLoader; import com.ibm.wala.classLoader.IField; import com.ibm.wala.classLoader.IMethod; import com.ibm.wala.core.util.strings.ImmutableByteArray; import com.ibm.wala.ipa.cha.IClassHierarchy; import com.ibm.wala.types.TypeReference; import com.ibm.wala.types.annotations.Annotation; import com.ibm.wala.util.collections.HashMapFactory; import com.ibm.wala.util.collections.HashSetFactory; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Map; import java.util.Set; import org.jf.dexlib2.AnnotationVisibility; import org.jf.dexlib2.iface.ClassDef; import org.jf.dexlib2.iface.Field; import org.jf.dexlib2.iface.Method; import org.jf.dexlib2.iface.MethodParameter; public class DexIClass extends BytecodeClass<IClassLoader> { /** Item which contains the class definitions. (compute by DexFile, from the dexLib) */ private final ClassDef classDef; /** * Bitfields of these flags are used to indicate the accessibility and overall properties of * classes and class members. i.e. public/private/abstract/interface. */ private final int modifiers; private IMethod[] methods = null; // private int construcorId = -1; private int clinitId = -1; private final DexModuleEntry dexModuleEntry; // public IClassLoader loader; public DexIClass(IClassLoader loader, IClassHierarchy cha, final DexModuleEntry dexEntry) { super(loader, cha); this.dexModuleEntry = dexEntry; classDef = dexEntry.getClassDefItem(); // this.loader = loader; // Set modifiers modifiers = classDef.getAccessFlags(); // computerTypeReference() // Set typeReference typeReference = TypeReference.findOrCreate(loader.getReference(), dexEntry.getClassName()); // set hashcode hashCode = 2161 * getReference().hashCode(); // computeSuperName() // Set Super Name; String descriptor = classDef.getSuperclass() != null ? classDef.getSuperclass() : null; if (descriptor != null && descriptor.endsWith(";")) descriptor = descriptor.substring(0, descriptor.length() - 1); // remove last ';' superName = descriptor != null ? ImmutableByteArray.make(descriptor) : null; // computeInterfaceNames() // Set interfaceNames final List<String> intfList = classDef.getInterfaces(); int size = intfList == null ? 0 : intfList.size(); // if (size != 0) // System.out.println(intfList.getTypes().get(0).getTypeDescriptor()); interfaceNames = new ImmutableByteArray[size]; for (int i = 0; i < size; i++) { descriptor = intfList.get(i); if (descriptor.endsWith(";")) descriptor = descriptor.substring(0, descriptor.length() - 1); interfaceNames[i] = ImmutableByteArray.make(descriptor); } // Set direct instance fields // if (classData == null) { // throw new RuntimeException("DexIClass::DexIClass(): classData is null"); // } // final EncodedField[] encInstFields = classData.getInstanceFields(); // size = encInstFields==null?0:encInstFields.length; // instanceFields = new IField[size]; // for (int i = 0; i < size; i++) { // //name of instance field. // //System.out.println(encInstFields[i].field.getFieldName().getStringValue()); // //name of field type. // //System.out.println(encInstFields[i].field.getFieldType().getTypeDescriptor()); // instanceFields[i] = new DexIField(encInstFields[i],this); // } // // // Set direct static fields // final EncodedField[] encStatFields = classData.getStaticFields(); // size = encStatFields==null?0:encStatFields.length; // staticFields = new IField[size]; // for (int i = 0; i < size; i++) { // //name of static field // //System.out.println(encInstFields[i].field.getFieldName().getStringValue()); // staticFields[i] = new DexIField(encStatFields[i],this); // } // computeFields() // final EncodedField[] encInstFields = classData.getInstanceFields(); final Iterable<? extends Field> encInstFields = classDef.getInstanceFields(); List<IField> ifs = new ArrayList<>(); for (Field dexf : encInstFields) { ifs.add(new DexIField(dexf, this)); } instanceFields = ifs.toArray(new IField[0]); // Set direct static fields final Iterable<? extends Field> encStatFields = classDef.getStaticFields(); List<IField> sfs = new ArrayList<>(); for (Field dexf : encStatFields) { sfs.add(new DexIField(dexf, this)); } staticFields = sfs.toArray(new IField[0]); } /** @return The classDef Item associated with this class. */ public ClassDef getClassDefItem() { return classDef; } /* * (non-Javadoc) * @see com.ibm.wala.classLoader.IClass#isPublic() */ @Override public boolean isPublic() { return (modifiers & PUBLIC.getValue()) != 0; } /* * (non-Javadoc) * @see com.ibm.wala.classLoader.IClass#isPrivate() */ @Override public boolean isPrivate() { return (modifiers & PRIVATE.getValue()) != 0; } /* * (non-Javadoc) * @see com.ibm.wala.classLoader.IClass#isInterface() */ @Override public boolean isInterface() { return (modifiers & INTERFACE.getValue()) != 0; } /** @see com.ibm.wala.classLoader.IClass#isAbstract() */ @Override public boolean isAbstract() { return (modifiers & ABSTRACT.getValue()) != 0; } /** @see com.ibm.wala.classLoader.IClass#isAbstract() */ @Override public boolean isSynthetic() { return (modifiers & SYNTHETIC.getValue()) != 0; } /* * (non-Javadoc) * @see com.ibm.wala.classLoader.IClass#getModifiers() */ @Override public int getModifiers() throws UnsupportedOperationException { return modifiers; } /** @see java.lang.Object#equals(Object) */ @Override public boolean equals(Object obj) { // it's ok to use instanceof since this class is final // if (this.getClass().equals(obj.getClass())) { if (obj instanceof DexIClass) { return getReference().equals(((DexIClass) obj).getReference()); } else { return false; } } @Override public int hashCode() { return hashCode; } Collection<Annotation> getAnnotations(Set<String> types) { Set<Annotation> result = HashSetFactory.make(); for (org.jf.dexlib2.iface.Annotation a : classDef.getAnnotations()) { if (types == null || types.contains(AnnotationVisibility.getVisibility(a.getVisibility()))) { result.add(DexUtil.getAnnotation(a, getClassLoader().getReference())); } } return result; } @Override public Collection<Annotation> getAnnotations() { return getAnnotations((Set<String>) null); } @Override public Collection<Annotation> getAnnotations(boolean runtimeInvisible) { return getAnnotations(getTypes(runtimeInvisible)); } static Set<String> getTypes(boolean runtimeInvisible) { Set<String> types = HashSetFactory.make(); types.add(AnnotationVisibility.getVisibility(AnnotationVisibility.SYSTEM)); if (runtimeInvisible) { types.add(AnnotationVisibility.getVisibility(AnnotationVisibility.BUILD)); } else { types.add(AnnotationVisibility.getVisibility(AnnotationVisibility.RUNTIME)); } return types; } List<Annotation> getAnnotations(Method m, Set<String> set) { List<Annotation> result = new ArrayList<>(); for (org.jf.dexlib2.iface.Annotation a : m.getAnnotations()) { if (set == null || set.contains(AnnotationVisibility.getVisibility(a.getVisibility()))) { result.add(DexUtil.getAnnotation(a, getClassLoader().getReference())); } } return result; } Collection<Annotation> getAnnotations(Field m) { List<Annotation> result = new ArrayList<>(); for (org.jf.dexlib2.iface.Annotation a : m.getAnnotations()) { result.add(DexUtil.getAnnotation(a, getClassLoader().getReference())); } return result; } Map<Integer, List<Annotation>> getParameterAnnotations(Method m) { Map<Integer, List<Annotation>> result = HashMapFactory.make(); int i = 0; for (MethodParameter as : m.getParameters()) { for (org.jf.dexlib2.iface.Annotation a : as.getAnnotations()) { if (!result.containsKey(i)) { result.put(i, new ArrayList<>()); } result.get(i).add(DexUtil.getAnnotation(a, getClassLoader().getReference())); } i++; } return result; } /* * (non-Javadoc) * @see com.ibm.wala.classLoader.BytecodeClass#computeDeclaredMethods() */ @Override protected IMethod[] computeDeclaredMethods() { ArrayList<IMethod> methodsAL = new ArrayList<>(); if (methods == null) { // final EncodedMethod[] directMethods = // classDef.getClassData().getDirectMethods(); // final EncodedMethod[] virtualMethods = // classDef.getClassData().getVirtualMethods(); final Iterable<? extends Method> directMethods = classDef.getDirectMethods(); final Iterable<? extends Method> virtualMethods = classDef.getVirtualMethods(); // methods = new IMethod[dSize+vSize]; // Create Direct methods (static, private, constructor) int i = 0; for (Method dMethod : directMethods) { // methods[i] = new DexIMethod(dMethod,this); DexIMethod method = new DexIMethod(dMethod, this); methodsAL.add(method); // Set construcorId // if ( (dMethod.accessFlags & CONSTRUCTOR.getValue()) != 0){ // construcorId = i; // } // Set clinitId // if (methods[i].isClinit()) if (method.isClinit()) { clinitId = i; } i++; } // Create virtual methods (other methods) for (Method dexm : virtualMethods) { // methods[dSize+i] = new DexIMethod(virtualMethods[i],this); methodsAL.add(new DexIMethod(dexm, this)); // is this enough to determine if the class is an activity? // maybe check superclass? -- but that may also not be enough // may need to keep checking superclass of superclass, etc. } } if (methods == null) methods = methodsAL.toArray(new IMethod[0]); return methods; } /* * (non-Javadoc) * @see com.ibm.wala.classLoader.IClass#getClassInitializer() */ @Override public IMethod getClassInitializer() { if (methods == null) { computeDeclaredMethods(); } // return construcorId!=-1?methods[construcorId]:null; return clinitId != -1 ? methods[clinitId] : null; } @Override public DexFileModule getContainer() { return dexModuleEntry.getContainer(); } }
13,073
33.13577
99
java
WALA
WALA-master/dalvik/src/main/java/com/ibm/wala/dalvik/classLoader/DexIContextInterpreter.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> * Steve Suh <suhsteve@gmail.com> * * 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.classLoader; import com.ibm.wala.cfg.ControlFlowGraph; import com.ibm.wala.classLoader.CallSiteReference; import com.ibm.wala.classLoader.IClass; import com.ibm.wala.classLoader.NewSiteReference; import com.ibm.wala.ipa.callgraph.CGNode; import com.ibm.wala.ipa.callgraph.IAnalysisCacheView; import com.ibm.wala.ipa.callgraph.propagation.SSAContextInterpreter; 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 java.util.Iterator; public class DexIContextInterpreter implements SSAContextInterpreter { public DexIContextInterpreter(IAnalysisCacheView cache) { this.cache = cache; } private final IAnalysisCacheView cache; @Override public boolean understands(CGNode node) { if (node.getMethod() instanceof DexIMethod) return true; return false; } @Override public boolean recordFactoryType(CGNode node, IClass klass) { // TODO what the heck does this mean? // com.ibm.wala.core/src/com/ibm/wala/analysis/reflection/JavaLangClassContextInterpreter.java // has this set to false return false; // throw new RuntimeException("not yet implemented"); } @Override public Iterator<NewSiteReference> iterateNewSites(CGNode node) { return getIR(node).iterateNewSites(); } @Override public Iterator<FieldReference> iterateFieldsWritten(CGNode node) { // TODO implement this! throw new RuntimeException("not yet implemented"); } @Override public Iterator<FieldReference> iterateFieldsRead(CGNode node) { // TODO implement this! throw new RuntimeException("not yet implemented"); } @Override public Iterator<CallSiteReference> iterateCallSites(CGNode node) { return getIR(node).iterateCallSites(); } @Override public int getNumberOfStatements(CGNode node) { // TODO verify this is correct assert understands(node); return getIR(node).getInstructions().length; } @Override public IR getIR(CGNode node) { // new Exception("getting IR for method // "+node.getMethod().getReference().toString()).printStackTrace(); return cache.getIR(node.getMethod(), node.getContext()); } @Override public IRView getIRView(CGNode node) { return getIR(node); } @Override public DefUse getDU(CGNode node) { return cache.getDefUse(getIR(node)); // return new DefUse(getIR(node)); } @Override public ControlFlowGraph<SSAInstruction, ISSABasicBlock> getCFG(CGNode n) { IR ir = getIR(n); return ir.getControlFlowGraph(); } }
4,669
31.887324
98
java
WALA
WALA-master/dalvik/src/main/java/com/ibm/wala/dalvik/classLoader/DexIField.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, * * Jonathan Bardin <astrosus@gmail.com> * Steve Suh <suhsteve@gmail.com> * * 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.classLoader; import static org.jf.dexlib2.AccessFlags.*; import com.ibm.wala.classLoader.IClass; import com.ibm.wala.classLoader.IField; import com.ibm.wala.core.util.strings.Atom; import com.ibm.wala.ipa.cha.IClassHierarchy; import com.ibm.wala.types.FieldReference; import com.ibm.wala.types.TypeName; import com.ibm.wala.types.TypeReference; import com.ibm.wala.types.annotations.Annotation; import java.util.Collection; import org.jf.dexlib2.iface.Field; public class DexIField implements IField { /* * The EncodedFied object for which this DexIField is a wrapper */ private final Field eField; /** The declaring class for this method. */ private final DexIClass myClass; // /** name of the return type for this method, construct in the get return type method. */ // private TypeReference typeReference; /** * canonical FieldReference corresponding to this method, construct in the getReference method. */ private FieldReference fieldReference; private final FieldReference myFieldRef; private final Atom name; public DexIField(Field encodedField, DexIClass klass) { // public DexIField(EncodedField encodedField) { eField = encodedField; myClass = klass; String fieldName = eField.getName(); name = Atom.findOrCreateUnicodeAtom(fieldName); String fieldType = eField.getType(); TypeName T = DexUtil.getTypeName(fieldType); TypeReference type = TypeReference.findOrCreate(myClass.getClassLoader().getReference(), T); myFieldRef = FieldReference.findOrCreate(myClass.getReference(), name, type); } @Override public TypeReference getFieldTypeReference() { // compute the typeReference from the EncodedField // if (typeReference == null) { // typeReference = TypeReference.findOrCreate(myClass.getClassLoader() // .getReference(), eField.field.getFieldType().getTypeDescriptor()); // } // return typeReference; return myFieldRef.getFieldType(); } @Override public FieldReference getReference() { if (fieldReference == null) { // fieldReference = FieldReference.findOrCreate(myClass.getReference(), // eField.field.getContainingClass().getTypeDescriptor(), // eField.field.getFieldName().getStringValue(), // eField.field.getFieldType().getTypeDescriptor()); fieldReference = FieldReference.findOrCreate(myClass.getReference(), getName(), getFieldTypeReference()); } return fieldReference; } @Override public Atom getName() { return name; } @Override public boolean isFinal() { return (eField.getAccessFlags() & FINAL.getValue()) != 0; } @Override public boolean isPrivate() { return (eField.getAccessFlags() & PRIVATE.getValue()) != 0; } @Override public boolean isProtected() { return (eField.getAccessFlags() & PROTECTED.getValue()) != 0; } @Override public boolean isPublic() { return (eField.getAccessFlags() & PUBLIC.getValue()) != 0; } @Override public boolean isStatic() { return (eField.getAccessFlags() & STATIC.getValue()) != 0; } @Override public IClass getDeclaringClass() { return myClass; } @Override public boolean isVolatile() { return (eField.getAccessFlags() & VOLATILE.getValue()) != 0; } @Override public IClassHierarchy getClassHierarchy() { return myClass.getClassHierarchy(); } @Override public Collection<Annotation> getAnnotations() { return myClass.getAnnotations(eField); } }
5,545
30.691429
98
java
WALA
WALA-master/dalvik/src/main/java/com/ibm/wala/dalvik/classLoader/DexIMethod.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. * * dexlib2 update: Julian Dolby (dolby@us.ibm.com) * */ /* * * Copyright (c) 2009-2012, * * Jonathan Bardin <astrosus@gmail.com> * Steve Suh <suhsteve@gmail.com> * * 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.classLoader; import static org.jf.dexlib2.AccessFlags.ABSTRACT; import static org.jf.dexlib2.AccessFlags.ANNOTATION; import static org.jf.dexlib2.AccessFlags.BRIDGE; import static org.jf.dexlib2.AccessFlags.DECLARED_SYNCHRONIZED; import static org.jf.dexlib2.AccessFlags.ENUM; import static org.jf.dexlib2.AccessFlags.FINAL; import static org.jf.dexlib2.AccessFlags.NATIVE; import static org.jf.dexlib2.AccessFlags.PRIVATE; import static org.jf.dexlib2.AccessFlags.PROTECTED; import static org.jf.dexlib2.AccessFlags.PUBLIC; import static org.jf.dexlib2.AccessFlags.STATIC; import static org.jf.dexlib2.AccessFlags.SYNTHETIC; import static org.jf.dexlib2.AccessFlags.VOLATILE; import com.google.common.collect.ImmutableMap; import com.ibm.wala.classLoader.CallSiteReference; import com.ibm.wala.classLoader.IBytecodeMethod; import com.ibm.wala.classLoader.IClass; import com.ibm.wala.classLoader.NewSiteReference; import com.ibm.wala.core.util.strings.Atom; import com.ibm.wala.core.util.strings.ImmutableByteArray; import com.ibm.wala.dalvik.dex.instructions.ArrayFill; import com.ibm.wala.dalvik.dex.instructions.ArrayGet; import com.ibm.wala.dalvik.dex.instructions.ArrayGet.Type; 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.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.PackedSwitchPad; import com.ibm.wala.dalvik.dex.instructions.PutField; import com.ibm.wala.dalvik.dex.instructions.Return; import com.ibm.wala.dalvik.dex.instructions.SparseSwitchPad; 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.dalvik.dex.instructions.UnaryOperation.OpID; import com.ibm.wala.ipa.cha.IClassHierarchy; import com.ibm.wala.shrike.shrikeBT.ExceptionHandler; import com.ibm.wala.shrike.shrikeBT.IndirectionData; import com.ibm.wala.types.ClassLoaderReference; import com.ibm.wala.types.Descriptor; import com.ibm.wala.types.MethodReference; import com.ibm.wala.types.Selector; import com.ibm.wala.types.TypeName; import com.ibm.wala.types.TypeReference; import com.ibm.wala.types.annotations.Annotation; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.NavigableMap; import java.util.Set; import java.util.TreeMap; import org.jf.dexlib2.DebugItemType; import org.jf.dexlib2.Opcode; import org.jf.dexlib2.analysis.ClassPath; import org.jf.dexlib2.analysis.ClassPathResolver; import org.jf.dexlib2.analysis.MethodAnalyzer; import org.jf.dexlib2.iface.AnnotationElement; import org.jf.dexlib2.iface.Method; import org.jf.dexlib2.iface.TryBlock; import org.jf.dexlib2.iface.debug.DebugItem; import org.jf.dexlib2.iface.debug.LineNumber; import org.jf.dexlib2.iface.instruction.SwitchPayload; import org.jf.dexlib2.iface.instruction.TwoRegisterInstruction; import org.jf.dexlib2.iface.instruction.formats.ArrayPayload; import org.jf.dexlib2.iface.instruction.formats.Instruction10t; import org.jf.dexlib2.iface.instruction.formats.Instruction11n; import org.jf.dexlib2.iface.instruction.formats.Instruction11x; import org.jf.dexlib2.iface.instruction.formats.Instruction12x; import org.jf.dexlib2.iface.instruction.formats.Instruction20t; import org.jf.dexlib2.iface.instruction.formats.Instruction21c; import org.jf.dexlib2.iface.instruction.formats.Instruction21ih; import org.jf.dexlib2.iface.instruction.formats.Instruction21lh; import org.jf.dexlib2.iface.instruction.formats.Instruction21s; import org.jf.dexlib2.iface.instruction.formats.Instruction21t; import org.jf.dexlib2.iface.instruction.formats.Instruction22b; import org.jf.dexlib2.iface.instruction.formats.Instruction22c; import org.jf.dexlib2.iface.instruction.formats.Instruction22s; import org.jf.dexlib2.iface.instruction.formats.Instruction22t; import org.jf.dexlib2.iface.instruction.formats.Instruction22x; import org.jf.dexlib2.iface.instruction.formats.Instruction23x; import org.jf.dexlib2.iface.instruction.formats.Instruction30t; import org.jf.dexlib2.iface.instruction.formats.Instruction31c; import org.jf.dexlib2.iface.instruction.formats.Instruction31i; import org.jf.dexlib2.iface.instruction.formats.Instruction31t; import org.jf.dexlib2.iface.instruction.formats.Instruction32x; import org.jf.dexlib2.iface.instruction.formats.Instruction35c; import org.jf.dexlib2.iface.instruction.formats.Instruction3rc; import org.jf.dexlib2.iface.instruction.formats.Instruction51l; import org.jf.dexlib2.iface.reference.FieldReference; import org.jf.dexlib2.iface.reference.StringReference; import org.jf.dexlib2.iface.value.ArrayEncodedValue; import org.jf.dexlib2.iface.value.EncodedValue; import org.jf.dexlib2.iface.value.TypeEncodedValue; import org.jf.dexlib2.immutable.ImmutableDexFile; import org.jf.dexlib2.immutable.ImmutableMultiDexContainer; /** A wrapper around a EncodedMethod object (from dexlib) that represents a method. */ public class DexIMethod implements IBytecodeMethod<Instruction> { /** The EncodedMethod object for which this DexIMethod is a wrapper. */ private final Method eMethod; /** The declaring class for this method. */ protected final DexIClass myClass; /** * canonical MethodReference corresponding to this method, construct in the getReference method. */ private MethodReference methodReference; /** name of the return type for this method, construct in the get return type method. */ private TypeReference typeReference; private ExceptionHandler[][] handlers; protected InstructionArray instructions; private static int totalInsts = 0; public DexIMethod(Method encodedMethod, DexIClass klass) { eMethod = encodedMethod; myClass = klass; } public static int getTotalInsts() { return totalInsts; } // ------------------------------------------ // Specific methods // ------------------------------------------ /** @return the EncodedMethod object for which this DexIMethod is a wrapper. */ public Method toEncodedMethod() { return eMethod; } // ------------------------------------------- // IMethod methods // ------------------------------------------- @Override public TypeReference[] getDeclaredExceptions() throws UnsupportedOperationException { /* BEGIN Custom change: Variable Names in synth. methods */ if (myClass.getClassDefItem().getAnnotations() == null) { return null; } ArrayList<String> strings = new ArrayList<>(); Set<? extends org.jf.dexlib2.iface.Annotation> annotationSet = eMethod.getAnnotations(); /* END Custom change: Variable Names in synth. methods */ if (annotationSet != null) { for (org.jf.dexlib2.iface.Annotation annotationItem : annotationSet) { if (annotationItem.getType().contentEquals("Ldalvik/annotation/Throws;")) { for (AnnotationElement e : annotationItem.getElements()) { for (EncodedValue v : ((ArrayEncodedValue) e.getValue()).getValue()) { String tname = ((TypeEncodedValue) v).getValue(); if (tname.endsWith(";")) tname = tname.substring(0, tname.length() - 1); strings.add(tname); } } } } } if (strings.size() == 0) return null; ClassLoaderReference loader = getDeclaringClass().getClassLoader().getReference(); TypeReference[] result = new TypeReference[strings.size()]; Arrays.setAll( result, i -> TypeReference.findOrCreate( loader, TypeName.findOrCreate(ImmutableByteArray.make(strings.get(i))))); return result; } @Override public String getLocalVariableName(int bcIndex, int localNumber) { throw new UnsupportedOperationException("getLocalVariableName not implemented"); } /** * XXX not fully about the + 2. * * @return the RegisterCount + 2 to make some room for the return and exception register * @see com.ibm.wala.classLoader.ShrikeCTMethod#getMaxLocals() */ public int getMaxLocals() { return eMethod.getImplementation().getRegisterCount() + 2; } public int getReturnReg() { return eMethod.getImplementation().getRegisterCount(); } public int getExceptionReg() { return eMethod.getImplementation().getRegisterCount() + 1; } /* * (non-Javadoc) * @see com.ibm.wala.classLoader.IMethod#getMaxStackHeight() */ public int getMaxStackHeight() { throw new UnsupportedOperationException("Dex Methods does not use a stack"); } /* * (non-Javadoc) * @see com.ibm.wala.classLoader.IMethod#getDescriptor() */ @Override public Descriptor getDescriptor() { return getReference().getDescriptor(); } /* * (non-Javadoc) * @see com.ibm.wala.classLoader.IMethod#getNumberOfParameters() */ @Override public int getNumberOfParameters() { final int number; if (isStatic() || isClinit()) { number = getReference().getNumberOfParameters(); } else { number = getReference().getNumberOfParameters() + 1; } return number; } public int getNumberOfParameterRegisters() { int number = isStatic() || isClinit() ? 0 : 1; for (int i = 0; i < getReference().getNumberOfParameters(); i++) { TypeReference ref = getReference().getParameterType(i); number += ref.equals(TypeReference.Double) || ref.equals(TypeReference.Long) ? 2 : 1; } return number; } /* * (non-Javadoc) * @see com.ibm.wala.classLoader.IMethod#getParameterType(int) */ @Override public TypeReference getParameterType(int index) { if (!isStatic()) { if (index == 0) { return myClass.getReference(); } else { return getReference().getParameterType(index - 1); } } else { return getReference().getParameterType(index); } } /* * (non-Javadoc) * @see com.ibm.wala.classLoader.IMethod#getReference() */ @Override public MethodReference getReference() { // Compute the method reference from the MethodIdItem if (methodReference == null) { // Set method name Atom name = Atom.findOrCreateUnicodeAtom(eMethod.getName()); // // Set the descriptor // Descriptor descriptor = // Descriptor.findOrCreateUTF8(eMethod.method.getPrototype().getPrototypeString()); // methodReference = MethodReference.findOrCreate(myClass.getReference(),name, // descriptor); Descriptor D = Descriptor.findOrCreate( myClass.getClassLoader().getLanguage(), ImmutableByteArray.make(DexUtil.getSignature(eMethod))); methodReference = MethodReference.findOrCreate(myClass.getReference(), name, D); } return methodReference; } /* * (non-Javadoc) * @see com.ibm.wala.classLoader.IMethod#getReturnType() */ @Override public TypeReference getReturnType() { // compute the typeReference from the MethodIdItem if (typeReference == null) { typeReference = getReference().getReturnType(); } return typeReference; } /* * (non-Javadoc) * @see com.ibm.wala.classLoader.IMethod#getSelector() */ @Override public Selector getSelector() { return getReference().getSelector(); } /* * (non-Javadoc) * * @see com.ibm.wala.classLoader.IMethod#getSignature() */ @Override public String getSignature() { return getReference().getSignature(); } /* * (non-Javadoc) * @see com.ibm.wala.classLoader.IMethod#hasExceptionHandler() */ @Override public boolean hasExceptionHandler() { List<? extends TryBlock<? extends org.jf.dexlib2.iface.ExceptionHandler>> tries = eMethod.getImplementation().getTryBlocks(); return tries == null ? false : tries.size() > 0; } /* * (non-Javadoc) * @see com.ibm.wala.classLoader.IMethod#hasLocalVariableTable() */ @Override public boolean hasLocalVariableTable() { throw new UnsupportedOperationException( "DexIMethod: hasLocalVariableTable() not yet implemented"); // TODO Compute the local variable name from the DebugInfo Item // eMethod.codeItem.getDebugInfo() // return false; } /* * (non-Javadoc) * @see com.ibm.wala.classLoader.IMethod#isAbstract() */ @Override public boolean isAbstract() { return (eMethod.getAccessFlags() & ABSTRACT.getValue()) != 0; } /* * (non-Javadoc) * @see com.ibm.wala.classLoader.IMethod#isClinit() */ @Override public boolean isClinit() { return eMethod.getName().equals(MethodReference.clinitName.toString()); } /* * (non-Javadoc) * @see com.ibm.wala.classLoader.IMethod#isFinal() */ @Override public boolean isFinal() { return (eMethod.getAccessFlags() & FINAL.getValue()) != 0; } /* * (non-Javadoc) * @see com.ibm.wala.classLoader.IMethod#isInit() */ @Override public boolean isInit() { return eMethod.getName().equals(MethodReference.initAtom.toString()); } /* * (non-Javadoc) * @see com.ibm.wala.classLoader.IMethod#isNative() */ @Override public boolean isNative() { return (eMethod.getAccessFlags() & NATIVE.getValue()) != 0; } /* * (non-Javadoc) * @see com.ibm.wala.classLoader.IMethod#isBridge() */ @Override public boolean isBridge() { return (eMethod.getAccessFlags() & BRIDGE.getValue()) != 0; } /* * (non-Javadoc) * @see com.ibm.wala.classLoader.IMethod#isPrivate() */ @Override public boolean isPrivate() { return (eMethod.getAccessFlags() & PRIVATE.getValue()) != 0; } /* * (non-Javadoc) * @see com.ibm.wala.classLoader.IMethod#isProtected() */ @Override public boolean isProtected() { return (eMethod.getAccessFlags() & PROTECTED.getValue()) != 0; } /* * (non-Javadoc) * * @see com.ibm.wala.classLoader.IMethod#isPublic() */ @Override public boolean isPublic() { return (eMethod.getAccessFlags() & PUBLIC.getValue()) != 0; } /* * (non-Javadoc) * @see com.ibm.wala.classLoader.IMethod#isSynchronized() */ @Override public boolean isSynchronized() { return (eMethod.getAccessFlags() & DECLARED_SYNCHRONIZED.getValue()) != 0; } /* * (non-Javadoc) * @see com.ibm.wala.classLoader.IMethod#isWalaSynthetic() */ @Override public boolean isWalaSynthetic() { return false; } /* * (non-Javadoc) * @see com.ibm.wala.classLoader.IMethod#isSynthetic() */ @Override public boolean isSynthetic() { return (eMethod.getAccessFlags() & SYNTHETIC.getValue()) != 0; } /* * (non-Javadoc) * @see com.ibm.wala.classLoader.IMember#isStatic() */ @Override public boolean isStatic() { return (eMethod.getAccessFlags() & STATIC.getValue()) != 0; } /* * (non-Javadoc) * @see com.ibm.wala.classLoader.IMember#isVolatile() */ public boolean isVolatile() { return (eMethod.getAccessFlags() & VOLATILE.getValue()) != 0; } @Override public boolean isAnnotation() { return (eMethod.getAccessFlags() & ANNOTATION.getValue()) != 0; } @Override public boolean isEnum() { return (eMethod.getAccessFlags() & ENUM.getValue()) != 0; } @Override public boolean isModule() { // flag seems not to be in dexlib return false; } /* * (non-Javadoc) * @see com.ibm.wala.classLoader.IMember#getDeclaringClass() */ @Override public IClass getDeclaringClass() { return myClass; } /* * (non-Javadoc) * * @see com.ibm.wala.ipa.cha.IClassHierarchyDweller#getClassHierarchy() */ @Override public IClassHierarchy getClassHierarchy() { return myClass.getClassHierarchy(); } @Override public Atom getName() { return getReference().getName(); } private NavigableMap<Integer, Integer> sourceLines = null; @Override public int getLineNumber(int bcIndex) { if (sourceLines == null && eMethod.getImplementation() != null && eMethod.getImplementation().getDebugItems() != null) { sourceLines = new TreeMap<>(); int lineNumber = -1; for (DebugItem dbg : eMethod.getImplementation().getDebugItems()) { if (dbg.getDebugItemType() == DebugItemType.LINE_NUMBER) { sourceLines.put(dbg.getCodeAddress(), lineNumber = ((LineNumber) dbg).getLineNumber()); } else if (dbg.getDebugItemType() == DebugItemType.ADVANCE_LINE) { assert lineNumber != -1; sourceLines.put(dbg.getCodeAddress(), lineNumber++); } } } Entry<Integer, Integer> fe = sourceLines.floorEntry(bcIndex); return fe != null ? fe.getValue() : -1; } /* * (non-Javadoc) * @see java.lang.Object#toString() */ @Override public String toString() { return getReference().toString(); } @Override public boolean equals(Object obj) { // instanceof is OK because this class is final. // if (this.getClass().equals(obj.getClass())) { if (obj instanceof DexIMethod) { DexIMethod that = (DexIMethod) obj; return (getDeclaringClass().equals(that.getDeclaringClass()) && getReference().equals(that.getReference())); } else { return false; } } @Override public int hashCode() { return 9661 * getReference().hashCode(); } // ------------------------------------------- // IByteCodeMethod methods // (required to build the ShrikeCFG) // ------------------------------------------- @Override public int getBytecodeIndex(int i) { // TODO Auto-generated method stub // System.out.println("DexIMethod: getBytecodeIndex() possibly not implemented correctly"); // Integer.valueOf(eMethod.codeItem.getInstructions()[i].opcode.value); // return i; return getAddressFromIndex(i); // return -1; } @Override public ExceptionHandler[][] getHandlers() { if (handlers != null) return handlers; // ExceptionHandler[][] handlers = new // ExceptionHandler[eMethod.codeItem.getInstructions().length][]; List<? extends TryBlock<? extends org.jf.dexlib2.iface.ExceptionHandler>> tryBlocks = eMethod.getImplementation().getTryBlocks(); // // if (tries == null){ // return new ExceptionHandler[eMethod.codeItem.getInstructions().length][]; // } // ExceptionHandler[][] handlers = new ExceptionHandler[tries.length][]; // for (int i = 0; i < tries.length; i++) { // EncodedTypeAddrPair[] etaps = tries[i].encodedCatchHandler.handlers; // handlers[i] = new ExceptionHandler[etaps.length]; // for (int j = 0; j < etaps.length; j++) { // EncodedTypeAddrPair etap = etaps[j]; // handlers[i][j] = new ExceptionHandler(etap.getHandlerAddress(), // etap.exceptionType.getTypeDescriptor()); // } // } this.handlers = new ExceptionHandler[instructions().size()][]; if (tryBlocks == null) { // return new ExceptionHandler[instructions.size()][]; return handlers; } ArrayList<ArrayList<ExceptionHandler>> temp_array = new ArrayList<>(); for (int i = 0; i < instructions().size(); i++) { temp_array.add(new ArrayList<>()); } for (TryBlock<? extends org.jf.dexlib2.iface.ExceptionHandler> tryItem : tryBlocks) { int startAddress = tryItem.getStartCodeAddress(); int endAddress = tryItem.getStartCodeAddress() + tryItem.getCodeUnitCount(); /* * The end address points to the address immediately after the end of the last instruction * that the try block covers. We want the .catch directive and end_try label to be associated * with the last covered instruction, so we need to get the address for that instruction */ int startInst = getInstructionIndex(startAddress); int endInst; /* * The try block can extend to the last instruction in the method. If this is the case then * endAddress will be the address immediately following the last instruction. Check to make * sure this is the case. */ if (endAddress > getAddressFromIndex(instructions().size() - 1)) { endInst = instructions().size() - 1; int endSize = 0; for (org.jf.dexlib2.iface.instruction.Instruction inst : eMethod.getImplementation().getInstructions()) { endSize = inst.getCodeUnits(); } if (endAddress != (getAddressFromIndex(endInst) + endSize)) throw new RuntimeException( "Invalid code offset " + endAddress + " for the try block end address"); } else { endInst = getInstructionIndex(endAddress) - 1; } for (int i = startInst; i <= endInst; i++) { // add the rest of the handlers for (org.jf.dexlib2.iface.ExceptionHandler etaps : tryItem.getExceptionHandlers()) { temp_array .get(i) .add( new ExceptionHandler( getInstructionIndex(etaps.getHandlerCodeAddress()), etaps.getExceptionType())); } } } for (int i = 0; i < instructions().size(); i++) { handlers[i] = temp_array.get(i).toArray(new ExceptionHandler[0]); /* System.out.println("i: " + i); for (int j = 0; j < handlers[i].length; j++) { System.out.println("\t j: " + j); System.out.println("\t\t Handler: " + handlers[i][j].getHandler()); System.out.println("\t\t Catch Class: " + handlers[i][j].getCatchClass()); } */ } return handlers; } @Override public Instruction[] getInstructions() { if (instructions == null) parseBytecode(); return instructions.toArray(new Instruction[0]); } private boolean odexMethod() { for (org.jf.dexlib2.iface.instruction.Instruction inst : eMethod.getImplementation().getInstructions()) { if (inst.getOpcode().odexOnly()) { return true; } } return false; } Iterable<? extends org.jf.dexlib2.iface.instruction.Instruction> deodex() { try { DexFileModule m = myClass.getContainer(); // wrap the dex file in a dummy container, so we can provide ClassPathResolver with a DexEntry String dummyDexName = "classes.dex"; ImmutableMultiDexContainer container = new ImmutableMultiDexContainer( ImmutableMap.of(dummyDexName, ImmutableDexFile.of(m.getDexFile()))); ClassPathResolver path = new ClassPathResolver( Collections.singletonList(m.getFile().getParent() + '/'), Collections.<String>emptyList(), container.getEntry(dummyDexName)); ClassPath cp = new ClassPath( path.getResolvedClassProviders(), false, m.getDexFile().getOpcodes().artVersion); MethodAnalyzer analyzer = new MethodAnalyzer(cp, eMethod, null, false); return analyzer.getInstructions(); } catch (Exception e) { assert false : e; return eMethod.getImplementation().getInstructions(); } } protected void parseBytecode() { Iterable<? extends org.jf.dexlib2.iface.instruction.Instruction> instrucs = odexMethod() ? deodex() : eMethod.getImplementation().getInstructions(); // for (org.jfmethod.getInstructionIndex(.dexlib.Code.Instruction inst: instrucs) // { // switch (inst.getFormat()) // { // // case Format10t: // instructions.add(new IInstruction10t((Instruction10t)inst, this)); // break; // case Format10x: // instructions.add(new IInstruction10x((Instruction10x)inst, this)); // break; // case Format11n: // instructions.add(new IInstruction11n((Instruction11n)inst, this)); // break; // case Format11x: // instructions.add(new IInstruction11x((Instruction11x)inst, this)); // break; // case Format12x: // instructions.add(new IInstruction12x((Instruction12x)inst, this)); // break; // case Format20t: // instructions.add(new IInstruction20t((Instruction20t)inst, this)); // break; // case Format21c: // instructions.add(new IInstruction21c((Instruction21c)inst, this)); // break; // case Format21h: // instructions.add(new IInstruction21h((Instruction21h)inst, this)); // break; // case Format21s: // instructions.add(new IInstruction21s((Instruction21s)inst, this)); // break; // case Format21t: // instructions.add(new IInstruction21t((Instruction21t)inst, this)); // break; // case Format22b: // instructions.add(new IInstruction22b((Instruction22b)inst, this)); // break; // case Format22c: // instructions.add(new IInstruction22c((Instruction22c)inst, this)); // break; // case Format22cs: // instructions.add(new IInstruction22cs((Instruction22cs)inst, this)); // break; // case Format22s: // instructions.add(new IInstruction22s((Instruction22s)inst, this)); // break; // case Format22t: // instructions.add(new IInstruction22t((Instruction22t)inst, this)); // break; // case Format22x: // instructions.add(new IInstruction22x((Instruction22x)inst, this)); // break; // case Format23x: // instructions.add(new IInstruction23x((Instruction23x)inst, this)); // break; // case Format30t: // instructions.add(new IInstruction30t((Instruction30t)inst, this)); // break; // case Format31c: // instructions.add(new IInstruction31c((Instruction31c)inst, this)); // break; // case Format31i: // instructions.add(new IInstruction31i((Instruction31i)inst, this)); // break; // case Format31t: // instructions.add(new IInstruction31t((Instruction31t)inst, this)); // break; // case Format32x: // instructions.add(new IInstruction32x((Instruction32x)inst, this)); // break; // case Format35c: // instructions.add(new IInstruction35c((Instruction35c)inst, this)); // break; // case Format35ms: // instructions.add(new IInstruction35ms((Instruction35ms)inst, this)); // break; // case Format35s: // instructions.add(new IInstruction35s((Instruction35s)inst, this)); // break; // case Format3rc: // instructions.add(new IInstruction3rc((Instruction3rc)inst, this)); // break; // case Format3rms: // instructions.add(new IInstruction3rms((Instruction3rms)inst, this)); // break; // case Format51l: // instructions.add(new IInstruction51l((Instruction51l)inst, this)); // break; // case ArrayData: // instructions.add(new // IArrayDataPseudoInstruction((ArrayDataPseudoInstruction)inst, this)); // break; // case PackedSwitchData: // instructions.add(new // IPackedSwitchDataPseudoInstruction((PackedSwitchDataPseudoInstruction)inst, this)); // break; // case SparseSwitchData: // instructions.add(new // ISparseSwitchDataPseudoInstruction((SparseSwitchDataPseudoInstruction)inst, this)); // break; // case UnresolvedOdexInstruction: // instructions.add(new IUnresolvedOdexInstruction((UnresolvedOdexInstruction)inst, // this)); // break; // // } // } // if (eMethod.method.getMethodString().contentEquals("Lorg/xbill/DNS/Name;-><init>([B)V") && // instrucs.length == 4) // System.out.println("debug here"); instructions = new InstructionArray(); int instLoc = 0; int instCounter = -1; // int pc = 0; int currentCodeAddress = 0; for (org.jf.dexlib2.iface.instruction.Instruction inst : instrucs) { totalInsts++; instCounter++; // instLoc = pc - instCounter; instLoc = currentCodeAddress; // pc += inst.getFormat().size; switch (inst.getOpcode()) { case NOP: case ARRAY_PAYLOAD: case PACKED_SWITCH_PAYLOAD: case SPARSE_SWITCH_PAYLOAD: switch (inst.getOpcode().format) { case ArrayPayload: { for (int i = 0; i < instructions.size(); i++) { if (instructions.getFromId(i) instanceof ArrayFill) if (instLoc == (((ArrayFill) getInstructionFromIndex(i)).tableAddressOffset + getAddressFromIndex(i))) { ((ArrayFill) getInstructionFromIndex(i)) .setArrayDataTable((ArrayPayload) inst); // Iterator<ArrayElement> b = // (((ArrayDataPseudoInstruction)inst).getElements()); // while (b.hasNext()) // { // int ElementWidth = // ((ArrayDataPseudoInstruction)inst).getElementWidth(); // byte[] temp_byte = new byte[ElementWidth]; // // ArrayElement t = (ArrayElement)b.next(); // for (int j = 0; j < ElementWidth; j++) // temp_byte[j] = // t.buffer[t.bufferIndex+(ElementWidth-1)-j]; // // ByteBuffer byte_buffer = // ByteBuffer.wrap(temp_byte); // // System.out.println("Index: " + // t.bufferIndex + ", Width: " + t.elementWidth + ", Value: " + // byte_buffer.getChar()); // } break; } } break; } case PackedSwitchPayload: for (int i = 0; i < instructions.size(); i++) { if (instructions.getFromId(i) instanceof Switch) if (instLoc == (((Switch) getInstructionFromIndex(i)).tableAddressOffset + getAddressFromIndex(i))) { ((Switch) getInstructionFromIndex(i)) .setSwitchPad( new PackedSwitchPad( (SwitchPayload) inst, getAddressFromIndex(i + 1) - getAddressFromIndex(i))); break; } } break; case SparseSwitchPayload: { for (int i = 0; i < instructions.size(); i++) { if (instructions.getFromId(i) instanceof Switch) if (instLoc == (((Switch) getInstructionFromIndex(i)).tableAddressOffset + getAddressFromIndex(i))) { ((Switch) getInstructionFromIndex(i)) .setSwitchPad( new SparseSwitchPad( (SwitchPayload) inst, getAddressFromIndex(i + 1) - getAddressFromIndex(i))); break; } } // System.out.println("Targets: " + // ((SparseSwitchDataPseudoInstruction)inst).getTargetCount()); // Iterator<SparseSwitchTarget> i = // (((SparseSwitchDataPseudoInstruction)inst).iterateKeysAndTargets()); // while (i.hasNext()) // { // SparseSwitchTarget t = (SparseSwitchTarget)i.next(); // System.out.println("Key: " + t.key + ", TargetAddressOffset: // " + t.targetAddressOffset); // } break; } default: class NOPInstruction extends Instruction { private NOPInstruction(int pc, Opcode op, DexIMethod method) { super(pc, op, method); } @Override public void visit(Visitor visitor) { // no op } } instructions.add(new NOPInstruction(currentCodeAddress, Opcode.NOP, this)); break; } break; case MOVE: case MOVE_OBJECT: instructions.add( new UnaryOperation( instLoc, UnaryOperation.OpID.MOVE, ((Instruction12x) inst).getRegisterA(), ((Instruction12x) inst).getRegisterB(), inst.getOpcode(), this)); break; case MOVE_FROM16: case MOVE_OBJECT_FROM16: instructions.add( new UnaryOperation( instLoc, UnaryOperation.OpID.MOVE, ((Instruction22x) inst).getRegisterA(), ((Instruction22x) inst).getRegisterB(), inst.getOpcode(), this)); break; case MOVE_16: instructions.add( new UnaryOperation( instLoc, UnaryOperation.OpID.MOVE, ((Instruction32x) inst).getRegisterA(), ((Instruction32x) inst).getRegisterB(), inst.getOpcode(), this)); break; case MOVE_WIDE: instructions.add( new UnaryOperation( instLoc, UnaryOperation.OpID.MOVE_WIDE, ((Instruction12x) inst).getRegisterA(), ((Instruction12x) inst).getRegisterB(), inst.getOpcode(), this)); break; case MOVE_WIDE_FROM16: instructions.add( new UnaryOperation( instLoc, UnaryOperation.OpID.MOVE_WIDE, ((Instruction22x) inst).getRegisterA(), ((Instruction22x) inst).getRegisterB(), inst.getOpcode(), this)); break; case MOVE_WIDE_16: instructions.add( new UnaryOperation( instLoc, UnaryOperation.OpID.MOVE_WIDE, ((Instruction32x) inst).getRegisterA(), ((Instruction32x) inst).getRegisterB(), inst.getOpcode(), this)); break; case MOVE_OBJECT_16: instructions.add( new UnaryOperation( instLoc, UnaryOperation.OpID.MOVE, ((Instruction32x) inst).getRegisterA(), ((Instruction32x) inst).getRegisterB(), inst.getOpcode(), this)); break; case MOVE_RESULT: // register b set as return register, -1; instructions.add( new UnaryOperation( instLoc, UnaryOperation.OpID.MOVE, ((Instruction11x) inst).getRegisterA(), getReturnReg(), inst.getOpcode(), this)); break; case MOVE_RESULT_WIDE: instructions.add( new UnaryOperation( instLoc, UnaryOperation.OpID.MOVE_WIDE, ((Instruction11x) inst).getRegisterA(), getReturnReg(), inst.getOpcode(), this)); break; case MOVE_RESULT_OBJECT: instructions.add( new UnaryOperation( instLoc, UnaryOperation.OpID.MOVE, ((Instruction11x) inst).getRegisterA(), getReturnReg(), inst.getOpcode(), this)); break; case MOVE_EXCEPTION: instructions.add( new UnaryOperation( instLoc, UnaryOperation.OpID.MOVE_EXCEPTION, ((Instruction11x) inst).getRegisterA(), getExceptionReg(), inst.getOpcode(), this)); break; case RETURN_VOID: case RETURN_VOID_NO_BARRIER: instructions.add(new Return.ReturnVoid(instLoc, inst.getOpcode(), this)); break; case RETURN: // I think only primitives call return, and objects call return-object instructions.add( new Return.ReturnSingle( instLoc, ((Instruction11x) inst).getRegisterA(), true, inst.getOpcode(), this)); break; case RETURN_WIDE: // +1 to second parameter okay? instructions.add( new Return.ReturnDouble( instLoc, ((Instruction11x) inst).getRegisterA(), ((Instruction11x) inst).getRegisterA() + 1, inst.getOpcode(), this)); break; case RETURN_OBJECT: instructions.add( new Return.ReturnSingle( instLoc, ((Instruction11x) inst).getRegisterA(), false, inst.getOpcode(), this)); break; case CONST_4: { instructions.add( new Constant.IntConstant( instLoc, ((Instruction11n) inst).getNarrowLiteral(), ((Instruction11n) inst).getRegisterA(), inst.getOpcode(), this)); break; } case CONST_16: instructions.add( new Constant.IntConstant( instLoc, ((Instruction21s) inst).getNarrowLiteral(), ((Instruction21s) inst).getRegisterA(), inst.getOpcode(), this)); break; case CONST: instructions.add( new Constant.IntConstant( instLoc, ((Instruction31i) inst).getNarrowLiteral(), ((Instruction31i) inst).getRegisterA(), inst.getOpcode(), this)); break; case CONST_HIGH16: instructions.add( new Constant.IntConstant( instLoc, ((Instruction21ih) inst).getHatLiteral() << 16, ((Instruction21ih) inst).getRegisterA(), inst.getOpcode(), this)); break; case CONST_WIDE_16: instructions.add( new Constant.LongConstant( instLoc, ((Instruction21s) inst).getWideLiteral(), ((Instruction21s) inst).getRegisterA(), inst.getOpcode(), this)); break; case CONST_WIDE_32: instructions.add( new Constant.LongConstant( instLoc, ((Instruction31i) inst).getWideLiteral(), ((Instruction31i) inst).getRegisterA(), inst.getOpcode(), this)); break; case CONST_WIDE: instructions.add( new Constant.LongConstant( instLoc, ((Instruction51l) inst).getWideLiteral(), ((Instruction51l) inst).getRegisterA(), inst.getOpcode(), this)); break; case CONST_WIDE_HIGH16: instructions.add( new Constant.LongConstant( instLoc, ((Instruction21lh) inst).getWideLiteral() << 16, ((Instruction21lh) inst).getRegisterA(), inst.getOpcode(), this)); break; case CONST_STRING: instructions.add( new Constant.StringConstant( instLoc, ((StringReference) ((Instruction21c) inst).getReference()).getString(), ((Instruction21c) inst).getRegisterA(), inst.getOpcode(), this)); break; case CONST_STRING_JUMBO: instructions.add( new Constant.StringConstant( instLoc, ((StringReference) ((Instruction31c) inst).getReference()).getString(), ((Instruction31c) inst).getRegisterA(), inst.getOpcode(), this)); break; case CONST_CLASS: { String cname = ((org.jf.dexlib2.iface.reference.TypeReference) ((Instruction21c) inst).getReference()) .getType(); if (cname.endsWith(";")) cname = cname.substring(0, cname.length() - 1); // IClass ic = this.myClass.loader.lookupClass(TypeName.findOrCreate(cname)); TypeReference typeRef = TypeReference.findOrCreate(myClass.getClassLoader().getReference(), cname); instructions.add( new Constant.ClassConstant( instLoc, typeRef, ((Instruction21c) inst).getRegisterA(), inst.getOpcode(), this)); // logger.debug("myClass found name: " + // this.myClass.loader.lookupClass(TypeName.findOrCreate(cname)).toString()); break; } case MONITOR_ENTER: instructions.add( new Monitor( instLoc, true, ((Instruction11x) inst).getRegisterA(), inst.getOpcode(), this)); break; case MONITOR_EXIT: instructions.add( new Monitor( instLoc, false, ((Instruction11x) inst).getRegisterA(), inst.getOpcode(), this)); break; case CHECK_CAST: { String cname = ((org.jf.dexlib2.iface.reference.TypeReference) ((Instruction21c) inst).getReference()) .getType(); if (cname.endsWith(";")) cname = cname.substring(0, cname.length() - 1); // retrieving type reference correctly? instructions.add( new CheckCast( instLoc, TypeReference.findOrCreate(myClass.getClassLoader().getReference(), cname), ((Instruction21c) inst).getRegisterA(), inst.getOpcode(), this)); break; } case INSTANCE_OF: { String cname = ((org.jf.dexlib2.iface.reference.TypeReference) ((Instruction22c) inst).getReference()) .getType(); if (cname.endsWith(";")) cname = cname.substring(0, cname.length() - 1); instructions.add( new InstanceOf( instLoc, ((Instruction22c) inst).getRegisterA(), TypeReference.findOrCreate(myClass.getClassLoader().getReference(), cname), ((Instruction22c) inst).getRegisterB(), inst.getOpcode(), this)); break; } case ARRAY_LENGTH: instructions.add( new ArrayLength( instLoc, ((Instruction12x) inst).getRegisterA(), ((Instruction12x) inst).getRegisterB(), inst.getOpcode(), this)); break; case NEW_INSTANCE: { // newsitereference use instLoc or pc? String cname = ((org.jf.dexlib2.iface.reference.TypeReference) ((Instruction21c) inst).getReference()) .getType(); if (cname.endsWith(";")) cname = cname.substring(0, cname.length() - 1); instructions.add( new New( instLoc, ((Instruction21c) inst).getRegisterA(), NewSiteReference.make( instLoc, TypeReference.findOrCreate(myClass.getClassLoader().getReference(), cname)), inst.getOpcode(), this)); break; } case NEW_ARRAY: { int[] params = new int[1]; params[0] = ((Instruction22c) inst).getRegisterB(); // MyLogger.log(LogLevel.INFO, "Type: " // +((TypeIdItem)((Instruction22c)inst).getReferencedItem()).getTypeDescriptor()); String cname = ((org.jf.dexlib2.iface.reference.TypeReference) ((Instruction22c) inst).getReference()) .getType(); if (cname.endsWith(";")) cname = cname.substring(0, cname.length() - 1); instructions.add( new NewArray( instLoc, ((Instruction22c) inst).getRegisterA(), NewSiteReference.make( instLoc, TypeReference.findOrCreate(myClass.getClassLoader().getReference(), cname)), params, inst.getOpcode(), this)); break; } // TODO: FILLED ARRAYS case FILLED_NEW_ARRAY: { int registerCount = ((Instruction35c) inst).getRegisterCount(); int[] params = new int[1]; params[0] = registerCount; int[] args = new int[registerCount]; for (int i = 0; i < registerCount; i++) { switch (i) { case 0: args[0] = ((Instruction35c) inst).getRegisterD(); break; case 1: args[1] = ((Instruction35c) inst).getRegisterE(); break; case 2: args[2] = ((Instruction35c) inst).getRegisterF(); break; case 3: args[3] = ((Instruction35c) inst).getRegisterG(); break; case 4: args[4] = ((Instruction35c) inst).getRegisterC(); break; default: throw new RuntimeException( "Illegal instruction at " + instLoc + ": bad register count"); } } String cname = ((org.jf.dexlib2.iface.reference.TypeReference) ((Instruction35c) inst).getReference()) .getType(); if (cname.endsWith(";")) cname = cname.substring(0, cname.length() - 1); NewSiteReference newSiteRef = NewSiteReference.make( instLoc, TypeReference.findOrCreate(myClass.getClassLoader().getReference(), cname)); TypeReference myTypeRef = TypeReference.findOrCreate( myClass.getClassLoader().getReference(), newSiteRef.getDeclaredType().getArrayElementType().getName().toString()); instructions.add( new NewArrayFilled( instLoc, getReturnReg(), newSiteRef, myTypeRef, params, args, inst.getOpcode(), this)); break; } case FILLED_NEW_ARRAY_RANGE: { int registerCount = ((Instruction3rc) inst).getRegisterCount(); int[] params = new int[1]; params[0] = registerCount; int[] args = new int[registerCount]; for (int i = 0; i < registerCount; i++) args[i] = ((Instruction3rc) inst).getStartRegister() + i; String cname = ((org.jf.dexlib2.iface.reference.TypeReference) ((Instruction3rc) inst).getReference()) .getType(); if (cname.endsWith(";")) cname = cname.substring(0, cname.length() - 1); NewSiteReference newSiteRef = NewSiteReference.make( instLoc, TypeReference.findOrCreate(myClass.getClassLoader().getReference(), cname)); TypeReference myTypeRef = TypeReference.findOrCreate( myClass.getClassLoader().getReference(), newSiteRef.getDeclaredType().getArrayElementType().getName().toString()); instructions.add( new NewArrayFilled( instLoc, getReturnReg(), newSiteRef, myTypeRef, params, args, inst.getOpcode(), this)); break; } case FILL_ARRAY_DATA: // System.out.println("Array Reference: " + ((Instruction31t)inst).getRegisterA()); // System.out.println("Table Address Offset: " + ((Instruction31t)inst).getCodeOffset()); TypeReference arrayElementType = findOutArrayElementType(inst, instructions.toArray(new Instruction[0]), instCounter); instructions.add( new ArrayFill( instLoc, ((Instruction31t) inst).getRegisterA(), ((Instruction31t) inst).getCodeOffset(), TypeReference.findOrCreate( myClass.getClassLoader().getReference(), arrayElementType.getName().toString()), inst.getOpcode(), this)); break; case THROW: instructions.add( new Throw(instLoc, ((Instruction11x) inst).getRegisterA(), inst.getOpcode(), this)); break; case GOTO: instructions.add( new Goto(instLoc, ((Instruction10t) inst).getCodeOffset(), inst.getOpcode(), this)); break; case GOTO_16: instructions.add( new Goto(instLoc, ((Instruction20t) inst).getCodeOffset(), inst.getOpcode(), this)); break; case GOTO_32: instructions.add( new Goto(instLoc, ((Instruction30t) inst).getCodeOffset(), inst.getOpcode(), this)); break; case PACKED_SWITCH: case SPARSE_SWITCH: instructions.add( new Switch( instLoc, ((Instruction31t) inst).getRegisterA(), ((Instruction31t) inst).getCodeOffset(), inst.getOpcode(), this)); break; case CMPL_FLOAT: instructions.add( new BinaryOperation( instLoc, BinaryOperation.OpID.CMPL_FLOAT, ((Instruction23x) inst).getRegisterA(), ((Instruction23x) inst).getRegisterB(), ((Instruction23x) inst).getRegisterC(), inst.getOpcode(), this)); break; case CMPG_FLOAT: instructions.add( new BinaryOperation( instLoc, BinaryOperation.OpID.CMPG_FLOAT, ((Instruction23x) inst).getRegisterA(), ((Instruction23x) inst).getRegisterB(), ((Instruction23x) inst).getRegisterC(), inst.getOpcode(), this)); break; case CMPL_DOUBLE: instructions.add( new BinaryOperation( instLoc, BinaryOperation.OpID.CMPL_DOUBLE, ((Instruction23x) inst).getRegisterA(), ((Instruction23x) inst).getRegisterB(), ((Instruction23x) inst).getRegisterC(), inst.getOpcode(), this)); break; case CMPG_DOUBLE: instructions.add( new BinaryOperation( instLoc, BinaryOperation.OpID.CMPG_DOUBLE, ((Instruction23x) inst).getRegisterA(), ((Instruction23x) inst).getRegisterB(), ((Instruction23x) inst).getRegisterC(), inst.getOpcode(), this)); break; case CMP_LONG: instructions.add( new BinaryOperation( instLoc, BinaryOperation.OpID.CMPL_LONG, ((Instruction23x) inst).getRegisterA(), ((Instruction23x) inst).getRegisterB(), ((Instruction23x) inst).getRegisterC(), inst.getOpcode(), this)); break; case IF_EQ: instructions.add( new Branch.BinaryBranch( instLoc, ((Instruction22t) inst).getCodeOffset(), Branch.BinaryBranch.CompareOp.EQ, ((Instruction22t) inst).getRegisterA(), ((Instruction22t) inst).getRegisterB(), inst.getOpcode(), this)); break; case IF_NE: instructions.add( new Branch.BinaryBranch( instLoc, ((Instruction22t) inst).getCodeOffset(), Branch.BinaryBranch.CompareOp.NE, ((Instruction22t) inst).getRegisterA(), ((Instruction22t) inst).getRegisterB(), inst.getOpcode(), this)); break; case IF_LT: instructions.add( new Branch.BinaryBranch( instLoc, ((Instruction22t) inst).getCodeOffset(), Branch.BinaryBranch.CompareOp.LT, ((Instruction22t) inst).getRegisterA(), ((Instruction22t) inst).getRegisterB(), inst.getOpcode(), this)); break; case IF_GE: instructions.add( new Branch.BinaryBranch( instLoc, ((Instruction22t) inst).getCodeOffset(), Branch.BinaryBranch.CompareOp.GE, ((Instruction22t) inst).getRegisterA(), ((Instruction22t) inst).getRegisterB(), inst.getOpcode(), this)); break; case IF_GT: instructions.add( new Branch.BinaryBranch( instLoc, ((Instruction22t) inst).getCodeOffset(), Branch.BinaryBranch.CompareOp.GT, ((Instruction22t) inst).getRegisterA(), ((Instruction22t) inst).getRegisterB(), inst.getOpcode(), this)); break; case IF_LE: instructions.add( new Branch.BinaryBranch( instLoc, ((Instruction22t) inst).getCodeOffset(), Branch.BinaryBranch.CompareOp.LE, ((Instruction22t) inst).getRegisterA(), ((Instruction22t) inst).getRegisterB(), inst.getOpcode(), this)); break; case IF_EQZ: instructions.add( new Branch.UnaryBranch( instLoc, ((Instruction21t) inst).getCodeOffset(), Branch.UnaryBranch.CompareOp.EQZ, ((Instruction21t) inst).getRegisterA(), inst.getOpcode(), this)); break; case IF_NEZ: instructions.add( new Branch.UnaryBranch( instLoc, ((Instruction21t) inst).getCodeOffset(), Branch.UnaryBranch.CompareOp.NEZ, ((Instruction21t) inst).getRegisterA(), inst.getOpcode(), this)); break; case IF_LTZ: instructions.add( new Branch.UnaryBranch( instLoc, ((Instruction21t) inst).getCodeOffset(), Branch.UnaryBranch.CompareOp.LTZ, ((Instruction21t) inst).getRegisterA(), inst.getOpcode(), this)); break; case IF_GEZ: instructions.add( new Branch.UnaryBranch( instLoc, ((Instruction21t) inst).getCodeOffset(), Branch.UnaryBranch.CompareOp.GEZ, ((Instruction21t) inst).getRegisterA(), inst.getOpcode(), this)); break; case IF_GTZ: instructions.add( new Branch.UnaryBranch( instLoc, ((Instruction21t) inst).getCodeOffset(), Branch.UnaryBranch.CompareOp.GTZ, ((Instruction21t) inst).getRegisterA(), inst.getOpcode(), this)); break; case IF_LEZ: instructions.add( new Branch.UnaryBranch( instLoc, ((Instruction21t) inst).getCodeOffset(), Branch.UnaryBranch.CompareOp.LEZ, ((Instruction21t) inst).getRegisterA(), inst.getOpcode(), this)); break; case AGET: instructions.add( new ArrayGet( instLoc, ((Instruction23x) inst).getRegisterA(), ((Instruction23x) inst).getRegisterB(), ((Instruction23x) inst).getRegisterC(), Type.t_int, inst.getOpcode(), this)); break; case AGET_WIDE: instructions.add( new ArrayGet( instLoc, ((Instruction23x) inst).getRegisterA(), ((Instruction23x) inst).getRegisterB(), ((Instruction23x) inst).getRegisterC(), Type.t_wide, inst.getOpcode(), this)); break; case AGET_OBJECT: instructions.add( new ArrayGet( instLoc, ((Instruction23x) inst).getRegisterA(), ((Instruction23x) inst).getRegisterB(), ((Instruction23x) inst).getRegisterC(), Type.t_object, inst.getOpcode(), this)); break; case AGET_BOOLEAN: instructions.add( new ArrayGet( instLoc, ((Instruction23x) inst).getRegisterA(), ((Instruction23x) inst).getRegisterB(), ((Instruction23x) inst).getRegisterC(), Type.t_boolean, inst.getOpcode(), this)); break; case AGET_BYTE: instructions.add( new ArrayGet( instLoc, ((Instruction23x) inst).getRegisterA(), ((Instruction23x) inst).getRegisterB(), ((Instruction23x) inst).getRegisterC(), Type.t_byte, inst.getOpcode(), this)); break; case AGET_CHAR: instructions.add( new ArrayGet( instLoc, ((Instruction23x) inst).getRegisterA(), ((Instruction23x) inst).getRegisterB(), ((Instruction23x) inst).getRegisterC(), Type.t_char, inst.getOpcode(), this)); break; case AGET_SHORT: instructions.add( new ArrayGet( instLoc, ((Instruction23x) inst).getRegisterA(), ((Instruction23x) inst).getRegisterB(), ((Instruction23x) inst).getRegisterC(), Type.t_short, inst.getOpcode(), this)); break; case APUT: instructions.add( new ArrayPut( instLoc, ((Instruction23x) inst).getRegisterA(), ((Instruction23x) inst).getRegisterB(), ((Instruction23x) inst).getRegisterC(), Type.t_int, inst.getOpcode(), this)); break; case APUT_WIDE: instructions.add( new ArrayPut( instLoc, ((Instruction23x) inst).getRegisterA(), ((Instruction23x) inst).getRegisterB(), ((Instruction23x) inst).getRegisterC(), Type.t_wide, inst.getOpcode(), this)); break; case APUT_OBJECT: instructions.add( new ArrayPut( instLoc, ((Instruction23x) inst).getRegisterA(), ((Instruction23x) inst).getRegisterB(), ((Instruction23x) inst).getRegisterC(), Type.t_object, inst.getOpcode(), this)); break; case APUT_BOOLEAN: instructions.add( new ArrayPut( instLoc, ((Instruction23x) inst).getRegisterA(), ((Instruction23x) inst).getRegisterB(), ((Instruction23x) inst).getRegisterC(), Type.t_boolean, inst.getOpcode(), this)); break; case APUT_BYTE: instructions.add( new ArrayPut( instLoc, ((Instruction23x) inst).getRegisterA(), ((Instruction23x) inst).getRegisterB(), ((Instruction23x) inst).getRegisterC(), Type.t_byte, inst.getOpcode(), this)); break; case APUT_CHAR: instructions.add( new ArrayPut( instLoc, ((Instruction23x) inst).getRegisterA(), ((Instruction23x) inst).getRegisterB(), ((Instruction23x) inst).getRegisterC(), Type.t_char, inst.getOpcode(), this)); break; case APUT_SHORT: instructions.add( new ArrayPut( instLoc, ((Instruction23x) inst).getRegisterA(), ((Instruction23x) inst).getRegisterB(), ((Instruction23x) inst).getRegisterC(), Type.t_short, inst.getOpcode(), this)); break; case IGET: case IGET_WIDE: case IGET_OBJECT: case IGET_BOOLEAN: case IGET_BYTE: case IGET_CHAR: case IGET_SHORT: { String cname = ((FieldReference) ((Instruction22c) inst).getReference()).getDefiningClass(); String fname = ((FieldReference) ((Instruction22c) inst).getReference()).getName(); String ftname = ((FieldReference) ((Instruction22c) inst).getReference()).getType(); if (cname.endsWith(";")) cname = cname.substring(0, cname.length() - 1); if (fname.endsWith(";")) fname = fname.substring(0, fname.length() - 1); if (ftname.endsWith(";")) ftname = ftname.substring(0, ftname.length() - 1); instructions.add( new GetField.GetInstanceField( instLoc, ((Instruction22c) inst).getRegisterA(), ((Instruction22c) inst).getRegisterB(), cname, fname, ftname, inst.getOpcode(), this)); break; } case IPUT: case IPUT_WIDE: case IPUT_OBJECT: case IPUT_BOOLEAN: case IPUT_BYTE: case IPUT_CHAR: case IPUT_SHORT: { String cname = ((FieldReference) ((Instruction22c) inst).getReference()).getDefiningClass(); String fname = ((FieldReference) ((Instruction22c) inst).getReference()).getName(); String ftname = ((FieldReference) ((Instruction22c) inst).getReference()).getType(); if (cname.endsWith(";")) cname = cname.substring(0, cname.length() - 1); if (fname.endsWith(";")) fname = fname.substring(0, fname.length() - 1); if (ftname.endsWith(";")) ftname = ftname.substring(0, ftname.length() - 1); instructions.add( new PutField.PutInstanceField( instLoc, ((TwoRegisterInstruction) inst).getRegisterA(), ((TwoRegisterInstruction) inst).getRegisterB(), cname, fname, ftname, inst.getOpcode(), this)); break; } case SGET: case SGET_WIDE: case SGET_OBJECT: case SGET_BOOLEAN: case SGET_BYTE: case SGET_CHAR: case SGET_SHORT: { String cname = ((FieldReference) ((Instruction21c) inst).getReference()).getDefiningClass(); String fname = ((FieldReference) ((Instruction21c) inst).getReference()).getName(); String ftname = ((FieldReference) ((Instruction21c) inst).getReference()).getType(); if (cname.endsWith(";")) cname = cname.substring(0, cname.length() - 1); if (fname.endsWith(";")) fname = fname.substring(0, fname.length() - 1); if (ftname.endsWith(";")) ftname = ftname.substring(0, ftname.length() - 1); instructions.add( new GetField.GetStaticField( instLoc, ((Instruction21c) inst).getRegisterA(), cname, fname, ftname, inst.getOpcode(), this)); break; } case SPUT: case SPUT_WIDE: case SPUT_OBJECT: case SPUT_BOOLEAN: case SPUT_BYTE: case SPUT_CHAR: case SPUT_SHORT: { String cname = ((FieldReference) ((Instruction21c) inst).getReference()).getDefiningClass(); String fname = ((FieldReference) ((Instruction21c) inst).getReference()).getName(); String ftname = ((FieldReference) ((Instruction21c) inst).getReference()).getType(); if (cname.endsWith(";")) cname = cname.substring(0, cname.length() - 1); if (fname.endsWith(";")) fname = fname.substring(0, fname.length() - 1); if (ftname.endsWith(";")) ftname = ftname.substring(0, ftname.length() - 1); instructions.add( new PutField.PutStaticField( instLoc, ((Instruction21c) inst).getRegisterA(), cname, fname, ftname, inst.getOpcode(), this)); break; } case INVOKE_VIRTUAL: { int registerCount = ((Instruction35c) inst).getRegisterCount(); int[] args = new int[registerCount]; for (int i = 0; i < registerCount; i++) { switch (i) { case 0: args[0] = ((Instruction35c) inst).getRegisterC(); break; case 1: args[1] = ((Instruction35c) inst).getRegisterD(); break; case 2: args[2] = ((Instruction35c) inst).getRegisterE(); break; case 3: args[3] = ((Instruction35c) inst).getRegisterF(); break; case 4: args[4] = ((Instruction35c) inst).getRegisterG(); break; default: throw new RuntimeException( "Illegal instruction at " + instLoc + ": bad register count"); } } String cname = ((org.jf.dexlib2.iface.reference.MethodReference) ((Instruction35c) inst).getReference()) .getDefiningClass(); String mname = ((org.jf.dexlib2.iface.reference.MethodReference) ((Instruction35c) inst).getReference()) .getName(); String pname = DexUtil.getSignature( (org.jf.dexlib2.iface.reference.MethodReference) ((Instruction35c) inst).getReference()); if (cname.endsWith(";")) cname = cname.substring(0, cname.length() - 1); // if (mname.endsWith(";")) // mname = mname.substring(0,mname.length()-1); // if (pname.endsWith(";")) // pname = pname.substring(0,pname.length()-1); // for (IMethod m: // this.myClass.loader.lookupClass(TypeName.findOrCreate(cname)).getDeclaredMethods()) // System.out.println(m.getDescriptor().toString()); handleINVOKE_VIRTUAL(instLoc, cname, mname, pname, args, inst.getOpcode()); // instructions.add(new Invoke.InvokeVirtual(instLoc, cname, mname, pname, args, // inst.opcode, this)); // logger.debug("\t" + inst.opcode.toString() + " class: "+ cname + ", method name: " + // mname + ", prototype string: " + pname); break; } case INVOKE_SUPER: { int registerCount = ((Instruction35c) inst).getRegisterCount(); int[] args = new int[registerCount]; for (int i = 0; i < registerCount; i++) { switch (i) { case 0: args[0] = ((Instruction35c) inst).getRegisterC(); break; case 1: args[1] = ((Instruction35c) inst).getRegisterD(); break; case 2: args[2] = ((Instruction35c) inst).getRegisterE(); break; case 3: args[3] = ((Instruction35c) inst).getRegisterF(); break; case 4: args[4] = ((Instruction35c) inst).getRegisterG(); break; default: throw new RuntimeException( "Illegal instruction at " + instLoc + ": bad register count"); } } String cname = ((org.jf.dexlib2.iface.reference.MethodReference) ((Instruction35c) inst).getReference()) .getDefiningClass(); String mname = ((org.jf.dexlib2.iface.reference.MethodReference) ((Instruction35c) inst).getReference()) .getName(); String pname = DexUtil.getSignature( (org.jf.dexlib2.iface.reference.MethodReference) ((Instruction35c) inst).getReference()); if (cname.endsWith(";")) cname = cname.substring(0, cname.length() - 1); instructions.add( new Invoke.InvokeSuper(instLoc, cname, mname, pname, args, inst.getOpcode(), this)); break; } case INVOKE_DIRECT: { int registerCount = ((Instruction35c) inst).getRegisterCount(); int[] args = new int[registerCount]; for (int i = 0; i < registerCount; i++) { switch (i) { case 0: args[0] = ((Instruction35c) inst).getRegisterC(); break; case 1: args[1] = ((Instruction35c) inst).getRegisterD(); break; case 2: args[2] = ((Instruction35c) inst).getRegisterE(); break; case 3: args[3] = ((Instruction35c) inst).getRegisterF(); break; case 4: args[4] = ((Instruction35c) inst).getRegisterG(); break; default: throw new RuntimeException( "Illegal instruction at " + instLoc + ": bad register count"); } } // logger.debug(inst.opcode.toString() + " class: // "+((MethodIdItem)((Instruction35c)inst).getReferencedItem()).getContainingClass().getTypeDescriptor() + ", method name: " + ((MethodIdItem)((Instruction35c)inst).getReferencedItem()).getMethodName().getStringValue() + ", prototype string: " + ((MethodIdItem)((Instruction35c)inst).getReferencedItem()).getPrototype().getPrototypeString()); String cname = ((org.jf.dexlib2.iface.reference.MethodReference) ((Instruction35c) inst).getReference()) .getDefiningClass(); String mname = ((org.jf.dexlib2.iface.reference.MethodReference) ((Instruction35c) inst).getReference()) .getName(); String pname = DexUtil.getSignature( (org.jf.dexlib2.iface.reference.MethodReference) ((Instruction35c) inst).getReference()); if (cname.endsWith(";")) cname = cname.substring(0, cname.length() - 1); instructions.add( new Invoke.InvokeDirect( instLoc, cname, mname, pname, args, inst.getOpcode(), this)); break; } case INVOKE_STATIC: { int registerCount = ((Instruction35c) inst).getRegisterCount(); int[] args = new int[registerCount]; for (int i = 0; i < registerCount; i++) { switch (i) { case 0: args[0] = ((Instruction35c) inst).getRegisterC(); break; case 1: args[1] = ((Instruction35c) inst).getRegisterD(); break; case 2: args[2] = ((Instruction35c) inst).getRegisterE(); break; case 3: args[3] = ((Instruction35c) inst).getRegisterF(); break; case 4: args[4] = ((Instruction35c) inst).getRegisterG(); break; default: throw new RuntimeException( "Illegal instruction at " + instLoc + ": bad register count"); } } // logger.debug(inst.opcode.toString() + " class: // "+((MethodIdItem)((Instruction35c)inst).getReferencedItem()).getContainingClass().getTypeDescriptor() + ", method name: " + ((MethodIdItem)((Instruction35c)inst).getReferencedItem()).getMethodName().getStringValue() + ", prototype string: " + ((MethodIdItem)((Instruction35c)inst).getReferencedItem()).getPrototype().getPrototypeString()); String cname = ((org.jf.dexlib2.iface.reference.MethodReference) ((Instruction35c) inst).getReference()) .getDefiningClass(); String mname = ((org.jf.dexlib2.iface.reference.MethodReference) ((Instruction35c) inst).getReference()) .getName(); String pname = DexUtil.getSignature( (org.jf.dexlib2.iface.reference.MethodReference) ((Instruction35c) inst).getReference()); if (cname.endsWith(";")) cname = cname.substring(0, cname.length() - 1); instructions.add( new Invoke.InvokeStatic( instLoc, cname, mname, pname, args, inst.getOpcode(), this)); break; } case INVOKE_INTERFACE: { int registerCount = ((Instruction35c) inst).getRegisterCount(); int[] args = new int[registerCount]; for (int i = 0; i < registerCount; i++) { switch (i) { case 0: args[0] = ((Instruction35c) inst).getRegisterC(); break; case 1: args[1] = ((Instruction35c) inst).getRegisterD(); break; case 2: args[2] = ((Instruction35c) inst).getRegisterE(); break; case 3: args[3] = ((Instruction35c) inst).getRegisterF(); break; case 4: args[4] = ((Instruction35c) inst).getRegisterG(); break; default: throw new RuntimeException( "Illegal instruction at " + instLoc + ": bad register count"); } } String cname = ((org.jf.dexlib2.iface.reference.MethodReference) ((Instruction35c) inst).getReference()) .getDefiningClass(); String mname = ((org.jf.dexlib2.iface.reference.MethodReference) ((Instruction35c) inst).getReference()) .getName(); String pname = DexUtil.getSignature( (org.jf.dexlib2.iface.reference.MethodReference) ((Instruction35c) inst).getReference()); if (cname.endsWith(";")) cname = cname.substring(0, cname.length() - 1); instructions.add( new Invoke.InvokeInterface( instLoc, cname, mname, pname, args, inst.getOpcode(), this)); break; } case INVOKE_VIRTUAL_RANGE: { int registerCount = ((Instruction3rc) inst).getRegisterCount(); int[] args = new int[registerCount]; for (int i = 0; i < registerCount; i++) args[i] = ((Instruction3rc) inst).getStartRegister() + i; String cname = ((org.jf.dexlib2.iface.reference.MethodReference) ((Instruction3rc) inst).getReference()) .getDefiningClass(); String mname = ((org.jf.dexlib2.iface.reference.MethodReference) ((Instruction3rc) inst).getReference()) .getName(); String pname = DexUtil.getSignature( (org.jf.dexlib2.iface.reference.MethodReference) ((Instruction3rc) inst).getReference()); if (cname.endsWith(";")) cname = cname.substring(0, cname.length() - 1); instructions.add( new Invoke.InvokeVirtual( instLoc, cname, mname, pname, args, inst.getOpcode(), this)); break; } case INVOKE_SUPER_RANGE: { int registerCount = ((Instruction3rc) inst).getRegisterCount(); int[] args = new int[registerCount]; for (int i = 0; i < registerCount; i++) args[i] = ((Instruction3rc) inst).getStartRegister() + i; String cname = ((org.jf.dexlib2.iface.reference.MethodReference) ((Instruction3rc) inst).getReference()) .getDefiningClass(); String mname = ((org.jf.dexlib2.iface.reference.MethodReference) ((Instruction3rc) inst).getReference()) .getName(); String pname = DexUtil.getSignature( (org.jf.dexlib2.iface.reference.MethodReference) ((Instruction3rc) inst).getReference()); if (cname.endsWith(";")) cname = cname.substring(0, cname.length() - 1); instructions.add( new Invoke.InvokeSuper(instLoc, cname, mname, pname, args, inst.getOpcode(), this)); break; } case INVOKE_DIRECT_RANGE: { int registerCount = ((Instruction3rc) inst).getRegisterCount(); int[] args = new int[registerCount]; for (int i = 0; i < registerCount; i++) args[i] = ((Instruction3rc) inst).getStartRegister() + i; String cname = ((org.jf.dexlib2.iface.reference.MethodReference) ((Instruction3rc) inst).getReference()) .getDefiningClass(); String mname = ((org.jf.dexlib2.iface.reference.MethodReference) ((Instruction3rc) inst).getReference()) .getName(); String pname = DexUtil.getSignature( (org.jf.dexlib2.iface.reference.MethodReference) ((Instruction3rc) inst).getReference()); if (cname.endsWith(";")) cname = cname.substring(0, cname.length() - 1); instructions.add( new Invoke.InvokeDirect( instLoc, cname, mname, pname, args, inst.getOpcode(), this)); break; } case INVOKE_STATIC_RANGE: { int registerCount = ((Instruction3rc) inst).getRegisterCount(); int[] args = new int[registerCount]; for (int i = 0; i < registerCount; i++) args[i] = ((Instruction3rc) inst).getStartRegister() + i; String cname = ((org.jf.dexlib2.iface.reference.MethodReference) ((Instruction3rc) inst).getReference()) .getDefiningClass(); String mname = ((org.jf.dexlib2.iface.reference.MethodReference) ((Instruction3rc) inst).getReference()) .getName(); String pname = DexUtil.getSignature( (org.jf.dexlib2.iface.reference.MethodReference) ((Instruction3rc) inst).getReference()); if (cname.endsWith(";")) cname = cname.substring(0, cname.length() - 1); instructions.add( new Invoke.InvokeStatic( instLoc, cname, mname, pname, args, inst.getOpcode(), this)); break; } case INVOKE_INTERFACE_RANGE: { int registerCount = ((Instruction3rc) inst).getRegisterCount(); int[] args = new int[registerCount]; for (int i = 0; i < registerCount; i++) args[i] = ((Instruction3rc) inst).getStartRegister() + i; String cname = ((org.jf.dexlib2.iface.reference.MethodReference) ((Instruction3rc) inst).getReference()) .getDefiningClass(); String mname = ((org.jf.dexlib2.iface.reference.MethodReference) ((Instruction3rc) inst).getReference()) .getName(); String pname = DexUtil.getSignature( (org.jf.dexlib2.iface.reference.MethodReference) ((Instruction3rc) inst).getReference()); if (cname.endsWith(";")) cname = cname.substring(0, cname.length() - 1); instructions.add( new Invoke.InvokeInterface( instLoc, cname, mname, pname, args, inst.getOpcode(), this)); break; } case NEG_INT: instructions.add( new UnaryOperation( instLoc, OpID.NEGINT, ((Instruction12x) inst).getRegisterA(), ((Instruction12x) inst).getRegisterB(), inst.getOpcode(), this)); break; case NOT_INT: instructions.add( new UnaryOperation( instLoc, OpID.NOTINT, ((Instruction12x) inst).getRegisterA(), ((Instruction12x) inst).getRegisterB(), inst.getOpcode(), this)); break; case NEG_LONG: instructions.add( new UnaryOperation( instLoc, OpID.NEGLONG, ((Instruction12x) inst).getRegisterA(), ((Instruction12x) inst).getRegisterB(), inst.getOpcode(), this)); break; case NOT_LONG: instructions.add( new UnaryOperation( instLoc, OpID.NOTLONG, ((Instruction12x) inst).getRegisterA(), ((Instruction12x) inst).getRegisterB(), inst.getOpcode(), this)); break; case NEG_FLOAT: instructions.add( new UnaryOperation( instLoc, OpID.NEGFLOAT, ((Instruction12x) inst).getRegisterA(), ((Instruction12x) inst).getRegisterB(), inst.getOpcode(), this)); break; case NEG_DOUBLE: instructions.add( new UnaryOperation( instLoc, OpID.NEGDOUBLE, ((Instruction12x) inst).getRegisterA(), ((Instruction12x) inst).getRegisterB(), inst.getOpcode(), this)); break; case INT_TO_LONG: instructions.add( new UnaryOperation( instLoc, OpID.INTTOLONG, ((Instruction12x) inst).getRegisterA(), ((Instruction12x) inst).getRegisterB(), inst.getOpcode(), this)); break; case INT_TO_FLOAT: instructions.add( new UnaryOperation( instLoc, OpID.INTTOFLOAT, ((Instruction12x) inst).getRegisterA(), ((Instruction12x) inst).getRegisterB(), inst.getOpcode(), this)); break; case INT_TO_DOUBLE: instructions.add( new UnaryOperation( instLoc, OpID.INTTODOUBLE, ((Instruction12x) inst).getRegisterA(), ((Instruction12x) inst).getRegisterB(), inst.getOpcode(), this)); break; case LONG_TO_INT: instructions.add( new UnaryOperation( instLoc, OpID.LONGTOINT, ((Instruction12x) inst).getRegisterA(), ((Instruction12x) inst).getRegisterB(), inst.getOpcode(), this)); break; case LONG_TO_FLOAT: instructions.add( new UnaryOperation( instLoc, OpID.LONGTOFLOAT, ((Instruction12x) inst).getRegisterA(), ((Instruction12x) inst).getRegisterB(), inst.getOpcode(), this)); break; case LONG_TO_DOUBLE: instructions.add( new UnaryOperation( instLoc, OpID.LONGTODOUBLE, ((Instruction12x) inst).getRegisterA(), ((Instruction12x) inst).getRegisterB(), inst.getOpcode(), this)); break; case FLOAT_TO_INT: instructions.add( new UnaryOperation( instLoc, OpID.FLOATTOINT, ((Instruction12x) inst).getRegisterA(), ((Instruction12x) inst).getRegisterB(), inst.getOpcode(), this)); break; case FLOAT_TO_LONG: instructions.add( new UnaryOperation( instLoc, OpID.FLOATTOLONG, ((Instruction12x) inst).getRegisterA(), ((Instruction12x) inst).getRegisterB(), inst.getOpcode(), this)); break; case FLOAT_TO_DOUBLE: instructions.add( new UnaryOperation( instLoc, OpID.FLOATTODOUBLE, ((Instruction12x) inst).getRegisterA(), ((Instruction12x) inst).getRegisterB(), inst.getOpcode(), this)); break; case DOUBLE_TO_INT: instructions.add( new UnaryOperation( instLoc, OpID.DOUBLETOINT, ((Instruction12x) inst).getRegisterA(), ((Instruction12x) inst).getRegisterB(), inst.getOpcode(), this)); break; case DOUBLE_TO_LONG: instructions.add( new UnaryOperation( instLoc, OpID.DOUBLETOLONG, ((Instruction12x) inst).getRegisterA(), ((Instruction12x) inst).getRegisterB(), inst.getOpcode(), this)); break; case DOUBLE_TO_FLOAT: instructions.add( new UnaryOperation( instLoc, OpID.DOUBLETOFLOAT, ((Instruction12x) inst).getRegisterA(), ((Instruction12x) inst).getRegisterB(), inst.getOpcode(), this)); break; case INT_TO_BYTE: instructions.add( new UnaryOperation( instLoc, OpID.INTTOBYTE, ((Instruction12x) inst).getRegisterA(), ((Instruction12x) inst).getRegisterB(), inst.getOpcode(), this)); break; case INT_TO_CHAR: instructions.add( new UnaryOperation( instLoc, OpID.INTTOCHAR, ((Instruction12x) inst).getRegisterA(), ((Instruction12x) inst).getRegisterB(), inst.getOpcode(), this)); break; case INT_TO_SHORT: instructions.add( new UnaryOperation( instLoc, OpID.INTTOSHORT, ((Instruction12x) inst).getRegisterA(), ((Instruction12x) inst).getRegisterB(), inst.getOpcode(), this)); break; case ADD_INT: instructions.add( new BinaryOperation( instLoc, BinaryOperation.OpID.ADD_INT, ((Instruction23x) inst).getRegisterA(), ((Instruction23x) inst).getRegisterB(), ((Instruction23x) inst).getRegisterC(), inst.getOpcode(), this)); break; case SUB_INT: instructions.add( new BinaryOperation( instLoc, BinaryOperation.OpID.SUB_INT, ((Instruction23x) inst).getRegisterA(), ((Instruction23x) inst).getRegisterB(), ((Instruction23x) inst).getRegisterC(), inst.getOpcode(), this)); break; case MUL_INT: instructions.add( new BinaryOperation( instLoc, BinaryOperation.OpID.MUL_INT, ((Instruction23x) inst).getRegisterA(), ((Instruction23x) inst).getRegisterB(), ((Instruction23x) inst).getRegisterC(), inst.getOpcode(), this)); break; case DIV_INT: instructions.add( new BinaryOperation( instLoc, BinaryOperation.OpID.DIV_INT, ((Instruction23x) inst).getRegisterA(), ((Instruction23x) inst).getRegisterB(), ((Instruction23x) inst).getRegisterC(), inst.getOpcode(), this)); break; case REM_INT: instructions.add( new BinaryOperation( instLoc, BinaryOperation.OpID.REM_INT, ((Instruction23x) inst).getRegisterA(), ((Instruction23x) inst).getRegisterB(), ((Instruction23x) inst).getRegisterC(), inst.getOpcode(), this)); break; case AND_INT: instructions.add( new BinaryOperation( instLoc, BinaryOperation.OpID.AND_INT, ((Instruction23x) inst).getRegisterA(), ((Instruction23x) inst).getRegisterB(), ((Instruction23x) inst).getRegisterC(), inst.getOpcode(), this)); break; case OR_INT: instructions.add( new BinaryOperation( instLoc, BinaryOperation.OpID.OR_INT, ((Instruction23x) inst).getRegisterA(), ((Instruction23x) inst).getRegisterB(), ((Instruction23x) inst).getRegisterC(), inst.getOpcode(), this)); break; case XOR_INT: instructions.add( new BinaryOperation( instLoc, BinaryOperation.OpID.XOR_INT, ((Instruction23x) inst).getRegisterA(), ((Instruction23x) inst).getRegisterB(), ((Instruction23x) inst).getRegisterC(), inst.getOpcode(), this)); break; case SHL_INT: instructions.add( new BinaryOperation( instLoc, BinaryOperation.OpID.SHL_INT, ((Instruction23x) inst).getRegisterA(), ((Instruction23x) inst).getRegisterB(), ((Instruction23x) inst).getRegisterC(), inst.getOpcode(), this)); break; case SHR_INT: instructions.add( new BinaryOperation( instLoc, BinaryOperation.OpID.SHR_INT, ((Instruction23x) inst).getRegisterA(), ((Instruction23x) inst).getRegisterB(), ((Instruction23x) inst).getRegisterC(), inst.getOpcode(), this)); break; case USHR_INT: instructions.add( new BinaryOperation( instLoc, BinaryOperation.OpID.USHR_INT, ((Instruction23x) inst).getRegisterA(), ((Instruction23x) inst).getRegisterB(), ((Instruction23x) inst).getRegisterC(), inst.getOpcode(), this)); break; case ADD_LONG: instructions.add( new BinaryOperation( instLoc, BinaryOperation.OpID.ADD_LONG, ((Instruction23x) inst).getRegisterA(), ((Instruction23x) inst).getRegisterB(), ((Instruction23x) inst).getRegisterC(), inst.getOpcode(), this)); break; case SUB_LONG: instructions.add( new BinaryOperation( instLoc, BinaryOperation.OpID.SUB_LONG, ((Instruction23x) inst).getRegisterA(), ((Instruction23x) inst).getRegisterB(), ((Instruction23x) inst).getRegisterC(), inst.getOpcode(), this)); break; case MUL_LONG: instructions.add( new BinaryOperation( instLoc, BinaryOperation.OpID.MUL_LONG, ((Instruction23x) inst).getRegisterA(), ((Instruction23x) inst).getRegisterB(), ((Instruction23x) inst).getRegisterC(), inst.getOpcode(), this)); break; case DIV_LONG: instructions.add( new BinaryOperation( instLoc, BinaryOperation.OpID.DIV_LONG, ((Instruction23x) inst).getRegisterA(), ((Instruction23x) inst).getRegisterB(), ((Instruction23x) inst).getRegisterC(), inst.getOpcode(), this)); break; case REM_LONG: instructions.add( new BinaryOperation( instLoc, BinaryOperation.OpID.REM_LONG, ((Instruction23x) inst).getRegisterA(), ((Instruction23x) inst).getRegisterB(), ((Instruction23x) inst).getRegisterC(), inst.getOpcode(), this)); break; case AND_LONG: instructions.add( new BinaryOperation( instLoc, BinaryOperation.OpID.AND_LONG, ((Instruction23x) inst).getRegisterA(), ((Instruction23x) inst).getRegisterB(), ((Instruction23x) inst).getRegisterC(), inst.getOpcode(), this)); break; case OR_LONG: instructions.add( new BinaryOperation( instLoc, BinaryOperation.OpID.OR_LONG, ((Instruction23x) inst).getRegisterA(), ((Instruction23x) inst).getRegisterB(), ((Instruction23x) inst).getRegisterC(), inst.getOpcode(), this)); break; case XOR_LONG: instructions.add( new BinaryOperation( instLoc, BinaryOperation.OpID.XOR_LONG, ((Instruction23x) inst).getRegisterA(), ((Instruction23x) inst).getRegisterB(), ((Instruction23x) inst).getRegisterC(), inst.getOpcode(), this)); break; case SHL_LONG: instructions.add( new BinaryOperation( instLoc, BinaryOperation.OpID.SHL_LONG, ((Instruction23x) inst).getRegisterA(), ((Instruction23x) inst).getRegisterB(), ((Instruction23x) inst).getRegisterC(), inst.getOpcode(), this)); break; case SHR_LONG: instructions.add( new BinaryOperation( instLoc, BinaryOperation.OpID.SHR_LONG, ((Instruction23x) inst).getRegisterA(), ((Instruction23x) inst).getRegisterB(), ((Instruction23x) inst).getRegisterC(), inst.getOpcode(), this)); break; case USHR_LONG: instructions.add( new BinaryOperation( instLoc, BinaryOperation.OpID.USHR_LONG, ((Instruction23x) inst).getRegisterA(), ((Instruction23x) inst).getRegisterB(), ((Instruction23x) inst).getRegisterC(), inst.getOpcode(), this)); break; case ADD_FLOAT: instructions.add( new BinaryOperation( instLoc, BinaryOperation.OpID.ADD_FLOAT, ((Instruction23x) inst).getRegisterA(), ((Instruction23x) inst).getRegisterB(), ((Instruction23x) inst).getRegisterC(), inst.getOpcode(), this)); break; case SUB_FLOAT: instructions.add( new BinaryOperation( instLoc, BinaryOperation.OpID.SUB_FLOAT, ((Instruction23x) inst).getRegisterA(), ((Instruction23x) inst).getRegisterB(), ((Instruction23x) inst).getRegisterC(), inst.getOpcode(), this)); break; case MUL_FLOAT: instructions.add( new BinaryOperation( instLoc, BinaryOperation.OpID.MUL_FLOAT, ((Instruction23x) inst).getRegisterA(), ((Instruction23x) inst).getRegisterB(), ((Instruction23x) inst).getRegisterC(), inst.getOpcode(), this)); break; case DIV_FLOAT: instructions.add( new BinaryOperation( instLoc, BinaryOperation.OpID.DIV_FLOAT, ((Instruction23x) inst).getRegisterA(), ((Instruction23x) inst).getRegisterB(), ((Instruction23x) inst).getRegisterC(), inst.getOpcode(), this)); break; case REM_FLOAT: instructions.add( new BinaryOperation( instLoc, BinaryOperation.OpID.REM_FLOAT, ((Instruction23x) inst).getRegisterA(), ((Instruction23x) inst).getRegisterB(), ((Instruction23x) inst).getRegisterC(), inst.getOpcode(), this)); break; case ADD_DOUBLE: instructions.add( new BinaryOperation( instLoc, BinaryOperation.OpID.ADD_DOUBLE, ((Instruction23x) inst).getRegisterA(), ((Instruction23x) inst).getRegisterB(), ((Instruction23x) inst).getRegisterC(), inst.getOpcode(), this)); break; case SUB_DOUBLE: instructions.add( new BinaryOperation( instLoc, BinaryOperation.OpID.SUB_DOUBLE, ((Instruction23x) inst).getRegisterA(), ((Instruction23x) inst).getRegisterB(), ((Instruction23x) inst).getRegisterC(), inst.getOpcode(), this)); break; case MUL_DOUBLE: instructions.add( new BinaryOperation( instLoc, BinaryOperation.OpID.MUL_DOUBLE, ((Instruction23x) inst).getRegisterA(), ((Instruction23x) inst).getRegisterB(), ((Instruction23x) inst).getRegisterC(), inst.getOpcode(), this)); break; case DIV_DOUBLE: instructions.add( new BinaryOperation( instLoc, BinaryOperation.OpID.DIV_DOUBLE, ((Instruction23x) inst).getRegisterA(), ((Instruction23x) inst).getRegisterB(), ((Instruction23x) inst).getRegisterC(), inst.getOpcode(), this)); break; case REM_DOUBLE: instructions.add( new BinaryOperation( instLoc, BinaryOperation.OpID.REM_DOUBLE, ((Instruction23x) inst).getRegisterA(), ((Instruction23x) inst).getRegisterB(), ((Instruction23x) inst).getRegisterC(), inst.getOpcode(), this)); break; case ADD_INT_2ADDR: instructions.add( new BinaryOperation( instLoc, BinaryOperation.OpID.ADD_INT, ((Instruction12x) inst).getRegisterA(), ((Instruction12x) inst).getRegisterA(), ((Instruction12x) inst).getRegisterB(), inst.getOpcode(), this)); break; case SUB_INT_2ADDR: instructions.add( new BinaryOperation( instLoc, BinaryOperation.OpID.SUB_INT, ((Instruction12x) inst).getRegisterA(), ((Instruction12x) inst).getRegisterA(), ((Instruction12x) inst).getRegisterB(), inst.getOpcode(), this)); break; case MUL_INT_2ADDR: instructions.add( new BinaryOperation( instLoc, BinaryOperation.OpID.MUL_INT, ((Instruction12x) inst).getRegisterA(), ((Instruction12x) inst).getRegisterA(), ((Instruction12x) inst).getRegisterB(), inst.getOpcode(), this)); break; case DIV_INT_2ADDR: instructions.add( new BinaryOperation( instLoc, BinaryOperation.OpID.DIV_INT, ((Instruction12x) inst).getRegisterA(), ((Instruction12x) inst).getRegisterA(), ((Instruction12x) inst).getRegisterB(), inst.getOpcode(), this)); break; case REM_INT_2ADDR: instructions.add( new BinaryOperation( instLoc, BinaryOperation.OpID.REM_INT, ((Instruction12x) inst).getRegisterA(), ((Instruction12x) inst).getRegisterA(), ((Instruction12x) inst).getRegisterB(), inst.getOpcode(), this)); break; case AND_INT_2ADDR: instructions.add( new BinaryOperation( instLoc, BinaryOperation.OpID.AND_INT, ((Instruction12x) inst).getRegisterA(), ((Instruction12x) inst).getRegisterA(), ((Instruction12x) inst).getRegisterB(), inst.getOpcode(), this)); break; case OR_INT_2ADDR: instructions.add( new BinaryOperation( instLoc, BinaryOperation.OpID.OR_INT, ((Instruction12x) inst).getRegisterA(), ((Instruction12x) inst).getRegisterA(), ((Instruction12x) inst).getRegisterB(), inst.getOpcode(), this)); break; case XOR_INT_2ADDR: instructions.add( new BinaryOperation( instLoc, BinaryOperation.OpID.XOR_INT, ((Instruction12x) inst).getRegisterA(), ((Instruction12x) inst).getRegisterA(), ((Instruction12x) inst).getRegisterB(), inst.getOpcode(), this)); break; case SHL_INT_2ADDR: instructions.add( new BinaryOperation( instLoc, BinaryOperation.OpID.SHL_INT, ((Instruction12x) inst).getRegisterA(), ((Instruction12x) inst).getRegisterA(), ((Instruction12x) inst).getRegisterB(), inst.getOpcode(), this)); break; case SHR_INT_2ADDR: instructions.add( new BinaryOperation( instLoc, BinaryOperation.OpID.SHR_INT, ((Instruction12x) inst).getRegisterA(), ((Instruction12x) inst).getRegisterA(), ((Instruction12x) inst).getRegisterB(), inst.getOpcode(), this)); break; case USHR_INT_2ADDR: instructions.add( new BinaryOperation( instLoc, BinaryOperation.OpID.USHR_INT, ((Instruction12x) inst).getRegisterA(), ((Instruction12x) inst).getRegisterA(), ((Instruction12x) inst).getRegisterB(), inst.getOpcode(), this)); break; case ADD_LONG_2ADDR: instructions.add( new BinaryOperation( instLoc, BinaryOperation.OpID.ADD_LONG, ((Instruction12x) inst).getRegisterA(), ((Instruction12x) inst).getRegisterA(), ((Instruction12x) inst).getRegisterB(), inst.getOpcode(), this)); break; case SUB_LONG_2ADDR: instructions.add( new BinaryOperation( instLoc, BinaryOperation.OpID.SUB_LONG, ((Instruction12x) inst).getRegisterA(), ((Instruction12x) inst).getRegisterA(), ((Instruction12x) inst).getRegisterB(), inst.getOpcode(), this)); break; case MUL_LONG_2ADDR: instructions.add( new BinaryOperation( instLoc, BinaryOperation.OpID.MUL_LONG, ((Instruction12x) inst).getRegisterA(), ((Instruction12x) inst).getRegisterA(), ((Instruction12x) inst).getRegisterB(), inst.getOpcode(), this)); break; case DIV_LONG_2ADDR: instructions.add( new BinaryOperation( instLoc, BinaryOperation.OpID.DIV_LONG, ((Instruction12x) inst).getRegisterA(), ((Instruction12x) inst).getRegisterA(), ((Instruction12x) inst).getRegisterB(), inst.getOpcode(), this)); break; case REM_LONG_2ADDR: instructions.add( new BinaryOperation( instLoc, BinaryOperation.OpID.REM_LONG, ((Instruction12x) inst).getRegisterA(), ((Instruction12x) inst).getRegisterA(), ((Instruction12x) inst).getRegisterB(), inst.getOpcode(), this)); break; case AND_LONG_2ADDR: instructions.add( new BinaryOperation( instLoc, BinaryOperation.OpID.AND_LONG, ((Instruction12x) inst).getRegisterA(), ((Instruction12x) inst).getRegisterA(), ((Instruction12x) inst).getRegisterB(), inst.getOpcode(), this)); break; case OR_LONG_2ADDR: instructions.add( new BinaryOperation( instLoc, BinaryOperation.OpID.OR_LONG, ((Instruction12x) inst).getRegisterA(), ((Instruction12x) inst).getRegisterA(), ((Instruction12x) inst).getRegisterB(), inst.getOpcode(), this)); break; case XOR_LONG_2ADDR: instructions.add( new BinaryOperation( instLoc, BinaryOperation.OpID.XOR_LONG, ((Instruction12x) inst).getRegisterA(), ((Instruction12x) inst).getRegisterA(), ((Instruction12x) inst).getRegisterB(), inst.getOpcode(), this)); break; case SHL_LONG_2ADDR: instructions.add( new BinaryOperation( instLoc, BinaryOperation.OpID.SHL_LONG, ((Instruction12x) inst).getRegisterA(), ((Instruction12x) inst).getRegisterA(), ((Instruction12x) inst).getRegisterB(), inst.getOpcode(), this)); break; case SHR_LONG_2ADDR: instructions.add( new BinaryOperation( instLoc, BinaryOperation.OpID.SHR_LONG, ((Instruction12x) inst).getRegisterA(), ((Instruction12x) inst).getRegisterA(), ((Instruction12x) inst).getRegisterB(), inst.getOpcode(), this)); break; case USHR_LONG_2ADDR: instructions.add( new BinaryOperation( instLoc, BinaryOperation.OpID.USHR_LONG, ((Instruction12x) inst).getRegisterA(), ((Instruction12x) inst).getRegisterA(), ((Instruction12x) inst).getRegisterB(), inst.getOpcode(), this)); break; case ADD_FLOAT_2ADDR: instructions.add( new BinaryOperation( instLoc, BinaryOperation.OpID.ADD_FLOAT, ((Instruction12x) inst).getRegisterA(), ((Instruction12x) inst).getRegisterA(), ((Instruction12x) inst).getRegisterB(), inst.getOpcode(), this)); break; case SUB_FLOAT_2ADDR: instructions.add( new BinaryOperation( instLoc, BinaryOperation.OpID.SUB_FLOAT, ((Instruction12x) inst).getRegisterA(), ((Instruction12x) inst).getRegisterA(), ((Instruction12x) inst).getRegisterB(), inst.getOpcode(), this)); break; case MUL_FLOAT_2ADDR: instructions.add( new BinaryOperation( instLoc, BinaryOperation.OpID.MUL_FLOAT, ((Instruction12x) inst).getRegisterA(), ((Instruction12x) inst).getRegisterA(), ((Instruction12x) inst).getRegisterB(), inst.getOpcode(), this)); break; case DIV_FLOAT_2ADDR: instructions.add( new BinaryOperation( instLoc, BinaryOperation.OpID.DIV_FLOAT, ((Instruction12x) inst).getRegisterA(), ((Instruction12x) inst).getRegisterA(), ((Instruction12x) inst).getRegisterB(), inst.getOpcode(), this)); break; case REM_FLOAT_2ADDR: instructions.add( new BinaryOperation( instLoc, BinaryOperation.OpID.REM_FLOAT, ((Instruction12x) inst).getRegisterA(), ((Instruction12x) inst).getRegisterA(), ((Instruction12x) inst).getRegisterB(), inst.getOpcode(), this)); break; case ADD_DOUBLE_2ADDR: instructions.add( new BinaryOperation( instLoc, BinaryOperation.OpID.ADD_DOUBLE, ((Instruction12x) inst).getRegisterA(), ((Instruction12x) inst).getRegisterA(), ((Instruction12x) inst).getRegisterB(), inst.getOpcode(), this)); break; case SUB_DOUBLE_2ADDR: instructions.add( new BinaryOperation( instLoc, BinaryOperation.OpID.SUB_DOUBLE, ((Instruction12x) inst).getRegisterA(), ((Instruction12x) inst).getRegisterA(), ((Instruction12x) inst).getRegisterB(), inst.getOpcode(), this)); break; case MUL_DOUBLE_2ADDR: instructions.add( new BinaryOperation( instLoc, BinaryOperation.OpID.MUL_DOUBLE, ((Instruction12x) inst).getRegisterA(), ((Instruction12x) inst).getRegisterA(), ((Instruction12x) inst).getRegisterB(), inst.getOpcode(), this)); break; case DIV_DOUBLE_2ADDR: instructions.add( new BinaryOperation( instLoc, BinaryOperation.OpID.DIV_DOUBLE, ((Instruction12x) inst).getRegisterA(), ((Instruction12x) inst).getRegisterA(), ((Instruction12x) inst).getRegisterB(), inst.getOpcode(), this)); break; case REM_DOUBLE_2ADDR: instructions.add( new BinaryOperation( instLoc, BinaryOperation.OpID.REM_DOUBLE, ((Instruction12x) inst).getRegisterA(), ((Instruction12x) inst).getRegisterA(), ((Instruction12x) inst).getRegisterB(), inst.getOpcode(), this)); break; case ADD_INT_LIT16: { Literal lit = new Literal.LongLiteral(((Instruction22s) inst).getWideLiteral()); instructions.add( new BinaryLiteralOperation( instLoc, BinaryLiteralOperation.OpID.ADD_INT, ((Instruction22s) inst).getRegisterA(), ((Instruction22s) inst).getRegisterB(), lit, inst.getOpcode(), this)); break; } case RSUB_INT: { Literal lit = new Literal.LongLiteral(((Instruction22s) inst).getWideLiteral()); instructions.add( new BinaryLiteralOperation( instLoc, BinaryLiteralOperation.OpID.RSUB_INT, ((Instruction22s) inst).getRegisterA(), ((Instruction22s) inst).getRegisterB(), lit, inst.getOpcode(), this)); break; } case MUL_INT_LIT16: { Literal lit = new Literal.LongLiteral(((Instruction22s) inst).getWideLiteral()); instructions.add( new BinaryLiteralOperation( instLoc, BinaryLiteralOperation.OpID.MUL_INT, ((Instruction22s) inst).getRegisterA(), ((Instruction22s) inst).getRegisterB(), lit, inst.getOpcode(), this)); break; } case DIV_INT_LIT16: { Literal lit = new Literal.LongLiteral(((Instruction22s) inst).getWideLiteral()); instructions.add( new BinaryLiteralOperation( instLoc, BinaryLiteralOperation.OpID.DIV_INT, ((Instruction22s) inst).getRegisterA(), ((Instruction22s) inst).getRegisterB(), lit, inst.getOpcode(), this)); break; } case REM_INT_LIT16: { Literal lit = new Literal.LongLiteral(((Instruction22s) inst).getWideLiteral()); instructions.add( new BinaryLiteralOperation( instLoc, BinaryLiteralOperation.OpID.REM_INT, ((Instruction22s) inst).getRegisterA(), ((Instruction22s) inst).getRegisterB(), lit, inst.getOpcode(), this)); break; } case AND_INT_LIT16: { Literal lit = new Literal.LongLiteral(((Instruction22s) inst).getWideLiteral()); instructions.add( new BinaryLiteralOperation( instLoc, BinaryLiteralOperation.OpID.AND_INT, ((Instruction22s) inst).getRegisterA(), ((Instruction22s) inst).getRegisterB(), lit, inst.getOpcode(), this)); break; } case OR_INT_LIT16: { Literal lit = new Literal.LongLiteral(((Instruction22s) inst).getWideLiteral()); instructions.add( new BinaryLiteralOperation( instLoc, BinaryLiteralOperation.OpID.OR_INT, ((Instruction22s) inst).getRegisterA(), ((Instruction22s) inst).getRegisterB(), lit, inst.getOpcode(), this)); break; } case XOR_INT_LIT16: { Literal lit = new Literal.LongLiteral(((Instruction22s) inst).getWideLiteral()); instructions.add( new BinaryLiteralOperation( instLoc, BinaryLiteralOperation.OpID.XOR_INT, ((Instruction22s) inst).getRegisterA(), ((Instruction22s) inst).getRegisterB(), lit, inst.getOpcode(), this)); break; } case ADD_INT_LIT8: { Literal lit = new Literal.LongLiteral(((Instruction22b) inst).getWideLiteral()); instructions.add( new BinaryLiteralOperation( instLoc, BinaryLiteralOperation.OpID.ADD_INT, ((Instruction22b) inst).getRegisterA(), ((Instruction22b) inst).getRegisterB(), lit, inst.getOpcode(), this)); break; } case RSUB_INT_LIT8: { Literal lit = new Literal.LongLiteral(((Instruction22b) inst).getWideLiteral()); instructions.add( new BinaryLiteralOperation( instLoc, BinaryLiteralOperation.OpID.RSUB_INT, ((Instruction22b) inst).getRegisterA(), ((Instruction22b) inst).getRegisterB(), lit, inst.getOpcode(), this)); break; } case MUL_INT_LIT8: { Literal lit = new Literal.LongLiteral(((Instruction22b) inst).getWideLiteral()); instructions.add( new BinaryLiteralOperation( instLoc, BinaryLiteralOperation.OpID.MUL_INT, ((Instruction22b) inst).getRegisterA(), ((Instruction22b) inst).getRegisterB(), lit, inst.getOpcode(), this)); break; } case DIV_INT_LIT8: { Literal lit = new Literal.LongLiteral(((Instruction22b) inst).getWideLiteral()); instructions.add( new BinaryLiteralOperation( instLoc, BinaryLiteralOperation.OpID.DIV_INT, ((Instruction22b) inst).getRegisterA(), ((Instruction22b) inst).getRegisterB(), lit, inst.getOpcode(), this)); break; } case REM_INT_LIT8: { Literal lit = new Literal.LongLiteral(((Instruction22b) inst).getWideLiteral()); instructions.add( new BinaryLiteralOperation( instLoc, BinaryLiteralOperation.OpID.REM_INT, ((Instruction22b) inst).getRegisterA(), ((Instruction22b) inst).getRegisterB(), lit, inst.getOpcode(), this)); break; } case AND_INT_LIT8: { Literal lit = new Literal.LongLiteral(((Instruction22b) inst).getWideLiteral()); instructions.add( new BinaryLiteralOperation( instLoc, BinaryLiteralOperation.OpID.AND_INT, ((Instruction22b) inst).getRegisterA(), ((Instruction22b) inst).getRegisterB(), lit, inst.getOpcode(), this)); break; } case OR_INT_LIT8: { Literal lit = new Literal.LongLiteral(((Instruction22b) inst).getWideLiteral()); instructions.add( new BinaryLiteralOperation( instLoc, BinaryLiteralOperation.OpID.OR_INT, ((Instruction22b) inst).getRegisterA(), ((Instruction22b) inst).getRegisterB(), lit, inst.getOpcode(), this)); break; } case XOR_INT_LIT8: { Literal lit = new Literal.LongLiteral(((Instruction22b) inst).getWideLiteral()); instructions.add( new BinaryLiteralOperation( instLoc, BinaryLiteralOperation.OpID.XOR_INT, ((Instruction22b) inst).getRegisterA(), ((Instruction22b) inst).getRegisterB(), lit, inst.getOpcode(), this)); break; } case SHL_INT_LIT8: { Literal lit = new Literal.LongLiteral(((Instruction22b) inst).getWideLiteral()); instructions.add( new BinaryLiteralOperation( instLoc, BinaryLiteralOperation.OpID.SHL_INT, ((Instruction22b) inst).getRegisterA(), ((Instruction22b) inst).getRegisterB(), lit, inst.getOpcode(), this)); break; } case SHR_INT_LIT8: { Literal lit = new Literal.LongLiteral(((Instruction22b) inst).getWideLiteral()); instructions.add( new BinaryLiteralOperation( instLoc, BinaryLiteralOperation.OpID.SHR_INT, ((Instruction22b) inst).getRegisterA(), ((Instruction22b) inst).getRegisterB(), lit, inst.getOpcode(), this)); break; } case USHR_INT_LIT8: { Literal lit = new Literal.LongLiteral(((Instruction22b) inst).getWideLiteral()); instructions.add( new BinaryLiteralOperation( instLoc, BinaryLiteralOperation.OpID.USHR_INT, ((Instruction22b) inst).getRegisterA(), ((Instruction22b) inst).getRegisterB(), lit, inst.getOpcode(), this)); break; } default: throw new RuntimeException( "not implemented instruction: 0x" + inst.getOpcode().toString() + " in " + eMethod.getDefiningClass() + ':' + eMethod.getName()); } currentCodeAddress += inst.getCodeUnits(); } //// comment out start //// Instruction[] iinstructions = new Instruction[instrucs.length]; // instructions = new InsructionArray(); // // // for (int i = 0; i < instrucs.length; i++) { // org.jf.dexlib.Code.Instruction instruction = instrucs[i]; // // // System.out.println(instruction.toString()); // switch (instruction.getFormat()) { // // /* // - Format10t(Instruction10t.Factory, 2), // - Format10x(Instruction10x.Factory, 2), // - Format11n(Instruction11n.Factory, 2), // - Format11x(Instruction11x.Factory, 2), // - Format12x(Instruction12x.Factory, 2), // - Format20t(Instruction20t.Factory, 4), // - Format21c(Instruction21c.Factory, 4), // Format21h(Instruction21h.Factory, 4), // Format21s(Instruction21s.Factory, 4), // Format21t(Instruction21t.Factory, 4), // Format22b(Instruction22b.Factory, 4), // Format22c(Instruction22c.Factory, 4), // Format22cs(Instruction22cs.Factory, 4), // Format22s(Instruction22s.Factory, 4), // Format22t(Instruction22t.Factory, 4), // Format22x(Instruction22x.Factory, 4), // Format23x(Instruction23x.Factory, 4), // - Format30t(Instruction30t.Factory, 6), // Format31c(Instruction31c.Factory, 6), // Format31i(Instruction31i.Factory, 6), // Format31t(Instruction31t.Factory, 6), // Format32x(Instruction32x.Factory, 6), // Format35c(Instruction35c.Factory, 6), // Format35s(Instruction35s.Factory, 6), // Format35ms(Instruction35ms.Factory, 6), // Format3rc(Instruction3rc.Factory, 6), // Format3rms(Instruction3rms.Factory, 6), // Format51l(Instruction51l.Factory, 10), // ArrayData(null, -1, true), // PackedSwitchData(null, -1, true), // SparseSwitchData(null, -1, true), // UnresolvedOdexInstruction(null, -1, false), // */ // case Format10t: { //goto // // // Instruction10t dInst = (Instruction10t)instruction; // // int offset = dInst.getCodeOffset(); // instructions.add(new Goto(i,offset)); // // break; // } // case Format10x: { // // switch(instruction.opcode) { // case RETURN_VOID: { // instructions.add(new Return.ReturnVoid(i)); // break; // } // default: // break; // } // // break; // } // // case Format11n: { // // Instruction11n dInst = (Instruction11n) instruction; // // System.out.println("here1"); // int a = (int)dInst.getLiteral(); // System.out.println("here2"); // Register b = regBank.get(dInst.getRegisterA()); // System.out.println("here3"); // // Constant.IntConstant c = new Constant.IntConstant(1, 2, b); // //instructions.add(c); // System.out.println("here5"); // instructions.add(new Constant.IntConstant(i, // (int)dInst.getLiteral(), regBank.get(dInst.getRegisterA()))); // System.out.println("here4"); // break; // } // // case Format11x: { // /* // * MOVE_RESULT((byte)0x0a, "move-result", ReferenceType.none, // Format.Format11x, Opcode.CAN_CONTINUE | Opcode.SETS_REGISTER), // MOVE_RESULT_WIDE((byte)0x0b, "move-result-wide", ReferenceType.none, Format.Format11x, // Opcode.CAN_CONTINUE | Opcode.SETS_REGISTER | Opcode.SETS_WIDE_REGISTER), // MOVE_RESULT_OBJECT((byte)0x0c, "move-result-object", ReferenceType.none, Format.Format11x, // Opcode.CAN_CONTINUE | Opcode.SETS_REGISTER), // MOVE_EXCEPTION((byte)0x0d, "move-exception", ReferenceType.none, Format.Format11x, // Opcode.CAN_CONTINUE | Opcode.SETS_REGISTER), // RETURN((byte)0x0f, "return", ReferenceType.none, Format.Format11x), // RETURN_WIDE((byte)0x10, "return-wide", ReferenceType.none, Format.Format11x), // RETURN_OBJECT((byte)0x11, "return-object", ReferenceType.none, Format.Format11x), // MONITOR_ENTER((byte)0x1d, "monitor-enter", ReferenceType.none, Format.Format11x, // Opcode.CAN_THROW | Opcode.CAN_CONTINUE), // MONITOR_EXIT((byte)0x1e, "monitor-exit", ReferenceType.none, Format.Format11x, // Opcode.CAN_THROW | Opcode.CAN_CONTINUE), // THROW((byte)0x27, "throw", ReferenceType.none, Format.Format11x, Opcode.CAN_THROW), // */ // // Instruction11x dInst = (Instruction11x) instruction; // // switch (dInst.opcode) { // case MOVE_RESULT: { // instructions.add(new UnaryOperation(i, // UnaryOperation.OpID.MOVE, regBank.get(dInst.getRegisterA()), // regBank.getReturnReg())); // break; // } // case MOVE_RESULT_WIDE: { // instructions.add(new UnaryOperation(i, // UnaryOperation.OpID.MOVE_WIDE, // regBank.get(dInst.getRegisterA()), regBank.getReturnReg())); // break; // } // case MOVE_RESULT_OBJECT: { // instructions.add(new UnaryOperation(i, // UnaryOperation.OpID.MOVE, regBank.get(dInst.getRegisterA()), // regBank.getReturnReg())); // break; // } // case MOVE_EXCEPTION: { // instructions.add(new UnaryOperation(i, // UnaryOperation.OpID.MOVE, regBank.get(dInst.getRegisterA()), // regBank.getReturnExceptionReg())); // break; // } // case RETURN: { // instructions.add(new Return.ReturnSingle(i, // regBank.get(dInst.getRegisterA()))); // break; // } // case RETURN_WIDE: { // instructions.add(new Return.ReturnDouble(i, // regBank.get(dInst.getRegisterA()), regBank.get(dInst.getRegisterA() // + 1))); // break; // } // case RETURN_OBJECT: { // instructions.add(new Return.ReturnSingle(i, // regBank.get(dInst.getRegisterA()))); // break; // } // case MONITOR_ENTER: { // instructions.add(new Monitor(i, true, regBank // .get(dInst.getRegisterA()))); // break; // } // case MONITOR_EXIT: { // instructions.add(new Monitor(i, false, regBank // .get(dInst.getRegisterA()))); // break; // } // case THROW: { // instructions.add(new Throw(i, regBank // .get(dInst.getRegisterA()))); // break; // } // default: // break; // } // break; // } // // case Format12x: { // // Instruction12x dInst = (Instruction12x) instruction; // int destination = dInst.getRegisterA(); // int source = dInst.getRegisterB(); // // switch(dInst.opcode) { // // MOVE((byte)0x01, "move", ReferenceType.none, Format.Format12x, // Opcode.CAN_CONTINUE | Opcode.SETS_REGISTER), // case MOVE: { // instructions.add(new UnaryOperation(i, // UnaryOperation.OpID.MOVE, regBank.get(destination), // regBank.get(source))); // break; // } // // MOVE_WIDE((byte)0x04, "move-wide", ReferenceType.none, Format.Format12x, // Opcode.CAN_CONTINUE | Opcode.SETS_REGISTER | Opcode.SETS_WIDE_REGISTER), // case MOVE_WIDE: { // instructions.add(new UnaryOperation(i, // UnaryOperation.OpID.MOVE_WIDE, // regBank.get(destination), regBank.get(source))); // break; // } // // MOVE_OBJECT((byte)0x07, "move-object", ReferenceType.none, // Format.Format12x, Opcode.CAN_CONTINUE | Opcode.SETS_REGISTER), // case MOVE_OBJECT: { // instructions.add(new UnaryOperation(i, // UnaryOperation.OpID.MOVE, regBank.get(destination), // regBank.get(source))); // // break; // } // // ARRAY_LENGTH((byte)0x21, "array-length", ReferenceType.none, // Format.Format12x, Opcode.CAN_THROW | Opcode.CAN_CONTINUE | Opcode.SETS_REGISTER), // case ARRAY_LENGTH: { // instructions.add(new ArrayLength(i, regBank // .get(destination), regBank.get(source))); // break; // } // // NEG_INT((byte)0x7b, "neg-int", ReferenceType.none, Format.Format12x, // Opcode.CAN_CONTINUE | Opcode.SETS_REGISTER), // case NEG_INT: { // instructions.add(new UnaryOperation(i, // OpID.NEGINT, regBank.get(destination), regBank.get(source))); // break; // } // // NOT_INT((byte)0x7c, "not-int", ReferenceType.none, Format.Format12x, // Opcode.CAN_CONTINUE | Opcode.SETS_REGISTER), // case NOT_INT: { // instructions.add(new UnaryOperation(i, // OpID.NOTINT, regBank.get(destination), regBank.get(source))); // break; // } // // NEG_LONG((byte)0x7d, "neg-long", ReferenceType.none, Format.Format12x, // Opcode.CAN_CONTINUE | Opcode.SETS_REGISTER | Opcode.SETS_WIDE_REGISTER), // case NEG_LONG: { // instructions.add(new UnaryOperation(i, // OpID.NEGLONG, regBank.get(destination), regBank.get(source))); // // break; // } // // NOT_LONG((byte)0x7e, "not-long", ReferenceType.none, Format.Format12x, // Opcode.CAN_CONTINUE | Opcode.SETS_REGISTER | Opcode.SETS_WIDE_REGISTER), // case NOT_LONG: { // instructions.add(new UnaryOperation(i, // OpID.NOTLONG, regBank.get(destination), regBank.get(source))); // break; // } // // NEG_FLOAT((byte)0x7f, "neg-float", ReferenceType.none, Format.Format12x, // Opcode.CAN_CONTINUE | Opcode.SETS_REGISTER), // case NEG_FLOAT: { // instructions.add(new UnaryOperation(i, // OpID.NEGFLOAT, regBank.get(destination), regBank.get(source))); // // break; // // } // // NEG_DOUBLE((byte)0x80, "neg-double", ReferenceType.none, Format.Format12x, // Opcode.CAN_CONTINUE | Opcode.SETS_REGISTER | Opcode.SETS_WIDE_REGISTER), // case NEG_DOUBLE: { // instructions.add(new UnaryOperation(i, // OpID.NEGDOUBLE, regBank.get(destination), regBank.get(source))); // // break; // } // // INT_TO_LONG((byte)0x81, "int-to-long", ReferenceType.none, // Format.Format12x, Opcode.CAN_CONTINUE | Opcode.SETS_REGISTER | Opcode.SETS_WIDE_REGISTER), // case INT_TO_LONG: { // instructions.add(new UnaryOperation(i, // OpID.INTTOLONG, regBank.get(destination), regBank.get(source))); // // break; // } // // INT_TO_FLOAT((byte)0x82, "int-to-float", ReferenceType.none, // Format.Format12x, Opcode.CAN_CONTINUE | Opcode.SETS_REGISTER), // case INT_TO_FLOAT: { // instructions.add(new UnaryOperation(i, // OpID.INTTOFLOAT, regBank.get(destination), regBank.get(source))); // break; // } // // INT_TO_DOUBLE((byte)0x83, "int-to-double", ReferenceType.none, // Format.Format12x, Opcode.CAN_CONTINUE | Opcode.SETS_REGISTER | Opcode.SETS_WIDE_REGISTER), // case INT_TO_DOUBLE: { // instructions.add(new UnaryOperation(i, // OpID.INTTODOUBLE, regBank.get(destination), regBank.get(source))); // // break; // } // // LONG_TO_INT((byte)0x84, "long-to-int", ReferenceType.none, // Format.Format12x, Opcode.CAN_CONTINUE | Opcode.SETS_REGISTER), // case LONG_TO_INT: { // instructions.add(new UnaryOperation(i, // OpID.LONGTOINT, regBank.get(destination), regBank.get(source))); // // break; // } // // LONG_TO_FLOAT((byte)0x85, "long-to-float", ReferenceType.none, // Format.Format12x, Opcode.CAN_CONTINUE | Opcode.SETS_REGISTER), // case LONG_TO_FLOAT: { // instructions.add(new UnaryOperation(i, // OpID.LONGTOFLOAT, regBank.get(destination), regBank.get(source))); // // break; // } // // LONG_TO_DOUBLE((byte)0x86, "long-to-double", ReferenceType.none, // Format.Format12x, Opcode.CAN_CONTINUE | Opcode.SETS_REGISTER | Opcode.SETS_WIDE_REGISTER), // case LONG_TO_DOUBLE: { // instructions.add(new UnaryOperation(i, // OpID.LONGTODOUBLE, regBank.get(destination), regBank.get(source))); // // break; // } // // FLOAT_TO_INT((byte)0x87, "float-to-int", ReferenceType.none, // Format.Format12x, Opcode.CAN_CONTINUE | Opcode.SETS_REGISTER), // case FLOAT_TO_INT: { // instructions.add(new UnaryOperation(i, // OpID.FLOATTOINT, regBank.get(destination), regBank.get(source))); // // break; // } // // FLOAT_TO_LONG((byte)0x88, "float-to-long", ReferenceType.none, // Format.Format12x, Opcode.CAN_CONTINUE | Opcode.SETS_REGISTER | Opcode.SETS_WIDE_REGISTER), // case FLOAT_TO_LONG: { // instructions.add(new UnaryOperation(i, // OpID.FLOATTOLONG, regBank.get(destination), regBank.get(source))); // // break; // } // // FLOAT_TO_DOUBLE((byte)0x89, "float-to-double", ReferenceType.none, // Format.Format12x, Opcode.CAN_CONTINUE | Opcode.SETS_REGISTER | Opcode.SETS_WIDE_REGISTER), // case FLOAT_TO_DOUBLE: { // instructions.add(new UnaryOperation(i, // OpID.FLOATTODOUBLE, regBank.get(destination), regBank.get(source))); // // break; // } // // DOUBLE_TO_INT((byte)0x8a, "double-to-int", ReferenceType.none, // Format.Format12x, Opcode.CAN_CONTINUE | Opcode.SETS_REGISTER), // case DOUBLE_TO_INT: { // instructions.add(new UnaryOperation(i, // OpID.DOUBLETOINT, regBank.get(destination), regBank.get(source))); // // break; // } // // DOUBLE_TO_LONG((byte)0x8b, "double-to-long", ReferenceType.none, // Format.Format12x, Opcode.CAN_CONTINUE | Opcode.SETS_REGISTER | Opcode.SETS_WIDE_REGISTER), // case DOUBLE_TO_LONG: { // instructions.add(new UnaryOperation(i, // OpID.DOUBLETOLONG, regBank.get(destination), regBank.get(source))); // // break; // } // // DOUBLE_TO_FLOAT((byte)0x8c, "double-to-float", ReferenceType.none, // Format.Format12x, Opcode.CAN_CONTINUE | Opcode.SETS_REGISTER), // case DOUBLE_TO_FLOAT: { // instructions.add(new UnaryOperation(i, // OpID.DOUBLETOFLOAT, regBank.get(destination), regBank.get(source))); // // break; // } // // INT_TO_BYTE((byte)0x8d, "int-to-byte", ReferenceType.none, // Format.Format12x, Opcode.CAN_CONTINUE | Opcode.SETS_REGISTER), // case INT_TO_BYTE: { // instructions.add(new UnaryOperation(i, // OpID.INTTOBYTE, regBank.get(destination), regBank.get(source))); // // break; // } // // INT_TO_CHAR((byte)0x8e, "int-to-char", ReferenceType.none, // Format.Format12x, Opcode.CAN_CONTINUE | Opcode.SETS_REGISTER), // case INT_TO_CHAR: { // instructions.add(new UnaryOperation(i, // OpID.INTTOCHAR, regBank.get(destination), regBank.get(source))); // // break; // } // // INT_TO_SHORT((byte)0x8f, "int-to-short", ReferenceType.none, // Format.Format12x, Opcode.CAN_CONTINUE | Opcode.SETS_REGISTER), // case INT_TO_SHORT: { // instructions.add(new UnaryOperation(i, // OpID.INTTOSHORT, regBank.get(destination), regBank.get(source))); // // break; // } // // ADD_INT_2ADDR((byte)0xb0, "add-int/2addr", ReferenceType.none, // Format.Format12x, Opcode.CAN_CONTINUE | Opcode.SETS_REGISTER), // case ADD_INT_2ADDR: { // Register d = regBank.get(destination); // Register s = regBank.get(source); // instructions.add(new BinaryOperation(i, // BinaryOperation.OpID.ADD_INT, d, d, s)); // break; // } // // SUB_INT_2ADDR((byte)0xb1, "sub-int/2addr", ReferenceType.none, // Format.Format12x, Opcode.CAN_CONTINUE | Opcode.SETS_REGISTER), // case SUB_INT_2ADDR: { // Register d = regBank.get(destination); // Register s = regBank.get(source); // instructions.add(new BinaryOperation(i, // BinaryOperation.OpID.SUB_INT, d, d, s)); // break; // } // // MUL_INT_2ADDR((byte)0xb2, "mul-int/2addr", ReferenceType.none, // Format.Format12x, Opcode.CAN_CONTINUE | Opcode.SETS_REGISTER), // case MUL_INT_2ADDR: { // Register d = regBank.get(destination); // Register s = regBank.get(source); // instructions.add(new BinaryOperation(i, // BinaryOperation.OpID.MUL_INT, d, d, s)); // break; // } // // DIV_INT_2ADDR((byte)0xb3, "div-int/2addr", ReferenceType.none, // Format.Format12x, Opcode.CAN_THROW | Opcode.CAN_CONTINUE | Opcode.SETS_REGISTER), // case DIV_INT_2ADDR: { // Register d = regBank.get(destination); // Register s = regBank.get(source); // instructions.add(new BinaryOperation(i, // BinaryOperation.OpID.DIV_INT, d, d, s)); // break; // } // // REM_INT_2ADDR((byte)0xb4, "rem-int/2addr", ReferenceType.none, // Format.Format12x, Opcode.CAN_THROW | Opcode.CAN_CONTINUE | Opcode.SETS_REGISTER), // case REM_INT_2ADDR: { // Register d = regBank.get(destination); // Register s = regBank.get(source); // instructions.add(new BinaryOperation(i, // BinaryOperation.OpID.REM_INT, d, d, s)); // break; // } // // AND_INT_2ADDR((byte)0xb5, "and-int/2addr", ReferenceType.none, // Format.Format12x, Opcode.CAN_CONTINUE | Opcode.SETS_REGISTER), // case AND_INT_2ADDR: { // Register d = regBank.get(destination); // Register s = regBank.get(source); // instructions.add(new BinaryOperation(i, // BinaryOperation.OpID.AND_INT, d, d, s)); // break; // } // // OR_INT_2ADDR((byte)0xb6, "or-int/2addr", ReferenceType.none, // Format.Format12x, Opcode.CAN_CONTINUE | Opcode.SETS_REGISTER), // case OR_INT_2ADDR: { // Register d = regBank.get(destination); // Register s = regBank.get(source); // instructions.add(new BinaryOperation(i, // BinaryOperation.OpID.OR_INT, d, d, s)); // break; // } // // XOR_INT_2ADDR((byte)0xb7, "xor-int/2addr", ReferenceType.none, // Format.Format12x, Opcode.CAN_CONTINUE | Opcode.SETS_REGISTER), // case XOR_INT_2ADDR: { // Register d = regBank.get(destination); // Register s = regBank.get(source); // instructions.add(new BinaryOperation(i, // BinaryOperation.OpID.XOR_INT, d, d, s)); // break; // } // // SHL_INT_2ADDR((byte)0xb8, "shl-int/2addr", ReferenceType.none, // Format.Format12x, Opcode.CAN_CONTINUE | Opcode.SETS_REGISTER), // case SHL_INT_2ADDR: { // Register d = regBank.get(destination); // Register s = regBank.get(source); // instructions.add(new BinaryOperation(i, // BinaryOperation.OpID.SHL_INT, d, d, s)); // break; // } // // SHR_INT_2ADDR((byte)0xb9, "shr-int/2addr", ReferenceType.none, // Format.Format12x, Opcode.CAN_CONTINUE | Opcode.SETS_REGISTER), // case SHR_INT_2ADDR: { // Register d = regBank.get(destination); // Register s = regBank.get(source); // instructions.add(new BinaryOperation(i, // BinaryOperation.OpID.SHR_INT, d, d, s)); // break; // } // // USHR_INT_2ADDR((byte)0xba, "ushr-int/2addr", ReferenceType.none, // Format.Format12x, Opcode.CAN_CONTINUE | Opcode.SETS_REGISTER), // case USHR_INT_2ADDR: { // Register d = regBank.get(destination); // Register s = regBank.get(source); // instructions.add(new BinaryOperation(i, // BinaryOperation.OpID.USHR_INT, d, d, s)); // break; // } // // ADD_LONG_2ADDR((byte)0xbb, "add-long/2addr", ReferenceType.none, // Format.Format12x, Opcode.CAN_CONTINUE | Opcode.SETS_REGISTER | Opcode.SETS_WIDE_REGISTER), // case ADD_LONG_2ADDR: { // Register d = regBank.get(destination); // Register s = regBank.get(source); // instructions.add(new BinaryOperation(i, // BinaryOperation.OpID.ADD_LONG, d, d, s)); // break; // } // // SUB_LONG_2ADDR((byte)0xbc, "sub-long/2addr", ReferenceType.none, // Format.Format12x, Opcode.CAN_CONTINUE | Opcode.SETS_REGISTER | Opcode.SETS_WIDE_REGISTER), // case SUB_LONG_2ADDR: { // Register d = regBank.get(destination); // Register s = regBank.get(source); // instructions.add(new BinaryOperation(i, // BinaryOperation.OpID.SUB_LONG, d, d, s)); // break; // } // // MUL_LONG_2ADDR((byte)0xbd, "mul-long/2addr", ReferenceType.none, // Format.Format12x, Opcode.CAN_CONTINUE | Opcode.SETS_REGISTER | Opcode.SETS_WIDE_REGISTER), // case MUL_LONG_2ADDR: { // Register d = regBank.get(destination); // Register s = regBank.get(source); // instructions.add(new BinaryOperation(i, // BinaryOperation.OpID.MUL_LONG, d, d, s)); // break; // } // // DIV_LONG_2ADDR((byte)0xbe, "div-long/2addr", ReferenceType.none, // Format.Format12x, Opcode.CAN_THROW | Opcode.CAN_CONTINUE | Opcode.SETS_REGISTER | // Opcode.SETS_WIDE_REGISTER), // case DIV_LONG_2ADDR: { // Register d = regBank.get(destination); // Register s = regBank.get(source); // instructions.add(new BinaryOperation(i, // BinaryOperation.OpID.DIV_LONG, d, d, s)); // break; // } // // REM_LONG_2ADDR((byte)0xbf, "rem-long/2addr", ReferenceType.none, // Format.Format12x, Opcode.CAN_THROW | Opcode.CAN_CONTINUE | Opcode.SETS_REGISTER | // Opcode.SETS_WIDE_REGISTER), // case REM_LONG_2ADDR: { // Register d = regBank.get(destination); // Register s = regBank.get(source); // instructions.add(new BinaryOperation(i, // BinaryOperation.OpID.REM_LONG, d, d, s)); // break; // } // // AND_LONG_2ADDR((byte)0xc0, "and-long/2addr", ReferenceType.none, // Format.Format12x, Opcode.CAN_CONTINUE | Opcode.SETS_REGISTER | Opcode.SETS_WIDE_REGISTER), // case AND_LONG_2ADDR: { // Register d = regBank.get(destination); // Register s = regBank.get(source); // instructions.add(new BinaryOperation(i, // BinaryOperation.OpID.AND_LONG, d, d, s)); // break; // } // // OR_LONG_2ADDR((byte)0xc1, "or-long/2addr", ReferenceType.none, // Format.Format12x, Opcode.CAN_CONTINUE | Opcode.SETS_REGISTER | Opcode.SETS_WIDE_REGISTER), // case OR_LONG_2ADDR: { // Register d = regBank.get(destination); // Register s = regBank.get(source); // instructions.add(new BinaryOperation(i, // BinaryOperation.OpID.OR_LONG, d, d, s)); // break; // } // // XOR_LONG_2ADDR((byte)0xc2, "xor-long/2addr", ReferenceType.none, // Format.Format12x, Opcode.CAN_CONTINUE | Opcode.SETS_REGISTER | Opcode.SETS_WIDE_REGISTER), // case XOR_LONG_2ADDR: { // Register d = regBank.get(destination); // Register s = regBank.get(source); // instructions.add(new BinaryOperation(i, // BinaryOperation.OpID.XOR_LONG, d, d, s)); // break; // } // // SHL_LONG_2ADDR((byte)0xc3, "shl-long/2addr", ReferenceType.none, // Format.Format12x, Opcode.CAN_CONTINUE | Opcode.SETS_REGISTER | Opcode.SETS_WIDE_REGISTER), // case SHL_LONG_2ADDR: { // Register d = regBank.get(destination); // Register s = regBank.get(source); // instructions.add(new BinaryOperation(i, // BinaryOperation.OpID.SHL_LONG, d, d, s)); // break; // } // // SHR_LONG_2ADDR((byte)0xc4, "shr-long/2addr", ReferenceType.none, // Format.Format12x, Opcode.CAN_CONTINUE | Opcode.SETS_REGISTER | Opcode.SETS_WIDE_REGISTER), // case SHR_LONG_2ADDR: { // Register d = regBank.get(destination); // Register s = regBank.get(source); // instructions.add(new BinaryOperation(i, // BinaryOperation.OpID.SHR_LONG, d, d, s)); // break; // } // // USHR_LONG_2ADDR((byte)0xc5, "ushr-long/2addr", ReferenceType.none, // Format.Format12x, Opcode.CAN_CONTINUE | Opcode.SETS_REGISTER | Opcode.SETS_WIDE_REGISTER), // case USHR_LONG_2ADDR: { // Register d = regBank.get(destination); // Register s = regBank.get(source); // instructions.add(new BinaryOperation(i, // BinaryOperation.OpID.USHR_LONG, d, d, s)); // break; // } // // ADD_FLOAT_2ADDR((byte)0xc6, "add-float/2addr", ReferenceType.none, // Format.Format12x, Opcode.CAN_CONTINUE | Opcode.SETS_REGISTER), // case ADD_FLOAT_2ADDR: { // Register d = regBank.get(destination); // Register s = regBank.get(source); // instructions.add(new BinaryOperation(i, // BinaryOperation.OpID.ADD_FLOAT, d, d, s)); // break; // } // // SUB_FLOAT_2ADDR((byte)0xc7, "sub-float/2addr", ReferenceType.none, // Format.Format12x, Opcode.CAN_CONTINUE | Opcode.SETS_REGISTER), // case SUB_FLOAT_2ADDR: { // Register d = regBank.get(destination); // Register s = regBank.get(source); // instructions.add(new BinaryOperation(i, // BinaryOperation.OpID.SUB_FLOAT, d, d, s)); // break; // } // // MUL_FLOAT_2ADDR((byte)0xc8, "mul-float/2addr", ReferenceType.none, // Format.Format12x, Opcode.CAN_CONTINUE | Opcode.SETS_REGISTER), // case MUL_FLOAT_2ADDR: { // Register d = regBank.get(destination); // Register s = regBank.get(source); // instructions.add(new BinaryOperation(i, // BinaryOperation.OpID.MUL_FLOAT, d, d, s)); // break; // } // // DIV_FLOAT_2ADDR((byte)0xc9, "div-float/2addr", ReferenceType.none, // Format.Format12x, Opcode.CAN_CONTINUE | Opcode.SETS_REGISTER), // case DIV_FLOAT_2ADDR: { // Register d = regBank.get(destination); // Register s = regBank.get(source); // instructions.add(new BinaryOperation(i, // BinaryOperation.OpID.DIV_FLOAT, d, d, s)); // break; // } // // REM_FLOAT_2ADDR((byte)0xca, "rem-float/2addr", ReferenceType.none, // Format.Format12x, Opcode.CAN_CONTINUE | Opcode.SETS_REGISTER), // case REM_FLOAT_2ADDR: { // Register d = regBank.get(destination); // Register s = regBank.get(source); // instructions.add(new BinaryOperation(i, // BinaryOperation.OpID.REM_FLOAT, d, d, s)); // break; // } // // ADD_DOUBLE_2ADDR((byte)0xcb, "add-double/2addr", ReferenceType.none, // Format.Format12x, Opcode.CAN_CONTINUE | Opcode.SETS_REGISTER | Opcode.SETS_WIDE_REGISTER), // case ADD_DOUBLE_2ADDR: { // Register d = regBank.get(destination); // Register s = regBank.get(source); // instructions.add(new BinaryOperation(i, // BinaryOperation.OpID.ADD_DOUBLE, d, d, s)); // break; // } // // SUB_DOUBLE_2ADDR((byte)0xcc, "sub-double/2addr", ReferenceType.none, // Format.Format12x, Opcode.CAN_CONTINUE | Opcode.SETS_REGISTER | Opcode.SETS_WIDE_REGISTER), // case SUB_DOUBLE_2ADDR: { // Register d = regBank.get(destination); // Register s = regBank.get(source); // instructions.add(new BinaryOperation(i, // BinaryOperation.OpID.SUB_DOUBLE, d, d, s)); // break; // } // // MUL_DOUBLE_2ADDR((byte)0xcd, "mul-double/2addr", ReferenceType.none, // Format.Format12x, Opcode.CAN_CONTINUE | Opcode.SETS_REGISTER | Opcode.SETS_WIDE_REGISTER), // case MUL_DOUBLE_2ADDR: { // Register d = regBank.get(destination); // Register s = regBank.get(source); // instructions.add(new BinaryOperation(i, // BinaryOperation.OpID.MUL_DOUBLE, d, d, s)); // break; // } // // DIV_DOUBLE_2ADDR((byte)0xce, "div-double/2addr", ReferenceType.none, // Format.Format12x, Opcode.CAN_CONTINUE | Opcode.SETS_REGISTER | Opcode.SETS_WIDE_REGISTER), // case DIV_DOUBLE_2ADDR: { // Register d = regBank.get(destination); // Register s = regBank.get(source); // instructions.add(new BinaryOperation(i, // BinaryOperation.OpID.DIV_DOUBLE, d, d, s)); // break; // } // // REM_DOUBLE_2ADDR((byte)0xcf, "rem-double/2addr", ReferenceType.none, // Format.Format12x, Opcode.CAN_CONTINUE | Opcode.SETS_REGISTER | Opcode.SETS_WIDE_REGISTER), // case REM_DOUBLE_2ADDR: { // Register d = regBank.get(destination); // Register s = regBank.get(source); // instructions.add(new BinaryOperation(i, // BinaryOperation.OpID.REM_DOUBLE, d, d, s)); // break; // } // default: // break; // } // // break; // } // // case Format20t: { //goto/16 // // // Instruction20t dInst = (Instruction20t)instruction; // // int offset = dInst.getCodeOffset(); // instructions.add(new Goto(i,offset)); // break; // } // case Format30t: { //goto/32 // // // Instruction30t dInst = (Instruction30t)instruction; // // int offset = dInst.getCodeOffset(); // instructions.add(new Goto(i,offset)); // break; // } // // case Format21c: { // Instruction21c dInst = (Instruction21c) instruction; // // // switch (dInst.opcode) { // //CONST_STRING((byte)0x1a, "const-string", ReferenceType.string, // Format.Format21c, Opcode.CAN_THROW | Opcode.CAN_CONTINUE | Opcode.SETS_REGISTER), // case CONST_STRING: { // int destination = dInst.getRegisterA(); // instructions.add(new Constant.StringConstant(i, // dInst.getReferencedItem().getConciseIdentity(), // regBank.get(destination))); // // break; // } // // CONST_CLASS((byte)0x1c, "const-class", ReferenceType.type, // Format.Format21c, Opcode.CAN_THROW | Opcode.CAN_CONTINUE | Opcode.SETS_REGISTER), // case CONST_CLASS: { // int destination = dInst.getRegisterA(); // IClass value = // this.myClass.getClassLoader().lookupClass(TypeName.findOrCreate(dInst.getReferencedItem().getConciseIdentity())); // // instructions.add(new Constant.ClassConstant(i, // value, regBank.get(destination))); // break; // } // // CHECK_CAST((byte)0x1f, "check-cast", ReferenceType.type, Format.Format21c, // Opcode.CAN_THROW | Opcode.CAN_CONTINUE | Opcode.SETS_REGISTER), // case CHECK_CAST: { // int val = dInst.getRegisterA(); // String type = dInst.getReferencedItem().getConciseIdentity(); // instructions.add(new CheckCast(i, TypeReference // .findOrCreate(this.myClass.getClassLoader().getReference(), type), // regBank // .get(val))); // // break; // } // // NEW_INSTANCE((byte)0x22, "new-instance", ReferenceType.type, // Format.Format21c, Opcode.CAN_THROW | Opcode.CAN_CONTINUE | Opcode.SETS_REGISTER), // case NEW_INSTANCE: { // int destination = dInst.getRegisterA(); // String type = dInst.getReferencedItem().getConciseIdentity(); // instructions.add(new New(i, regBank // .get(destination), NewSiteReference.make(i, // TypeReference // .findOrCreate(this.myClass.getClassLoader().getReference(), // type)))); // break; // } // // SGET((byte)0x60, "sget", ReferenceType.field, Format.Format21c, // Opcode.CAN_THROW | Opcode.CAN_CONTINUE | Opcode.SETS_REGISTER), // case SGET: // // SGET_WIDE((byte)0x61, "sget-wide", ReferenceType.field, Format.Format21c, // Opcode.CAN_THROW | Opcode.CAN_CONTINUE | Opcode.SETS_REGISTER | Opcode.SETS_WIDE_REGISTER), // case SGET_WIDE: // // SGET_OBJECT((byte)0x62, "sget-object", ReferenceType.field, // Format.Format21c, Opcode.CAN_THROW | Opcode.CAN_CONTINUE | Opcode.SETS_REGISTER), // case SGET_OBJECT: // // SGET_BOOLEAN((byte)0x63, "sget-boolean", ReferenceType.field, // Format.Format21c, Opcode.CAN_THROW | Opcode.CAN_CONTINUE | Opcode.SETS_REGISTER), // case SGET_BOOLEAN: // // SGET_BYTE((byte)0x64, "sget-byte", ReferenceType.field, Format.Format21c, // Opcode.CAN_THROW | Opcode.CAN_CONTINUE | Opcode.SETS_REGISTER), // case SGET_BYTE: // // SGET_CHAR((byte)0x65, "sget-char", ReferenceType.field, Format.Format21c, // Opcode.CAN_THROW | Opcode.CAN_CONTINUE | Opcode.SETS_REGISTER), // case SGET_CHAR: // // SGET_SHORT((byte)0x66, "sget-short", ReferenceType.field, // Format.Format21c, Opcode.CAN_THROW | Opcode.CAN_CONTINUE | Opcode.SETS_REGISTER), // case SGET_SHORT: { // // /* TODO // Register destination = regBank.get(dInst.getRegisterA()); // Register source = regBank.get(dInst.getReferencedItem().getOffset()); // int fieldIndex = codes[pc++]; // this.eMethod // String clazzName = fieldClasses[fieldIndex]; // String fieldName = fieldNames[fieldIndex]; // String fieldType = fieldTypes[fieldIndex]; // // getField(false, frame, source, fieldIndex, destination); // instructions.add(new GetField.GetInstanceField( // instLoc, destination, source, clazzName, fieldName, // fieldType)); // */ // break; // } // // SPUT((byte)0x67, "sput", ReferenceType.field, Format.Format21c, // Opcode.CAN_THROW | Opcode.CAN_CONTINUE), // // SPUT_WIDE((byte)0x68, "sput-wide", ReferenceType.field, Format.Format21c, // Opcode.CAN_THROW | Opcode.CAN_CONTINUE), // // SPUT_OBJECT((byte)0x69, "sput-object", ReferenceType.field, // Format.Format21c, Opcode.CAN_THROW | Opcode.CAN_CONTINUE), // // SPUT_BOOLEAN((byte)0x6a, "sput-boolean", ReferenceType.field, // Format.Format21c, Opcode.CAN_THROW | Opcode.CAN_CONTINUE), // // SPUT_BYTE((byte)0x6b, "sput-byte", ReferenceType.field, Format.Format21c, // Opcode.CAN_THROW | Opcode.CAN_CONTINUE), // // SPUT_CHAR((byte)0x6c, "sput-char", ReferenceType.field, Format.Format21c, // Opcode.CAN_THROW | Opcode.CAN_CONTINUE), // // SPUT_SHORT((byte)0x6d, "sput-short", ReferenceType.field, // Format.Format21c, Opcode.CAN_THROW | Opcode.CAN_CONTINUE), // // SGET_VOLATILE((byte)0xe5, "sget-volatile", ReferenceType.field, // Format.Format21c, Opcode.ODEX_ONLY | Opcode.ODEXED_STATIC_VOLATILE | Opcode.CAN_THROW | // Opcode.CAN_CONTINUE | Opcode.SETS_REGISTER), // // SPUT_VOLATILE((byte)0xe6, "sput-volatile", ReferenceType.field, // Format.Format21c, Opcode.ODEX_ONLY | Opcode.ODEXED_STATIC_VOLATILE | Opcode.CAN_THROW | // Opcode.CAN_CONTINUE), // // SGET_WIDE_VOLATILE((byte)0xea, "sget-wide-volatile", ReferenceType.field, // Format.Format21c, Opcode.ODEX_ONLY | Opcode.ODEXED_STATIC_VOLATILE | Opcode.CAN_THROW | // Opcode.CAN_CONTINUE | Opcode.SETS_REGISTER | Opcode.SETS_WIDE_REGISTER), // // SPUT_WIDE_VOLATILE((byte)0xeb, "sput-wide-volatile", ReferenceType.field, // Format.Format21c, Opcode.ODEX_ONLY | Opcode.ODEXED_STATIC_VOLATILE | Opcode.CAN_THROW | // Opcode.CAN_CONTINUE), // // SGET_OBJECT_VOLATILE((byte)0xfd, "sget-object-volatile", // ReferenceType.field, Format.Format21c, Opcode.ODEX_ONLY | Opcode.ODEXED_STATIC_VOLATILE | // Opcode.CAN_THROW | Opcode.CAN_CONTINUE | Opcode.SETS_REGISTER), // // SPUT_OBJECT_VOLATILE((byte)0xfe, "sput-object-volatile", // ReferenceType.field, Format.Format21c, Opcode.ODEX_ONLY | Opcode.ODEXED_STATIC_VOLATILE | // Opcode.CAN_THROW | Opcode.CAN_CONTINUE); // default: // break; // } // break; // } // // case Format21t: { // // Instruction21t dInst = (Instruction21t)instruction; // // Register oper1 = regBank.get(dInst.getRegisterA()); // int offset = dInst.getCodeOffset(); // // switch(dInst.opcode) { // case IF_EQZ: // instructions.add(new Branch.UnaryBranch(i, // offset, Branch.UnaryBranch.CompareOp.EQZ, oper1)); // break; // case IF_NEZ: // instructions.add(new Branch.UnaryBranch(i, // offset, Branch.UnaryBranch.CompareOp.NEZ, oper1)); // break; // case IF_LTZ: // instructions.add(new Branch.UnaryBranch(i, // offset, Branch.UnaryBranch.CompareOp.LTZ, oper1)); // break; // case IF_GEZ: // instructions.add(new Branch.UnaryBranch(i, // offset, Branch.UnaryBranch.CompareOp.GEZ, oper1)); // break; // case IF_GTZ: // instructions.add(new Branch.UnaryBranch(i, // offset, Branch.UnaryBranch.CompareOp.GTZ, oper1)); // break; // case IF_LEZ: // instructions.add(new Branch.UnaryBranch(i, // offset, Branch.UnaryBranch.CompareOp.LEZ, oper1)); // break; // default: // logger.debug(instruction.opcode.name + " - " + // instruction.getFormat().toString()); // break; // } // /* // IF_EQZ((byte)0x38, "if-eqz", ReferenceType.none, Format.Format21t, Opcode.CAN_CONTINUE), // IF_NEZ((byte)0x39, "if-nez", ReferenceType.none, Format.Format21t, Opcode.CAN_CONTINUE), // IF_LTZ((byte)0x3a, "if-ltz", ReferenceType.none, Format.Format21t, Opcode.CAN_CONTINUE), // IF_GEZ((byte)0x3b, "if-gez", ReferenceType.none, Format.Format21t, Opcode.CAN_CONTINUE), // IF_GTZ((byte)0x3c, "if-gtz", ReferenceType.none, Format.Format21t, Opcode.CAN_CONTINUE), // IF_LEZ((byte)0x3d, "if-lez", ReferenceType.none, Format.Format21t, Opcode.CAN_CONTINUE), // // */ // break; // } // case Format22t: { // Instruction22t dInst = (Instruction22t)instruction; // // // Register oper1 = regBank.get(dInst.getRegisterA()); // Register oper2 = regBank.get(dInst.getRegisterB()); // int offset = dInst.getTargetAddressOffset(); // // switch(dInst.opcode) { // case IF_EQ: // instructions.add(new Branch.BinaryBranch(i, offset, // Branch.BinaryBranch.CompareOp.EQ, oper1, oper2)); // break; // case IF_NE: // instructions.add(new Branch.BinaryBranch(i, offset, // Branch.BinaryBranch.CompareOp.NE, oper1, oper2)); // break; // case IF_LT: // instructions.add(new Branch.BinaryBranch(i, offset, // Branch.BinaryBranch.CompareOp.LT, oper1, oper2)); // break; // case IF_GE: // instructions.add(new Branch.BinaryBranch(i, offset, // Branch.BinaryBranch.CompareOp.GE, oper1, oper2)); // break; // case IF_GT: // instructions.add(new Branch.BinaryBranch(i, offset, // Branch.BinaryBranch.CompareOp.GT, oper1, oper2)); // break; // case IF_LE: // instructions.add(new Branch.BinaryBranch(i, offset, // Branch.BinaryBranch.CompareOp.LE, oper1, oper2)); // break; // default: // logger.debug(instruction.opcode.name + " - " + // instruction.getFormat().toString()); // break; // } /// * IF_EQ((byte)0x32, "if-eq", ReferenceType.none, Format.Format22t, // Opcode.CAN_CONTINUE), // IF_NE((byte)0x33, "if-ne", ReferenceType.none, Format.Format22t, // Opcode.CAN_CONTINUE), // IF_LT((byte)0x34, "if-lt", ReferenceType.none, Format.Format22t, // Opcode.CAN_CONTINUE), // IF_GE((byte)0x35, "if-ge", ReferenceType.none, Format.Format22t, // Opcode.CAN_CONTINUE), // IF_GT((byte)0x36, "if-gt", ReferenceType.none, Format.Format22t, // Opcode.CAN_CONTINUE), // IF_LE((byte)0x37, "if-le", ReferenceType.none, Format.Format22t, // Opcode.CAN_CONTINUE), // */ // break; // } // case Format31t: { // /* PACKED_SWITCH((byte)0x2b, "packed-switch", ReferenceType.none, // Format.Format31t, Opcode.CAN_CONTINUE), // SPARSE_SWITCH((byte)0x2c, "sparse-switch", ReferenceType.none, Format.Format31t, // Opcode.CAN_CONTINUE), // */ // Instruction31t dInst = (Instruction31t)instruction; // Register val = regBank.get(dInst.getRegisterA()); // int offset = dInst.getTargetAddressOffset(); // // instructions.add(new Switch(i, // // getSparseSwitchPad(offset, codes, 3), val)); // break; // } // // // // case Format35c: { // // // = invoke virtual // //iinstructions[i] = new IInstruction35c((Instruction35c)instruction, this); // break; // } // // // default: // logger.debug(instruction.opcode.name + " - " + // instruction.getFormat().toString()); // break; // } // // // } // // //comment out stop } private static TypeReference findOutArrayElementType( org.jf.dexlib2.iface.instruction.Instruction inst, Instruction[] walaInstructions, int instCounter) { if (instCounter < 0) { throw new IllegalArgumentException(); } else if (instCounter == 0) { throw new UnsupportedOperationException( "fill-array-data as first instruction is not supported!"); } Instruction31t arrayFill = (Instruction31t) inst; int interestingRegister = arrayFill.getRegisterA(); int curCounter = instCounter - 1; while (curCounter >= 0) { Instruction curInst = walaInstructions[curCounter]; // do we have a 'new-array'-instruction, where the destination register coincides with the // current interesting register? // then we return the element type of that array if (curInst.getOpcode() == Opcode.NEW_ARRAY) { NewArray newArray = (NewArray) walaInstructions[curCounter]; if (newArray.destination == interestingRegister) { return newArray.newSiteRef.getDeclaredType().getArrayElementType(); } } else if (curInst.getOpcode() == Opcode.MOVE_OBJECT || curInst.getOpcode() == Opcode.MOVE_OBJECT_16 || curInst.getOpcode() == Opcode.MOVE_OBJECT_FROM16) { UnaryOperation uo = (UnaryOperation) curInst; if (uo.destination == interestingRegister) { interestingRegister = uo.source; } } // all other instructions are ignored curCounter--; } throw new UnsupportedOperationException( "found a fill-array-data instruction without a corresponding new-array instruction. This should not happen!"); } protected void handleINVOKE_VIRTUAL( int instLoc, String cname, String mname, String pname, int[] args, Opcode opcode) { instructions.add(new Invoke.InvokeVirtual(instLoc, cname, mname, pname, args, opcode, this)); } public Instruction[] getDexInstructions() { return instructions().toArray(new Instruction[0]); } protected InstructionArray instructions() { if (instructions == null) parseBytecode(); return instructions; } public int getAddressFromIndex(int index) { return instructions().getPcFromIndex(index); } @Override public int getInstructionIndex(int bytecodeindex) { return instructions().getIndexFromPc(bytecodeindex); } public Instruction getInstructionFromIndex(int instructionIndex) { return instructions().getFromId(instructionIndex); } private static final IndirectionData NO_INDIRECTIONS = new IndirectionData() { private final int[] NOTHING = new int[0]; @Override public int[] indirectlyReadLocals(int instructionIndex) { return NOTHING; } @Override public int[] indirectlyWrittenLocals(int instructionIndex) { return NOTHING; } }; @Override public IndirectionData getIndirectionData() { return NO_INDIRECTIONS; } // ------------------------------------------- // MethodAnnotationIteratorDelegate Methods // ------------------------------------------- // /** // * Delegate called by the class in order to parse the method annotations. // */ // public void processMethodAnnotations(MethodIdItem mIdItem, // AnnotationSetItem anoSet) { // //System.out.println("DexIMethod: processMethodAnnotations()"); // if ( mIdItem.equals(eMethod.method) ){ // AnnotationItem[] items = anoSet.getAnnotations(); // for (AnnotationItem item : items) { // // } // // } // } /** * @throws UnsupportedOperationException * <p>TODO: Review this implementation - it may be horribly wrong! */ @Override public Collection<CallSiteReference> getCallSites() { if (isNative()) { return Collections.emptySet(); } // assert(false) : "Please review getCallSites-Implementation before use!"; // TODO ArrayList<CallSiteReference> csites = new ArrayList<>(); // XXX The call Sites in this method or to this method?!!! for (Instruction inst : instructions()) { if (inst instanceof Invoke) { // Locate the Target MethodReference target = MethodReference.findOrCreate( getDeclaringClass() .getClassLoader() .getReference(), // XXX: Is this the correct class loader? ((Invoke) inst).clazzName, ((Invoke) inst).methodName, ((Invoke) inst).descriptor); csites.add( CallSiteReference.make( inst.pc, // programCounter target, // declaredTarget ((Invoke) inst).getInvocationCode() // invocationCode )); } } return csites; } @Override public Iterator<com.ibm.wala.types.FieldReference> getFieldsRead() { if (isNative()) { return Collections.emptyIterator(); } ArrayList<com.ibm.wala.types.FieldReference> fsites = new ArrayList<>(); for (Instruction inst : instructions()) { if (inst instanceof GetField) { fsites.add( com.ibm.wala.types.FieldReference.findOrCreate( getDeclaringClass().getClassLoader().getReference(), ((GetField) inst).clazzName, ((GetField) inst).fieldName, ((GetField) inst).fieldType)); } } return fsites.iterator(); } @Override public Iterator<com.ibm.wala.types.FieldReference> getFieldsWritten() { if (isNative()) { return Collections.emptyIterator(); } ArrayList<com.ibm.wala.types.FieldReference> fsites = new ArrayList<>(); for (Instruction inst : instructions()) { if (inst instanceof PutField) { fsites.add( com.ibm.wala.types.FieldReference.findOrCreate( getDeclaringClass().getClassLoader().getReference(), ((PutField) inst).clazzName, ((PutField) inst).fieldName, ((PutField) inst).fieldType)); } } return fsites.iterator(); } @Override public Iterator<TypeReference> getArraysWritten() { if (isNative()) { return Collections.emptyIterator(); } ArrayList<TypeReference> asites = new ArrayList<>(); for (Instruction inst : instructions()) { if (inst instanceof ArrayPut) { asites.add(((ArrayPut) inst).getType()); } } return asites.iterator(); } @Override public Collection<NewSiteReference> getNewSites() { if (isNative()) { return Collections.emptySet(); } ArrayList<NewSiteReference> nsites = new ArrayList<>(); for (Instruction inst : instructions()) { if (inst instanceof New) { nsites.add(((New) inst).newSiteRef); } } return nsites; } @Override public SourcePosition getSourcePosition(int instructionIndex) { return null; } @Override public SourcePosition getParameterSourcePosition(int paramNum) { return null; } @Override public Collection<Annotation> getAnnotations() { return myClass.getAnnotations(eMethod, null); } @Override public Collection<Annotation> getAnnotations(boolean runtimeInvisible) { return myClass.getAnnotations(eMethod, DexIClass.getTypes(runtimeInvisible)); } @Override public Collection<Annotation>[] getParameterAnnotations() { Map<Integer, List<Annotation>> raw = myClass.getParameterAnnotations(eMethod); @SuppressWarnings("unchecked") Collection<Annotation>[] result = new Collection[getReference().getNumberOfParameters()]; for (Map.Entry<Integer, List<Annotation>> x : raw.entrySet()) { result[x.getKey()] = x.getValue(); } return result; } }
191,751
39.428421
354
java
WALA
WALA-master/dalvik/src/main/java/com/ibm/wala/dalvik/classLoader/DexIRFactory.java
/* * Copyright (c) 2002 - 2006, 2011 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 Chaudhur, Steve Suh - Modified ShrikeIRFactory to work with Dalvik */ package com.ibm.wala.dalvik.classLoader; import com.ibm.wala.cfg.ControlFlowGraph; import com.ibm.wala.classLoader.IMethod; import com.ibm.wala.dalvik.ssa.DexSSABuilder; import com.ibm.wala.ipa.callgraph.Context; import com.ibm.wala.ssa.DefaultIRFactory; import com.ibm.wala.ssa.IR; import com.ibm.wala.ssa.SSACFG; import com.ibm.wala.ssa.SSAInstruction; import com.ibm.wala.ssa.SSAOptions; import com.ibm.wala.ssa.ShrikeIndirectionData; import com.ibm.wala.ssa.SymbolTable; import com.ibm.wala.ssa.analysis.DeadAssignmentElimination; public class DexIRFactory extends DefaultIRFactory { public static final boolean buildLocalMap = false; @Override public ControlFlowGraph<?, ?> makeCFG(IMethod method, Context C) throws IllegalArgumentException { if (method == null) { throw new IllegalArgumentException("null method"); } if (method instanceof DexIMethod) return new DexCFG((DexIMethod) method, C); return super.makeCFG(method, C); } @Override public IR makeIR(IMethod _method, Context C, final SSAOptions options) throws IllegalArgumentException { if (_method == null) { throw new IllegalArgumentException("null method"); } if (!(_method instanceof DexIMethod)) return super.makeIR(_method, C, options); final DexIMethod method = (DexIMethod) _method; // com.ibm.wala.shrikeBT.IInstruction[] instructions = null; // try { // instructions = method.getInstructions(); // } catch (InvalidClassFileException e) { // e.printStackTrace(); // Assertions.UNREACHABLE(); // } final DexCFG cfg = (DexCFG) makeCFG(method, C); // calculate the SSA registers from the given cfg // TODO: check this final SymbolTable symbolTable = new SymbolTable(method.getNumberOfParameters()); // final SymbolTable symbolTable = new SymbolTable(method.getNumberOfParameterRegisters()); final SSAInstruction[] newInstrs = new SSAInstruction[method.getDexInstructions().length]; final SSACFG newCfg = new SSACFG(method, cfg, newInstrs); return new IR(method, newInstrs, symbolTable, newCfg, options) { private final SSA2LocalMap localMap; private final ShrikeIndirectionData indirectionData; /** * Remove any phis that are dead assignments. * * <p>TODO: move this elsewhere? */ private void eliminateDeadPhis() { DeadAssignmentElimination.perform(this); } @Override protected String instructionPosition(int instructionIndex) { int bcIndex = method.getBytecodeIndex(instructionIndex); int lineNumber = method.getLineNumber(bcIndex); if (lineNumber == -1) { return ""; } else { return "(line " + lineNumber + ')'; } } @Override public SSA2LocalMap getLocalMap() { return localMap; } { DexSSABuilder builder = DexSSABuilder.make( method, newCfg, cfg, newInstrs, symbolTable, buildLocalMap, options.getPiNodePolicy()); builder.build(); if (buildLocalMap) localMap = builder.getLocalMap(); else localMap = null; indirectionData = builder.getIndirectionData(); eliminateDeadPhis(); setupLocationMap(); // System.out.println("Successfully built a Dex IR!"); // for(SSAInstruction ssaInst:newInstrs) // { // System.out.println("\t"+ssaInst); // } } @SuppressWarnings("unchecked") @Override protected ShrikeIndirectionData getIndirectionData() { return indirectionData; } }; } @Override public boolean contextIsIrrelevant(IMethod method) { if (method == null) { throw new IllegalArgumentException("null method"); } if (method instanceof DexIMethod) return true; return super.contextIsIrrelevant(method); } }
4,514
30.573427
100
java
WALA
WALA-master/dalvik/src/main/java/com/ibm/wala/dalvik/classLoader/DexModuleEntry.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> * Steve Suh <suhsteve@gmail.com> * * 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.classLoader; import com.ibm.wala.classLoader.Module; import com.ibm.wala.classLoader.ModuleEntry; import java.io.InputStream; import org.jf.dexlib2.iface.ClassDef; public class DexModuleEntry implements ModuleEntry { private final ClassDef classDefItem; private final String className; private final DexFileModule container; public DexModuleEntry(ClassDef cdefitems, DexFileModule container) { classDefItem = cdefitems; this.container = container; String temp = cdefitems.getType(); // className = temp; if (temp.endsWith(";")) className = temp.substring(0, temp.length() - 1); // remove last ';' else className = temp; // System.out.println(className); } public ClassDef getClassDefItem() { return classDefItem; } /* * (non-Javadoc) * @see com.ibm.wala.classLoader.ModuleEntry#asModule() */ @Override public Module asModule() { throw new UnsupportedOperationException(); } /* * (non-Javadoc) * @see com.ibm.wala.classLoader.ModuleEntry#getClassName() */ @Override public String getClassName() { return className; } /* * (non-Javadoc) * @see com.ibm.wala.classLoader.ModuleEntry#getInputStream() */ @Override public InputStream getInputStream() { throw new UnsupportedOperationException(); } /* * (non-Javadoc) * @see com.ibm.wala.classLoader.ModuleEntry#getName() */ @Override public String getName() { return className; } /* * (non-Javadoc) * @see com.ibm.wala.classLoader.ModuleEntry#isClassFile() */ @Override public boolean isClassFile() { return false; } /* * (non-Javadoc) * @see com.ibm.wala.classLoader.ModuleEntry#isModuleFile() */ @Override public boolean isModuleFile() { return false; } /* * (non-Javadoc) * @see com.ibm.wala.classLoader.ModuleEntry#isSourceFile() */ @Override public boolean isSourceFile() { return false; } @Override public DexFileModule getContainer() { return container; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((className == null) ? 0 : className.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (!(obj instanceof DexModuleEntry)) { return false; } DexModuleEntry other = (DexModuleEntry) obj; if (className == null) { if (other.className != null) { return false; } } else if (!className.equals(other.className)) { return false; } return true; } }
4,695
25.988506
96
java
WALA
WALA-master/dalvik/src/main/java/com/ibm/wala/dalvik/classLoader/DexUtil.java
package com.ibm.wala.dalvik.classLoader; import static org.jf.dexlib2.ValueType.ANNOTATION; import static org.jf.dexlib2.ValueType.ARRAY; import static org.jf.dexlib2.ValueType.BOOLEAN; import static org.jf.dexlib2.ValueType.BYTE; import static org.jf.dexlib2.ValueType.CHAR; import static org.jf.dexlib2.ValueType.DOUBLE; import static org.jf.dexlib2.ValueType.ENUM; import static org.jf.dexlib2.ValueType.FIELD; import static org.jf.dexlib2.ValueType.FLOAT; import static org.jf.dexlib2.ValueType.INT; import static org.jf.dexlib2.ValueType.LONG; import static org.jf.dexlib2.ValueType.METHOD; import static org.jf.dexlib2.ValueType.NULL; import static org.jf.dexlib2.ValueType.SHORT; import static org.jf.dexlib2.ValueType.STRING; import static org.jf.dexlib2.ValueType.TYPE; import com.ibm.wala.core.util.strings.Atom; import com.ibm.wala.core.util.strings.ImmutableByteArray; import com.ibm.wala.shrike.shrikeCT.AnnotationsReader.AnnotationAttribute; import com.ibm.wala.shrike.shrikeCT.AnnotationsReader.ArrayElementValue; import com.ibm.wala.shrike.shrikeCT.AnnotationsReader.ConstantElementValue; import com.ibm.wala.shrike.shrikeCT.AnnotationsReader.ElementValue; import com.ibm.wala.shrike.shrikeCT.AnnotationsReader.EnumElementValue; import com.ibm.wala.types.ClassLoaderReference; import com.ibm.wala.types.Descriptor; import com.ibm.wala.types.FieldReference; import com.ibm.wala.types.MethodReference; import com.ibm.wala.types.TypeName; import com.ibm.wala.types.TypeReference; import com.ibm.wala.types.annotations.Annotation; import com.ibm.wala.util.collections.HashMapFactory; import com.ibm.wala.util.collections.HashSetFactory; import java.util.Collection; import java.util.List; import java.util.Map; import org.jf.dexlib2.iface.AnnotationElement; import org.jf.dexlib2.iface.value.AnnotationEncodedValue; import org.jf.dexlib2.iface.value.ArrayEncodedValue; import org.jf.dexlib2.iface.value.BooleanEncodedValue; import org.jf.dexlib2.iface.value.ByteEncodedValue; import org.jf.dexlib2.iface.value.CharEncodedValue; import org.jf.dexlib2.iface.value.DoubleEncodedValue; import org.jf.dexlib2.iface.value.EncodedValue; import org.jf.dexlib2.iface.value.EnumEncodedValue; import org.jf.dexlib2.iface.value.FieldEncodedValue; import org.jf.dexlib2.iface.value.FloatEncodedValue; import org.jf.dexlib2.iface.value.IntEncodedValue; import org.jf.dexlib2.iface.value.LongEncodedValue; import org.jf.dexlib2.iface.value.MethodEncodedValue; import org.jf.dexlib2.iface.value.ShortEncodedValue; import org.jf.dexlib2.iface.value.StringEncodedValue; import org.jf.dexlib2.iface.value.TypeEncodedValue; public class DexUtil { static Collection<Annotation> getAnnotations( Collection<org.jf.dexlib2.iface.Annotation> as, ClassLoaderReference clr) { Collection<Annotation> result = HashSetFactory.make(); for (org.jf.dexlib2.iface.Annotation a : as) { result.add(getAnnotation(a, clr)); } return result; } static Annotation getAnnotation(org.jf.dexlib2.iface.Annotation ea, ClassLoaderReference clr) { Map<String, ElementValue> values = HashMapFactory.make(); TypeReference at = getTypeRef(ea.getType(), clr); for (AnnotationElement elt : ea.getElements()) { String name = elt.getName(); EncodedValue v = elt.getValue(); ElementValue value = getValue(clr, v); values.put(name, value); } return Annotation.makeWithNamed(at, values); } static ElementValue getValue(ClassLoaderReference clr, EncodedValue v) { switch (v.getValueType()) { case ANNOTATION: { Map<String, ElementValue> values = HashMapFactory.make(); String at = ((AnnotationEncodedValue) v).getType(); for (AnnotationElement elt : ((AnnotationEncodedValue) v).getElements()) { String name = elt.getName(); EncodedValue ev = elt.getValue(); ElementValue value = getValue(clr, ev); values.put(name, value); } return new AnnotationAttribute(at, values); } case ARRAY: { List<? extends EncodedValue> vs = ((ArrayEncodedValue) v).getValue(); ElementValue[] rs = new ElementValue[vs.size()]; int idx = 0; for (EncodedValue ev : vs) { rs[idx++] = getValue(clr, ev); } return new ArrayElementValue(rs); } case BOOLEAN: Boolean bl = ((BooleanEncodedValue) v).getValue(); return new ConstantElementValue(bl); case BYTE: Byte bt = ((ByteEncodedValue) v).getValue(); return new ConstantElementValue(bt); case CHAR: Character c = ((CharEncodedValue) v).getValue(); return new ConstantElementValue(c); case DOUBLE: Double d = ((DoubleEncodedValue) v).getValue(); return new ConstantElementValue(d); case ENUM: org.jf.dexlib2.iface.reference.FieldReference o = ((EnumEncodedValue) v).getValue(); return new EnumElementValue(o.getType(), o.getName()); case FIELD: o = v.getValueType() == ENUM ? ((EnumEncodedValue) v).getValue() : ((FieldEncodedValue) v).getValue(); String fieldName = o.getName(); TypeReference ft = getTypeRef(o.getType(), clr); TypeReference ct = getTypeRef(o.getDefiningClass(), clr); return new ConstantElementValue( FieldReference.findOrCreate(ct, Atom.findOrCreateUnicodeAtom(fieldName), ft)); case FLOAT: Float f = ((FloatEncodedValue) v).getValue(); return new ConstantElementValue(f); case INT: Integer iv = ((IntEncodedValue) v).getValue(); return new ConstantElementValue(iv); case LONG: Long l = ((LongEncodedValue) v).getValue(); return new ConstantElementValue(l); case METHOD: org.jf.dexlib2.iface.reference.MethodReference m = ((MethodEncodedValue) v).getValue(); ct = getTypeRef(m.getDefiningClass(), clr); String methodName = m.getName(); String methodSig = getSignature(m); return new ConstantElementValue( MethodReference.findOrCreate( ct, Atom.findOrCreateUnicodeAtom(methodName), Descriptor.findOrCreateUTF8(methodSig))); case NULL: return new ConstantElementValue(null); case SHORT: Short s = ((ShortEncodedValue) v).getValue(); return new ConstantElementValue(s); case STRING: String str = ((StringEncodedValue) v).getValue(); return new ConstantElementValue(str); case TYPE: String t = ((TypeEncodedValue) v).getValue(); return new ConstantElementValue(getTypeName(t) + ";"); default: assert false : v; return null; } } static String getSignature(org.jf.dexlib2.iface.reference.MethodReference ref) { StringBuilder sig = new StringBuilder("("); for (CharSequence p : ref.getParameterTypes()) { sig = sig.append(p); } sig.append(')').append(ref.getReturnType()); return sig.toString(); } static TypeReference getTypeRef(String type, ClassLoaderReference clr) { return TypeReference.findOrCreate(clr, getTypeName(type)); } static TypeName getTypeName(String fieldType) { ImmutableByteArray fieldTypeArray = ImmutableByteArray.make(fieldType); TypeName T = null; if (fieldTypeArray.get(fieldTypeArray.length() - 1) == ';') { T = TypeName.findOrCreate(fieldTypeArray, 0, fieldTypeArray.length() - 1); } else { T = TypeName.findOrCreate(fieldTypeArray); } return T; } }
7,664
35.674641
97
java
WALA
WALA-master/dalvik/src/main/java/com/ibm/wala/dalvik/classLoader/InstructionArray.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, * * Jonathan Bardin <astrosus@gmail.com> * Steve Suh <suhsteve@gmail.com> * * 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.classLoader; import com.ibm.wala.dalvik.dex.instructions.Instruction; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; /** * Collection of Instruction wich allow to get an instruction from its table index id or from its * bytecode index. It's not allowed to remove an element. */ public class InstructionArray implements Collection<Instruction> { List<Instruction> instructions; Map<Integer, Integer> pc2index; List<Integer> index2pc; public InstructionArray() { instructions = new ArrayList<>(); pc2index = new HashMap<>(); index2pc = new ArrayList<>(); } @Override public boolean add(Instruction e) { boolean ret = instructions.add(e); if (ret) { pc2index.put(e.pc, size() - 1); index2pc.add(e.pc); } return ret; } @Override public boolean addAll(Collection<? extends Instruction> c) { boolean ret = false; for (Instruction instruction : c) { ret |= add(instruction); } return ret; } @Override public boolean contains(Object o) { return instructions.contains(o); } @Override public boolean containsAll(Collection<?> c) { return instructions.containsAll(c); } @Override public boolean equals(Object o) { return instructions.equals(o); } @Override public int hashCode() { return instructions.hashCode(); } public int indexOf(Object o) { return instructions.indexOf(o); } @Override public boolean isEmpty() { return instructions.isEmpty(); } @Override public Iterator<Instruction> iterator() { return instructions.iterator(); } @Override public void clear() { throw new UnsupportedOperationException(); } @Override public boolean remove(Object o) { throw new UnsupportedOperationException(); } @Override public boolean removeAll(Collection<?> c) { throw new UnsupportedOperationException(); } @Override public boolean retainAll(Collection<?> c) { throw new UnsupportedOperationException(); } @Override public int size() { return instructions.size(); } @Override public Object[] toArray() { return instructions.toArray(); } @Override public <T> T[] toArray(T[] a) { return instructions.toArray(a); } /** * @param pc the byte code index. * @return The index of the instruction of given byte code index */ public int getIndexFromPc(int pc) { if (!pc2index.containsKey(pc) && pc2index.containsKey(pc + 1)) { pc++; } return pc2index.get(pc); } /** * @param index the instruction index. * @return The byte code address of the instruction index */ public int getPcFromIndex(int index) { return index2pc.get(index); } /** @return The instruction from its id. */ public Instruction getFromId(int id) { return instructions.get(id); } /** @return The instruction from its pc. */ public Instruction getFromPc(int pc) { return instructions.get(pc2index.get(pc)); } }
5,051
25.041237
97
java
WALA
WALA-master/dalvik/src/main/java/com/ibm/wala/dalvik/classLoader/Literal.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> * Steve Suh <suhsteve@gmail.com> * * 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.classLoader; public abstract class Literal { public int value; public static class IntLiteral extends Literal { public final int value; public IntLiteral(int value) { this.value = value; } } public static class LongLiteral extends Literal { public final long value; public LongLiteral(long value) { this.value = value; } } public static class FloatLiteral extends Literal { public final float value; public FloatLiteral(float value) { this.value = value; } } public static class DoubleLiteral extends Literal { public final double value; public DoubleLiteral(double value) { this.value = value; } } }
2,709
30.511628
79
java
WALA
WALA-master/dalvik/src/main/java/com/ibm/wala/dalvik/classLoader/WDexClassLoaderImpl.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, * * Jonathan Bardin <astrosus@gmail.com> * Steve Suh <suhsteve@gmail.com> * * 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.classLoader; import com.ibm.wala.classLoader.ClassLoaderImpl; import com.ibm.wala.classLoader.IClass; import com.ibm.wala.classLoader.IClassLoader; import com.ibm.wala.classLoader.Module; import com.ibm.wala.classLoader.ModuleEntry; import com.ibm.wala.core.util.warnings.Warning; import com.ibm.wala.core.util.warnings.Warnings; import com.ibm.wala.ipa.cha.IClassHierarchy; import com.ibm.wala.types.ClassLoaderReference; import com.ibm.wala.types.TypeName; import com.ibm.wala.util.collections.HashSetFactory; import com.ibm.wala.util.collections.Iterator2Iterable; import com.ibm.wala.util.config.SetOfClasses; import java.io.IOException; import java.util.Collection; import java.util.HashSet; import java.util.List; import java.util.Set; /** ClassLoader for Java &amp; Dalvik. */ public class WDexClassLoaderImpl extends ClassLoaderImpl { private final IClassLoader lParent; private final SetOfClasses exclusions; // Commented out until IBM fixes ClassLoaderFactoryImpl "protected IClassLoader // makeNewClassLoader" // public WDexClassLoaderImpl(ClassLoaderReference loader, // ArrayClassLoader arrayClassLoader, IClassLoader parent, // SetOfClasses exclusions, IClassHierarchy cha) { // super(loader, arrayClassLoader, parent, exclusions, cha); // lParent = parent; // lExclusions = exclusions; // //DEBUG_LEVEL = 0; // } public WDexClassLoaderImpl( ClassLoaderReference loader, IClassLoader parent, SetOfClasses exclusions, IClassHierarchy cha) { super(loader, cha.getScope().getArrayClassLoader(), parent, exclusions, cha); lParent = parent; this.exclusions = exclusions; // DEBUG_LEVEL = 0; } @Override public void init(List<Module> modules) throws IOException { super.init(modules); // module are loaded according to the given order (same as in Java VM) Set<ModuleEntry> classModuleEntries = HashSetFactory.make(); for (Module archive : modules) { Set<ModuleEntry> classFiles = getDexFiles(archive); removeClassFiles(classFiles, classModuleEntries); loadAllDexClasses(classFiles); classModuleEntries.addAll(classFiles); } } /** Remove from s any class file module entries which already are in t */ private static void removeClassFiles(Set<ModuleEntry> s, Set<ModuleEntry> t) { s.removeAll(t); } private static Set<ModuleEntry> getDexFiles(Module M) { HashSet<ModuleEntry> result = HashSetFactory.make(); for (ModuleEntry entry : Iterator2Iterable.make(M.getEntries())) { if (entry instanceof DexModuleEntry) { result.add(entry); } } return result; } @SuppressWarnings("unused") private void loadAllDexClasses(Collection<ModuleEntry> moduleEntries) { for (ModuleEntry entry : moduleEntries) { // Dalvik class if (entry instanceof DexModuleEntry) { DexModuleEntry dexEntry = ((DexModuleEntry) entry); String className = dexEntry.getClassName(); TypeName tName = TypeName.string2TypeName(className); // if (DEBUG_LEVEL > 0) { // System.err.println("Consider dex class: " + tName); // } // System.out.println("Typename: " + tName.toString()); // System.out.println(tName.getClassName()); if (loadedClasses.get(tName) != null) { Warnings.add(MultipleDexImplementationsWarning.create(className)); } else if (lParent != null && lParent.lookupClass(tName) != null) { Warnings.add(MultipleDexImplementationsWarning.create(className)); } // if the class is empty, ie an interface // else if (dexEntry.getClassDefItem().getClassData() == null) { // System.out.println("Jumping over (classdata null): // "+dexEntry.getClassName()); // Warnings.add(MultipleDexImplementationsWarning // .create(dexEntry.getClassName())); // } else { IClass iClass = new DexIClass(this, cha, dexEntry); if (iClass.getReference().getName().equals(tName)) { // className is a descriptor, so strip the 'L' if (exclusions != null && exclusions.contains(className.substring(1))) { if (DEBUG_LEVEL > 0) { System.err.println("Excluding " + className); } continue; } loadedClasses.put(tName, iClass); } else { Warnings.add(InvalidDexFile.create(className)); } } } } } /** @return the IClassHierarchy of this classLoader. */ public IClassHierarchy getClassHierarcy() { return cha; } /** A warning when we find more than one implementation of a given class name */ private static class MultipleDexImplementationsWarning extends Warning { final String className; MultipleDexImplementationsWarning(String className) { super(Warning.SEVERE); this.className = className; } @Override public String getMsg() { return getClass().toString() + " : " + className; } public static MultipleDexImplementationsWarning create(String className) { return new MultipleDexImplementationsWarning(className); } } /** A warning when we encounter InvalidClassFileException */ private static class InvalidDexFile extends Warning { final String className; InvalidDexFile(String className) { super(Warning.SEVERE); this.className = className; } @Override public String getMsg() { return getClass().toString() + " : " + className; } public static InvalidDexFile create(String className) { return new InvalidDexFile(className); } } }
7,806
34.008969
89
java
WALA
WALA-master/dalvik/src/main/java/com/ibm/wala/dalvik/dex/instructions/ArrayFill.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> * Steve Suh <suhsteve@gmail.com> * * 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.dex.instructions; import com.ibm.wala.dalvik.classLoader.DexIMethod; import com.ibm.wala.types.TypeReference; import org.jf.dexlib2.Opcode; import org.jf.dexlib2.iface.instruction.formats.ArrayPayload; public class ArrayFill extends Instruction { public final int array; public final int tableAddressOffset; public int registerIndex; private ArrayPayload table; public final TypeReference type; public ArrayFill( int pc, int array, int offset, TypeReference type, Opcode op, DexIMethod method) { super(pc, op, method); this.array = array; this.tableAddressOffset = offset; this.type = type; } /* (non-Javadoc) * @see wala.dex.instructions.Instruction#visit(wala.dex.instructions.Instruction.Visitor) */ @Override public void visit(Visitor visitor) { visitor.visitArrayFill(this); } public void setArrayDataTable(ArrayPayload inst) { this.table = inst; } public ArrayPayload getTable() { return table; } public int getElementCount() { return table.getArrayElements().size(); } public TypeReference getType() { return type; } }
3,130
31.614583
92
java
WALA
WALA-master/dalvik/src/main/java/com/ibm/wala/dalvik/dex/instructions/ArrayGet.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> * Steve Suh <suhsteve@gmail.com> * * 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.dex.instructions; import com.ibm.wala.dalvik.classLoader.DexIMethod; import com.ibm.wala.types.TypeReference; import org.jf.dexlib2.Opcode; public class ArrayGet extends Instruction { public enum Type { t_int, t_wide, t_boolean, t_byte, t_char, t_object, t_short } public final int destination; public final int array; public final int offset; public final Type type; public ArrayGet( int pc, int destination, int array, int offset, Type type, Opcode op, DexIMethod method) { super(pc, op, method); this.destination = destination; this.array = array; this.offset = offset; this.type = type; } @Override public void visit(Visitor visitor) { visitor.visitArrayGet(this); } public TypeReference getType() { return getType(type); } public static TypeReference getType(Type type) { switch (type) { case t_int: return TypeReference.Int; case t_wide: return TypeReference.Long; case t_boolean: return TypeReference.Boolean; case t_byte: return TypeReference.Byte; case t_char: return TypeReference.Char; case t_object: return TypeReference.JavaLangObject; case t_short: return TypeReference.Short; default: return null; } } }
3,348
29.171171
96
java
WALA
WALA-master/dalvik/src/main/java/com/ibm/wala/dalvik/dex/instructions/ArrayLength.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> * Steve Suh <suhsteve@gmail.com> * * 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.dex.instructions; import com.ibm.wala.dalvik.classLoader.DexIMethod; import org.jf.dexlib2.Opcode; public class ArrayLength extends Instruction { public final int destination; public final int source; public ArrayLength(int instLoc, int destination, int source, Opcode op, DexIMethod method) { super(instLoc, op, method); this.destination = destination; this.source = source; } @Override public void visit(Visitor visitor) { visitor.visitArrayLength(this); } }
2,504
35.304348
94
java
WALA
WALA-master/dalvik/src/main/java/com/ibm/wala/dalvik/dex/instructions/ArrayPut.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> * Steve Suh <suhsteve@gmail.com> * * 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.dex.instructions; import com.ibm.wala.dalvik.classLoader.DexIMethod; import com.ibm.wala.dalvik.dex.instructions.ArrayGet.Type; import com.ibm.wala.types.TypeReference; import org.jf.dexlib2.Opcode; public class ArrayPut extends Instruction { public final int array; public final int source; public final int offset; public final Type type; public ArrayPut( int pc, int source, int array, int offset, Type type, Opcode op, DexIMethod method) { super(pc, op, method); this.source = source; this.array = array; this.offset = offset; this.type = type; } @Override public void visit(Visitor visitor) { visitor.visitArrayPut(this); } public TypeReference getType() { return ArrayGet.getType(type); } }
2,768
33.185185
91
java
WALA
WALA-master/dalvik/src/main/java/com/ibm/wala/dalvik/dex/instructions/BinaryLiteralOperation.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> * Steve Suh <suhsteve@gmail.com> * * 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.dex.instructions; import com.ibm.wala.dalvik.classLoader.DexIMethod; import com.ibm.wala.dalvik.classLoader.Literal; import com.ibm.wala.dalvik.dex.instructions.BinaryOperation.DalvikBinaryOp; import com.ibm.wala.shrike.shrikeBT.IBinaryOpInstruction; import com.ibm.wala.shrike.shrikeBT.IShiftInstruction; import org.jf.dexlib2.Opcode; public class BinaryLiteralOperation extends Instruction { public enum OpID { CMPL_FLOAT, CMPG_FLOAT, CMPL_DOUBLE, CMPG_DOUBLE, CMPL_LONG, CMPG_LONG, CMPL_INT, CMPG_INT, ADD_INT, RSUB_INT, MUL_INT, DIV_INT, REM_INT, AND_INT, OR_INT, XOR_INT, SHL_INT, SHR_INT, USHR_INT, ADD_LONG, RSUB_LONG, MUL_LONG, DIV_LONG, REM_LONG, AND_LONG, OR_LONG, XOR_LONG, SHL_LONG, SHR_LONG, USHR_LONG, ADD_FLOAT, RSUB_FLOAT, MUL_FLOAT, DIV_FLOAT, REM_FLOAT, ADD_DOUBLE, RSUB_DOUBLE, MUL_DOUBLE, DIV_DOUBLE, REM_DOUBLE } public final OpID op; public final int oper1; public final Literal oper2; public final int destination; public BinaryLiteralOperation( int pc, OpID op, int destination, int oper1, Literal oper2, Opcode opcode, DexIMethod method) { super(pc, opcode, method); this.op = op; this.destination = destination; this.oper1 = oper1; this.oper2 = oper2; } @Override public void visit(Visitor visitor) { visitor.visitBinaryLiteral(this); } public IBinaryOpInstruction.IOperator getOperator() { switch (op) { case CMPL_FLOAT: case CMPL_DOUBLE: case CMPL_LONG: case CMPL_INT: return DalvikBinaryOp.LT; case CMPG_FLOAT: case CMPG_DOUBLE: case CMPG_LONG: case CMPG_INT: return DalvikBinaryOp.GT; case ADD_INT: case ADD_LONG: case ADD_DOUBLE: case ADD_FLOAT: return IBinaryOpInstruction.Operator.ADD; case RSUB_INT: case RSUB_LONG: case RSUB_DOUBLE: case RSUB_FLOAT: return IBinaryOpInstruction.Operator.SUB; case MUL_INT: case MUL_LONG: case MUL_DOUBLE: case MUL_FLOAT: return IBinaryOpInstruction.Operator.MUL; case DIV_INT: case DIV_LONG: case DIV_DOUBLE: case DIV_FLOAT: return IBinaryOpInstruction.Operator.DIV; case REM_INT: case REM_LONG: case REM_DOUBLE: case REM_FLOAT: return IBinaryOpInstruction.Operator.REM; case AND_INT: case AND_LONG: return IBinaryOpInstruction.Operator.AND; case OR_INT: case OR_LONG: return IBinaryOpInstruction.Operator.OR; case XOR_INT: case XOR_LONG: return IBinaryOpInstruction.Operator.XOR; case SHL_INT: case SHL_LONG: return IShiftInstruction.Operator.SHL; case SHR_INT: case SHR_LONG: return IShiftInstruction.Operator.SHR; case USHR_INT: case USHR_LONG: return IShiftInstruction.Operator.USHR; default: return null; } } public boolean isFloat() { switch (op) { case CMPL_FLOAT: case CMPG_FLOAT: case CMPL_DOUBLE: case CMPG_DOUBLE: case ADD_FLOAT: case RSUB_FLOAT: case MUL_FLOAT: case DIV_FLOAT: case REM_FLOAT: case ADD_DOUBLE: case RSUB_DOUBLE: case MUL_DOUBLE: case DIV_DOUBLE: case REM_DOUBLE: return true; default: return false; } } public boolean isUnsigned() { switch (op) { case AND_INT: case OR_INT: case XOR_INT: case SHL_INT: case USHR_INT: case AND_LONG: case OR_LONG: case XOR_LONG: case SHL_LONG: case USHR_LONG: return true; default: return false; } } public boolean isSub() { switch (op) { case RSUB_DOUBLE: case RSUB_FLOAT: case RSUB_INT: case RSUB_LONG: return true; default: return false; } } @Override public String toString() { return String.format( "%04dpc: v%d = v%d %s v%d", this.pc, this.destination, this.oper1, this.op.toString(), this.oper2.value); } }
6,277
24.417004
85
java
WALA
WALA-master/dalvik/src/main/java/com/ibm/wala/dalvik/dex/instructions/BinaryOperation.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> * Steve Suh <suhsteve@gmail.com> * * 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.dex.instructions; import com.ibm.wala.dalvik.classLoader.DexIMethod; import com.ibm.wala.shrike.shrikeBT.IBinaryOpInstruction; import com.ibm.wala.shrike.shrikeBT.IShiftInstruction; import org.jf.dexlib2.Opcode; public class BinaryOperation extends Instruction { public enum OpID { CMPL_FLOAT, CMPG_FLOAT, CMPL_DOUBLE, CMPG_DOUBLE, CMPL_LONG, CMPG_LONG, CMPL_INT, CMPG_INT, ADD_INT, SUB_INT, MUL_INT, DIV_INT, REM_INT, AND_INT, OR_INT, XOR_INT, SHL_INT, SHR_INT, USHR_INT, ADD_LONG, SUB_LONG, MUL_LONG, DIV_LONG, REM_LONG, AND_LONG, OR_LONG, XOR_LONG, SHL_LONG, SHR_LONG, USHR_LONG, ADD_FLOAT, SUB_FLOAT, MUL_FLOAT, DIV_FLOAT, REM_FLOAT, ADD_DOUBLE, SUB_DOUBLE, MUL_DOUBLE, DIV_DOUBLE, REM_DOUBLE } /** for binary ops not defined in JVML */ public enum DalvikBinaryOp implements IBinaryOpInstruction.IOperator { LT, GT; @Override public String toString() { return super.toString().toLowerCase(); } } public final OpID op; public final int oper1; public final int oper2; public final int destination; public BinaryOperation( int pc, OpID op, int destination, int oper1, int oper2, Opcode opcode, DexIMethod method) { super(pc, opcode, method); this.op = op; this.destination = destination; this.oper1 = oper1; this.oper2 = oper2; } @Override public void visit(Visitor visitor) { visitor.visitBinaryOperation(this); } public IBinaryOpInstruction.IOperator getOperator() { switch (op) { case CMPL_FLOAT: case CMPL_INT: case CMPL_LONG: case CMPL_DOUBLE: return DalvikBinaryOp.LT; case CMPG_FLOAT: case CMPG_INT: case CMPG_LONG: case CMPG_DOUBLE: return DalvikBinaryOp.GT; case ADD_INT: case ADD_DOUBLE: case ADD_FLOAT: case ADD_LONG: return IBinaryOpInstruction.Operator.ADD; case SUB_INT: case SUB_DOUBLE: case SUB_FLOAT: case SUB_LONG: return IBinaryOpInstruction.Operator.SUB; case MUL_INT: case MUL_DOUBLE: case MUL_FLOAT: case MUL_LONG: return IBinaryOpInstruction.Operator.MUL; case DIV_INT: case DIV_DOUBLE: case DIV_FLOAT: case DIV_LONG: return IBinaryOpInstruction.Operator.DIV; case REM_INT: case REM_DOUBLE: case REM_FLOAT: case REM_LONG: return IBinaryOpInstruction.Operator.REM; case AND_INT: case AND_LONG: return IBinaryOpInstruction.Operator.AND; case OR_INT: case OR_LONG: return IBinaryOpInstruction.Operator.OR; case XOR_INT: case XOR_LONG: return IBinaryOpInstruction.Operator.XOR; case SHL_INT: case SHL_LONG: return IShiftInstruction.Operator.SHL; case SHR_INT: case SHR_LONG: return IShiftInstruction.Operator.SHR; case USHR_INT: case USHR_LONG: return IShiftInstruction.Operator.USHR; default: return null; } } public boolean isFloat() { switch (op) { case CMPL_FLOAT: case CMPG_FLOAT: case CMPL_DOUBLE: case CMPG_DOUBLE: case ADD_FLOAT: case SUB_FLOAT: case MUL_FLOAT: case DIV_FLOAT: case REM_FLOAT: case ADD_DOUBLE: case SUB_DOUBLE: case MUL_DOUBLE: case DIV_DOUBLE: case REM_DOUBLE: return true; default: return false; } } public boolean isUnsigned() { switch (op) { case AND_INT: case OR_INT: case XOR_INT: case SHL_INT: case USHR_INT: case AND_LONG: case OR_LONG: case XOR_LONG: case SHL_LONG: case USHR_LONG: return true; default: return false; } } }
5,924
24.649351
97
java
WALA
WALA-master/dalvik/src/main/java/com/ibm/wala/dalvik/dex/instructions/Branch.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> * Steve Suh <suhsteve@gmail.com> * * 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.dex.instructions; import com.ibm.wala.dalvik.classLoader.DexIMethod; import com.ibm.wala.shrike.shrikeBT.IConditionalBranchInstruction; import com.ibm.wala.shrike.shrikeBT.IConditionalBranchInstruction.IOperator; import org.jf.dexlib2.Opcode; public abstract class Branch extends Instruction { public final int offset; private int label; protected Branch(int instLoc, int offset, Opcode opcode, DexIMethod method) { super(instLoc, opcode, method); this.offset = offset; } public static class UnaryBranch extends Branch { public enum CompareOp { EQZ, NEZ, LTZ, LEZ, GTZ, GEZ } public final int oper1; public final CompareOp op; public UnaryBranch( int instLoc, int offset, CompareOp op, int oper1, Opcode opcode, DexIMethod method) { super(instLoc, offset, opcode, method); this.op = op; this.oper1 = oper1; } @Override public IOperator getOperator() { switch (op) { case EQZ: return IConditionalBranchInstruction.Operator.EQ; case NEZ: return IConditionalBranchInstruction.Operator.NE; case LTZ: return IConditionalBranchInstruction.Operator.LT; case LEZ: return IConditionalBranchInstruction.Operator.LE; case GTZ: return IConditionalBranchInstruction.Operator.GT; case GEZ: return IConditionalBranchInstruction.Operator.GE; default: return null; } } } public static class BinaryBranch extends Branch { public enum CompareOp { EQ, NE, LT, LE, GT, GE } public final int oper1; public final int oper2; public final CompareOp op; public BinaryBranch( int instLoc, int offset, CompareOp op, int oper1, int oper2, Opcode opcode, DexIMethod method) { super(instLoc, offset, opcode, method); this.op = op; this.oper1 = oper1; this.oper2 = oper2; } @Override public IOperator getOperator() { switch (op) { case EQ: return IConditionalBranchInstruction.Operator.EQ; case NE: return IConditionalBranchInstruction.Operator.NE; case LT: return IConditionalBranchInstruction.Operator.LT; case LE: return IConditionalBranchInstruction.Operator.LE; case GT: return IConditionalBranchInstruction.Operator.GT; case GE: return IConditionalBranchInstruction.Operator.GE; default: return null; } } } @Override public void visit(Visitor visitor) { visitor.visitBranch(this); } public abstract IOperator getOperator(); @Override public int[] getBranchTargets() { this.label = method.getInstructionIndex(pc + offset); int[] r = {label}; return r; } }
4,937
28.047059
93
java
WALA
WALA-master/dalvik/src/main/java/com/ibm/wala/dalvik/dex/instructions/CheckCast.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> * Steve Suh <suhsteve@gmail.com> * * 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.dex.instructions; import com.ibm.wala.dalvik.classLoader.DexIMethod; import com.ibm.wala.types.TypeReference; import org.jf.dexlib2.Opcode; public class CheckCast extends Instruction { public final TypeReference type; public final int object; public CheckCast(int pc, TypeReference type, int object, Opcode opcode, DexIMethod method) { super(pc, opcode, method); this.type = type; this.object = object; } @Override public void visit(Visitor visitor) { visitor.visitCheckCast(this); } }
2,530
34.647887
94
java
WALA
WALA-master/dalvik/src/main/java/com/ibm/wala/dalvik/dex/instructions/Constant.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> * Steve Suh <suhsteve@gmail.com> * * 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.dex.instructions; import com.ibm.wala.dalvik.classLoader.DexIMethod; import com.ibm.wala.types.TypeReference; import org.jf.dexlib2.Opcode; public abstract class Constant extends Instruction { public final int destination; public static class LongConstant extends Constant { public final long value; public LongConstant(int pc, long value, int destination, Opcode opcode, DexIMethod method) { super(pc, destination, opcode, method); this.value = value; } } protected Constant(int pc, int destination, Opcode opcode, DexIMethod method) { super(pc, opcode, method); this.destination = destination; } public static class IntConstant extends Constant { public final int value; public IntConstant(int pc, int value, int destination, Opcode opcode, DexIMethod method) { super(pc, destination, opcode, method); this.value = value; } } public static class StringConstant extends Constant { public final String value; public StringConstant(int pc, String value, int destination, Opcode opcode, DexIMethod method) { super(pc, destination, opcode, method); this.value = value; } } public static class ClassConstant extends Constant { public final TypeReference value; public ClassConstant( int pc, TypeReference value, int destination, Opcode opcode, DexIMethod method) { super(pc, destination, opcode, method); this.value = value; } } @Override public void visit(Visitor visitor) { visitor.visitConstant(this); } }
3,571
32.698113
100
java
WALA
WALA-master/dalvik/src/main/java/com/ibm/wala/dalvik/dex/instructions/GetField.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> * Steve Suh <suhsteve@gmail.com> * * 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.dex.instructions; import com.ibm.wala.dalvik.classLoader.DexIMethod; import org.jf.dexlib2.Opcode; public abstract class GetField extends Instruction { public final int destination; public final String clazzName; public final String fieldName; public final String fieldType; protected GetField( int pc, int destination, String clazzName, String fieldName, String fieldType, Opcode opcode, DexIMethod method) { super(pc, opcode, method); this.destination = destination; this.clazzName = clazzName; this.fieldName = fieldName; this.fieldType = fieldType; } public static class GetInstanceField extends GetField { public final int instance; public GetInstanceField( int pc, int destination, int instance, String clazzName, String fieldName, String fieldType, Opcode opcode, DexIMethod method) { super(pc, destination, clazzName, fieldName, fieldType, opcode, method); this.instance = instance; } } public static class GetStaticField extends GetField { public GetStaticField( int pc, int destination, String clazzName, String fieldName, String fieldType, Opcode opcode, DexIMethod method) { super(pc, destination, clazzName, fieldName, fieldType, opcode, method); } } @Override public void visit(Visitor visitor) { visitor.visitGetField(this); } }
3,511
30.63964
79
java
WALA
WALA-master/dalvik/src/main/java/com/ibm/wala/dalvik/dex/instructions/Goto.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> * Steve Suh <suhsteve@gmail.com> * * 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.dex.instructions; import com.ibm.wala.dalvik.classLoader.DexIMethod; import org.jf.dexlib2.Opcode; public class Goto extends Instruction { public final int destination; private int[] label; public Goto(int pc, int destination, Opcode opcode, DexIMethod method) { super(pc, opcode, method); this.destination = destination; } @Override public void visit(Visitor visitor) { visitor.visitGoto(this); } @Override public int[] getBranchTargets() { if (label == null) { int[] l = {method.getInstructionIndex(pc + destination)}; this.label = l; } return label; } }
2,628
32.705128
79
java
WALA
WALA-master/dalvik/src/main/java/com/ibm/wala/dalvik/dex/instructions/InstanceOf.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> * Steve Suh <suhsteve@gmail.com> * * 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.dex.instructions; import com.ibm.wala.dalvik.classLoader.DexIMethod; import com.ibm.wala.types.TypeReference; import org.jf.dexlib2.Opcode; public class InstanceOf extends Instruction { public final int destination; public final int source; public final TypeReference type; public InstanceOf( int pc, int destination, TypeReference type, int source, Opcode opcode, DexIMethod method) { super(pc, opcode, method); this.destination = destination; this.type = type; this.source = source; } @Override public void visit(Visitor visitor) { visitor.visitInstanceof(this); } }
2,624
34.958904
98
java
WALA
WALA-master/dalvik/src/main/java/com/ibm/wala/dalvik/dex/instructions/Instruction.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> * Steve Suh <suhsteve@gmail.com> * * 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.dex.instructions; import com.ibm.wala.dalvik.classLoader.DexIMethod; import org.jf.dexlib2.Opcode; public abstract class Instruction { @SuppressWarnings("unused") public static class Visitor { public void visitArrayLength(ArrayLength instruction) {} public void visitArrayGet(ArrayGet instruction) {} public void visitArrayPut(ArrayPut instruction) {} public void visitArrayFill(ArrayFill instruction) {} public void visitBinaryOperation(BinaryOperation instruction) {} public void visitBinaryLiteral(BinaryLiteralOperation binaryLiteralOperation) {} public void visitBranch(Branch instruction) {} public void visitCheckCast(CheckCast checkCast) {} public void visitConstant(Constant instruction) {} public void visitGetField(GetField instruction) {} public void visitGoto(Goto inst) {} public void visitInstanceof(InstanceOf instruction) {} public void visitInvoke(Invoke instruction) {} public void visitMonitor(Monitor instruction) {} public void visitNew(New instruction) {} public void visitNewArray(NewArray newArray) {} public void visitNewArrayFilled(NewArrayFilled newArrayFilled) {} public void visitPutField(PutField instruction) {} public void visitReturn(Return return1) {} public void visitSwitch(Switch instruction) {} public void visitThrow(Throw instruction) {} public void visitUnaryOperation(UnaryOperation instruction) {} } public final int pc; protected final Opcode opcode; protected final DexIMethod method; public static final int[] noInstructions = new int[0]; protected Instruction(int pc, Opcode op, DexIMethod method) { this.pc = pc; this.opcode = op; this.method = method; } /** * True if the instruction can continue. * * @see com.ibm.wala.shrike.shrikeBT.IInstruction#isFallThrough() */ public boolean isFallThrough() { return opcode.canContinue(); } /** * True if the instruction can throw an exception * * @see com.ibm.wala.shrike.shrikeBT.IInstruction#isPEI() */ public boolean isPEI() { return opcode.canThrow(); } /** @return The DexIMethod which contains this instruction. */ public DexIMethod getParentMethod() { return method; } /** @return The opcode associated with this instruction. */ public Opcode getOpcode() { return opcode; } public int[] getBranchTargets() { return noInstructions; } public abstract void visit(Visitor visitor); }
4,514
29.1
84
java
WALA
WALA-master/dalvik/src/main/java/com/ibm/wala/dalvik/dex/instructions/Invoke.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> * Steve Suh <suhsteve@gmail.com> * * 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.dex.instructions; import com.ibm.wala.dalvik.classLoader.DexIMethod; import com.ibm.wala.shrike.shrikeBT.IInvokeInstruction; import com.ibm.wala.shrike.shrikeBT.IInvokeInstruction.IDispatch; import com.ibm.wala.types.Descriptor; import org.jf.dexlib2.Opcode; public abstract class Invoke extends Instruction { public final int[] args; public final String clazzName; public final String methodName; public final String descriptor; protected Invoke( int instLoc, String clazzName, String methodName, String descriptor, int[] args, Opcode opcode, DexIMethod method) { super(instLoc, opcode, method); this.clazzName = clazzName; this.methodName = methodName; this.descriptor = descriptor; this.args = args; assert Descriptor.findOrCreateUTF8(descriptor) != null; } public static class InvokeVirtual extends Invoke { public InvokeVirtual( int instLoc, String clazzName, String methodName, String descriptor, int[] args, Opcode opcode, DexIMethod method) { super(instLoc, clazzName, methodName, descriptor, args, opcode, method); } @Override public IDispatch getInvocationCode() { return IInvokeInstruction.Dispatch.VIRTUAL; } @Override public String toString() { StringBuilder argString = new StringBuilder(); argString.append('('); String sep = ""; for (int r : args) { argString.append(sep).append(r); sep = ","; } argString.append(')'); return "InvokeVirtual " + clazzName + ' ' + methodName + ' ' + descriptor + ' ' + argString + ' ' + pc; } } public static class InvokeSuper extends Invoke { public InvokeSuper( int instLoc, String clazzName, String methodName, String descriptor, int[] args, Opcode opcode, DexIMethod method) { super(instLoc, clazzName, methodName, descriptor, args, opcode, method); assert descriptor.contains("("); } @Override public IDispatch getInvocationCode() { // TODO: check that this is correct -- I suspect the invoke super in dex is for method // protection rather than dispatching return IInvokeInstruction.Dispatch.SPECIAL; } @Override public String toString() { StringBuilder argString = new StringBuilder(); argString.append('('); String sep = ""; for (int r : args) { argString.append(sep).append(r); sep = ","; } argString.append(')'); return "InvokeSuper " + clazzName + ' ' + methodName + ' ' + descriptor + ' ' + argString + ' ' + pc; } } public static class InvokeDirect extends Invoke { public InvokeDirect( int instLoc, String clazzName, String methodName, String descriptor, int[] args, Opcode opcode, DexIMethod method) { super(instLoc, clazzName, methodName, descriptor, args, opcode, method); } @Override public IDispatch getInvocationCode() { return IInvokeInstruction.Dispatch.SPECIAL; } @Override public String toString() { StringBuilder argString = new StringBuilder(); argString.append('('); String sep = ""; for (int r : args) { argString.append(sep).append(r); sep = ","; } argString.append(')'); return "InvokeDirect " + clazzName + ' ' + methodName + ' ' + descriptor + ' ' + argString + ' ' + pc; } } public static class InvokeStatic extends Invoke { public InvokeStatic( int instLoc, String clazzName, String methodName, String descriptor, int[] args, Opcode opcode, DexIMethod method) { super(instLoc, clazzName, methodName, descriptor, args, opcode, method); } @Override public IDispatch getInvocationCode() { return IInvokeInstruction.Dispatch.STATIC; } @Override public String toString() { StringBuilder argString = new StringBuilder(); argString.append('('); String sep = ""; for (int r : args) { argString.append(sep).append(r); sep = ","; } argString.append(')'); return "InvokeStatic " + clazzName + ' ' + methodName + ' ' + descriptor + ' ' + argString + ' ' + pc; } } public static class InvokeInterface extends Invoke { public InvokeInterface( int instLoc, String clazzName, String methodName, String descriptor, int[] args, Opcode opcode, DexIMethod method) { super(instLoc, clazzName, methodName, descriptor, args, opcode, method); } @Override public IDispatch getInvocationCode() { return IInvokeInstruction.Dispatch.INTERFACE; } @Override public String toString() { StringBuilder argString = new StringBuilder(); argString.append('('); String sep = ""; for (int r : args) { argString.append(sep).append(r); sep = ","; } argString.append(')'); return "InvokeInterface " + clazzName + ' ' + methodName + ' ' + descriptor + ' ' + argString + ' ' + pc; } } @Override public void visit(Visitor visitor) { visitor.visitInvoke(this); } public abstract IDispatch getInvocationCode(); }
7,852
25.620339
92
java
WALA
WALA-master/dalvik/src/main/java/com/ibm/wala/dalvik/dex/instructions/Monitor.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> * Steve Suh <suhsteve@gmail.com> * * 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.dex.instructions; import com.ibm.wala.dalvik.classLoader.DexIMethod; import org.jf.dexlib2.Opcode; public class Monitor extends Instruction { public Monitor(int pc, boolean enter, int object, Opcode opcode, DexIMethod method) { super(pc, opcode, method); this.enter = enter; this.object = object; } public final boolean enter; public final int object; @Override public void visit(Visitor visitor) { visitor.visitMonitor(this); } }
2,475
34.371429
87
java
WALA
WALA-master/dalvik/src/main/java/com/ibm/wala/dalvik/dex/instructions/New.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> * Steve Suh <suhsteve@gmail.com> * * 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.dex.instructions; import com.ibm.wala.classLoader.NewSiteReference; import com.ibm.wala.dalvik.classLoader.DexIMethod; import org.jf.dexlib2.Opcode; public class New extends Instruction { public final int destination; public final NewSiteReference newSiteRef; public New( int pc, int destination, NewSiteReference newSiteRef, Opcode opcode, DexIMethod method) { super(pc, opcode, method); this.destination = destination; this.newSiteRef = newSiteRef; } @Override public void visit(Visitor visitor) { visitor.visitNew(this); } }
2,578
34.819444
95
java
WALA
WALA-master/dalvik/src/main/java/com/ibm/wala/dalvik/dex/instructions/NewArray.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> * Steve Suh <suhsteve@gmail.com> * * 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.dex.instructions; import com.ibm.wala.classLoader.NewSiteReference; import com.ibm.wala.dalvik.classLoader.DexIMethod; import org.jf.dexlib2.Opcode; public class NewArray extends Instruction { public final int destination; public final NewSiteReference newSiteRef; public final int[] sizes; public NewArray( int pc, int destination, NewSiteReference newSiteRef, int[] sizes, Opcode opcode, DexIMethod method) { super(pc, opcode, method); this.destination = destination; this.newSiteRef = newSiteRef; this.sizes = sizes.clone(); } @Override public void visit(Visitor visitor) { visitor.visitNewArray(this); } }
2,696
33.139241
79
java
WALA
WALA-master/dalvik/src/main/java/com/ibm/wala/dalvik/dex/instructions/NewArrayFilled.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> * Steve Suh <suhsteve@gmail.com> * * 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.dex.instructions; import com.ibm.wala.classLoader.NewSiteReference; import com.ibm.wala.dalvik.classLoader.DexIMethod; import com.ibm.wala.types.TypeReference; import org.jf.dexlib2.Opcode; public class NewArrayFilled extends Instruction { public final int destination; public final NewSiteReference newSiteRef; public final int[] sizes; public final int[] args; public final TypeReference myType; public NewArrayFilled( int pc, int destination, NewSiteReference newSiteRef, TypeReference myType, int[] sizes, int[] args, Opcode opcode, DexIMethod method) { super(pc, opcode, method); this.destination = destination; this.newSiteRef = newSiteRef; this.sizes = sizes.clone(); this.myType = myType; this.args = args.clone(); } @Override public void visit(Visitor visitor) { visitor.visitNewArrayFilled(this); } }
2,921
32.976744
79
java
WALA
WALA-master/dalvik/src/main/java/com/ibm/wala/dalvik/dex/instructions/PackedSwitchPad.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> * Steve Suh <suhsteve@gmail.com> * * 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.dex.instructions; import org.jf.dexlib2.iface.instruction.SwitchElement; import org.jf.dexlib2.iface.instruction.SwitchPayload; public class PackedSwitchPad implements SwitchPad { public int firstValue; public final int[] offsets; public final int defaultOffset; private int[] labelsAndOffsets; private int[] values; public PackedSwitchPad(SwitchPayload inst, int defaultOffset) { int i = 0; this.offsets = new int[inst.getSwitchElements().size()]; for (SwitchElement elt : inst.getSwitchElements()) { if (i == 0) { firstValue = elt.getKey(); } offsets[i++] = elt.getOffset(); } this.defaultOffset = defaultOffset; } @Override public int[] getOffsets() { return offsets; } @Override public int[] getValues() { if (values != null) return values; values = new int[offsets.length]; for (int i = 0; i < offsets.length; i++) { values[i] = firstValue + i; } return values; } @Override public int getDefaultOffset() { // return Integer.MIN_VALUE; return defaultOffset; } @Override public int[] getLabelsAndOffsets() { if (labelsAndOffsets != null) return labelsAndOffsets; // labelsAndOffsets = new int[offsets.length * 2 + 2]; labelsAndOffsets = new int[offsets.length * 2]; for (int i = 0; i < offsets.length; i++) { labelsAndOffsets[i * 2] = firstValue + i; labelsAndOffsets[i * 2 + 1] = offsets[i]; } // labelsAndOffsets[offsets.length*2] = getDefaultLabel(); // labelsAndOffsets[offsets.length*2+1] = defaultOffset; return labelsAndOffsets; } }
3,641
32.412844
79
java
WALA
WALA-master/dalvik/src/main/java/com/ibm/wala/dalvik/dex/instructions/PutField.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> * Steve Suh <suhsteve@gmail.com> * * 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.dex.instructions; import com.ibm.wala.dalvik.classLoader.DexIMethod; import org.jf.dexlib2.Opcode; public abstract class PutField extends Instruction { public final int source; public final String clazzName; public final String fieldName; public final String fieldType; protected PutField( int pc, int source, String clazzName, String fieldName, String fieldType, Opcode opcode, DexIMethod method) { super(pc, opcode, method); this.source = source; this.clazzName = clazzName; this.fieldName = fieldName; this.fieldType = fieldType; } public static class PutInstanceField extends PutField { public final int instance; public PutInstanceField( int pc, int source, int instance, String clazzName, String fieldName, String fieldType, Opcode opcode, DexIMethod method) { super(pc, source, clazzName, fieldName, fieldType, opcode, method); this.instance = instance; } } public static class PutStaticField extends PutField { public PutStaticField( int pc, int source, String clazzName, String fieldName, String fieldType, Opcode opcode, DexIMethod method) { super(pc, source, clazzName, fieldName, fieldType, opcode, method); } } @Override public void visit(Visitor visitor) { visitor.visitPutField(this); } }
3,471
30.279279
79
java
WALA
WALA-master/dalvik/src/main/java/com/ibm/wala/dalvik/dex/instructions/Return.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> * Steve Suh <suhsteve@gmail.com> * * 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.dex.instructions; import com.ibm.wala.dalvik.classLoader.DexIMethod; import org.jf.dexlib2.Opcode; public abstract class Return extends Instruction { protected Return(int pc, Opcode opcode, DexIMethod method) { super(pc, opcode, method); } public static class ReturnVoid extends Return { public ReturnVoid(int pc, Opcode opcode, DexIMethod method) { super(pc, opcode, method); } } public static class ReturnSingle extends Return { public ReturnSingle(int pc, int source, boolean primitive, Opcode opcode, DexIMethod method) { super(pc, opcode, method); this.source = source; this.primitive = primitive; } public boolean isPrimitive() { return primitive; } public final int source; public boolean primitive; } public static class ReturnDouble extends Return { public ReturnDouble(int pc, int source1, int source2, Opcode opcode, DexIMethod method) { super(pc, opcode, method); this.source1 = source1; this.source2 = source2; } public final int source1; public final int source2; } @Override public void visit(Visitor visitor) { visitor.visitReturn(this); } }
3,203
32.030928
98
java
WALA
WALA-master/dalvik/src/main/java/com/ibm/wala/dalvik/dex/instructions/SparseSwitchPad.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> * Steve Suh <suhsteve@gmail.com> * * 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.dex.instructions; import org.jf.dexlib2.iface.instruction.SwitchElement; import org.jf.dexlib2.iface.instruction.SwitchPayload; public class SparseSwitchPad implements SwitchPad { public final int[] values; public final int[] offsets; public final int defaultOffset; private int[] labelsAndOffsets; public SparseSwitchPad(SwitchPayload inst, int defaultOffset) { int i = 0; this.values = new int[inst.getSwitchElements().size()]; this.offsets = new int[inst.getSwitchElements().size()]; for (SwitchElement elt : inst.getSwitchElements()) { values[i] = elt.getKey(); offsets[i++] = elt.getOffset(); } this.defaultOffset = defaultOffset; } @Override public int[] getOffsets() { return offsets; } @Override public int[] getValues() { return values; } @Override public int getDefaultOffset() { // return Integer.MIN_VALUE; return defaultOffset; } @Override public int[] getLabelsAndOffsets() { // return values; if (labelsAndOffsets != null) return labelsAndOffsets; // labelsAndOffsets = new int[offsets.length * 2 + 2]; labelsAndOffsets = new int[offsets.length * 2]; for (int i = 0; i < offsets.length; i++) { labelsAndOffsets[i * 2] = values[i]; labelsAndOffsets[i * 2 + 1] = offsets[i]; } // labelsAndOffsets[offsets.length*2] = getDefaultLabel(); // labelsAndOffsets[offsets.length*2+1] = defaultOffset; return labelsAndOffsets; } }
3,509
32.75
79
java
WALA
WALA-master/dalvik/src/main/java/com/ibm/wala/dalvik/dex/instructions/Switch.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> * Steve Suh <suhsteve@gmail.com> * * 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.dex.instructions; import com.ibm.wala.dalvik.classLoader.DexIMethod; import org.jf.dexlib2.Opcode; public class Switch extends Instruction { public final int regA; public final int tableAddressOffset; public SwitchPad pad; private int[] casesAndLabels; private int defaultLabel; public Switch(int instLoc, int regA, int tableAddressOffset, Opcode opcode, DexIMethod method) { super(instLoc, opcode, method); this.regA = regA; this.tableAddressOffset = tableAddressOffset; } public void setSwitchPad(SwitchPad pad) { this.pad = pad; computeCasesAndLabels(); } private void computeCasesAndLabels() { casesAndLabels = pad.getLabelsAndOffsets(); for (int i = 1; i < casesAndLabels.length; i += 2) // casesAndLabels[i] = method.getInstructionIndex(pc+casesAndLabels[i]); casesAndLabels[i] = pc + casesAndLabels[i]; // defaultLabel = method.getInstructionIndex(pc + pad.getDefaultOffset()); defaultLabel = pc + pad.getDefaultOffset(); } public int[] getOffsets() { return pad.getOffsets(); } public int getDefaultLabel() { return defaultLabel; } public int[] getCasesAndLabels() { return casesAndLabels; } @Override public int[] getBranchTargets() { int[] r = new int[casesAndLabels.length / 2 + 1]; r[0] = method.getInstructionIndex(defaultLabel); for (int i = 1; i < r.length; i++) { r[i] = method.getInstructionIndex(casesAndLabels[(i - 1) * 2 + 1]); } return r; } @Override public void visit(Visitor visitor) { visitor.visitSwitch(this); } }
3,609
31.522523
98
java
WALA
WALA-master/dalvik/src/main/java/com/ibm/wala/dalvik/dex/instructions/SwitchPad.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> * Steve Suh <suhsteve@gmail.com> * * 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.dex.instructions; public interface SwitchPad { int[] getOffsets(); int[] getValues(); int[] getLabelsAndOffsets(); int getDefaultOffset(); }
2,163
34.47541
79
java
WALA
WALA-master/dalvik/src/main/java/com/ibm/wala/dalvik/dex/instructions/Throw.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> * Steve Suh <suhsteve@gmail.com> * * 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.dex.instructions; import com.ibm.wala.dalvik.classLoader.DexIMethod; import org.jf.dexlib2.Opcode; public class Throw extends Instruction { public final int throwable; public Throw(int pc, int throwable, Opcode opcode, DexIMethod method) { super(pc, opcode, method); this.throwable = throwable; } @Override public void visit(Visitor visitor) { visitor.visitThrow(this); } }
2,412
34.485294
79
java
WALA
WALA-master/dalvik/src/main/java/com/ibm/wala/dalvik/dex/instructions/UnaryOperation.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> * Steve Suh <suhsteve@gmail.com> * * 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.dex.instructions; import com.ibm.wala.dalvik.classLoader.DexIMethod; import com.ibm.wala.shrike.shrikeBT.IUnaryOpInstruction; import com.ibm.wala.shrike.shrikeBT.IUnaryOpInstruction.IOperator; import com.ibm.wala.util.debug.Assertions; import org.jf.dexlib2.Opcode; public class UnaryOperation extends Instruction { public enum OpID { MOVE, MOVE_WIDE, MOVE_EXCEPTION, NOT, NEGINT, NOTINT, NEGLONG, NOTLONG, NEGFLOAT, NEGDOUBLE, DOUBLETOLONG, DOUBLETOFLOAT, INTTOBYTE, INTTOCHAR, INTTOSHORT, DOUBLETOINT, FLOATTODOUBLE, FLOATTOLONG, FLOATTOINT, LONGTODOUBLE, LONGTOFLOAT, LONGTOINT, INTTODOUBLE, INTTOFLOAT, INTTOLONG } /** for unary ops not defined in JVML */ public enum DalvikUnaryOp implements IUnaryOpInstruction.IOperator { BITNOT; @Override public String toString() { return super.toString().toLowerCase(); } } public final OpID op; public final int source; public final int destination; public UnaryOperation( int pc, OpID op, int destination, int source, Opcode opcode, DexIMethod method) { super(pc, opcode, method); this.op = op; this.destination = destination; this.source = source; } @Override public void visit(Visitor visitor) { visitor.visitUnaryOperation(this); } public boolean isConversion() { switch (op) { case DOUBLETOLONG: case DOUBLETOFLOAT: case INTTOBYTE: case INTTOCHAR: case INTTOSHORT: case DOUBLETOINT: case FLOATTODOUBLE: case FLOATTOLONG: case FLOATTOINT: case LONGTODOUBLE: case LONGTOFLOAT: case LONGTOINT: case INTTODOUBLE: case INTTOFLOAT: case INTTOLONG: return true; default: return false; } } public boolean isMove() { switch (op) { case MOVE: case MOVE_WIDE: return true; default: return false; } } public IOperator getOperator() { switch (op) { // SSA unary ops case NOT: case NOTLONG: case NOTINT: return DalvikUnaryOp.BITNOT; case NEGINT: case NEGDOUBLE: case NEGFLOAT: case NEGLONG: return IUnaryOpInstruction.Operator.NEG; default: Assertions.UNREACHABLE(); return null; } } }
4,385
25.581818
87
java
WALA
WALA-master/dalvik/src/main/java/com/ibm/wala/dalvik/dex/util/config/DexAnalysisScopeReader.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, * * <p>Jonathan Bardin <astrosus@gmail.com> Steve Suh <suhsteve@gmail.com> * * <p>All rights reserved. * * <p>Redistribution and use in source and binary forms, with or without modification, are permitted * provided that the following conditions are met: * * <p>1. Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. * * <p>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. * * <p>3. The names of the contributors may not be used to endorse or promote products derived from * this software without specific prior written permission. * * <p>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.dex.util.config; import com.ibm.wala.core.util.config.AnalysisScopeReader; import com.ibm.wala.dalvik.classLoader.DexFileModule; import com.ibm.wala.ipa.callgraph.AnalysisScope; import com.ibm.wala.types.ClassLoaderReference; import java.io.File; import java.io.IOException; import java.net.URI; /** * Create AnalysisScope from java &amp; dalvik file. * * @see com.ibm.wala.ipa.callgraph.AnalysisScope */ public class DexAnalysisScopeReader extends AnalysisScopeReader { private static final ClassLoader WALA_CLASSLOADER = AnalysisScopeReader.class.getClassLoader(); /* BEGIN Custom change: Fixes in AndroidAnalysisScope */ // private static final String BASIC_FILE = "conf" + File.separator+ "primordial.txt"; private static final String BASIC_FILE = "./primordial.txt"; // Path inside jar /* END Custom change: Fixes in AndroidAnalysisScope */ public static AnalysisScope makeAndroidBinaryAnalysisScope(URI classPath, String exclusionsFile) throws IOException { if (classPath == null) { throw new IllegalArgumentException("classPath null"); } AnalysisScope scope = AnalysisScopeReader.instance.readJavaScope( BASIC_FILE, new File(exclusionsFile), WALA_CLASSLOADER); ClassLoaderReference loader = scope.getLoader(AnalysisScope.APPLICATION); final String path = classPath.getPath(); if (path.endsWith(".jar") || path.endsWith(".apk") || path.endsWith(".dex")) { scope.addToScope(loader, DexFileModule.make(new File(classPath))); } else { throw new IOException("could not determine type of classpath from file extension: " + path); } return scope; } }
3,603
42.95122
100
java
WALA
WALA-master/dalvik/src/main/java/com/ibm/wala/dalvik/ipa/callgraph/androidModel/AndroidModel.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.androidModel; import com.ibm.wala.classLoader.CallSiteReference; import com.ibm.wala.classLoader.IClass; import com.ibm.wala.classLoader.IField; import com.ibm.wala.classLoader.IMethod; import com.ibm.wala.core.util.ssa.ParameterAccessor; import com.ibm.wala.core.util.ssa.ParameterAccessor.Parameter; import com.ibm.wala.core.util.ssa.SSAValue; import com.ibm.wala.core.util.ssa.SSAValue.TypeKey; import com.ibm.wala.core.util.ssa.SSAValue.VariableKey; import com.ibm.wala.core.util.ssa.SSAValue.WeaklyNamedKey; import com.ibm.wala.core.util.ssa.SSAValueManager; import com.ibm.wala.core.util.ssa.TypeSafeInstructionFactory; import com.ibm.wala.core.util.strings.Atom; import com.ibm.wala.dalvik.ipa.callgraph.androidModel.parameters.FlatInstantiator; import com.ibm.wala.dalvik.ipa.callgraph.androidModel.parameters.IInstantiationBehavior; import com.ibm.wala.dalvik.ipa.callgraph.androidModel.parameters.IInstantiationBehavior.InstanceBehavior; import com.ibm.wala.dalvik.ipa.callgraph.androidModel.parameters.Instantiator; import com.ibm.wala.dalvik.ipa.callgraph.androidModel.parameters.ReuseParameters; import com.ibm.wala.dalvik.ipa.callgraph.androidModel.structure.AbstractAndroidModel; import com.ibm.wala.dalvik.ipa.callgraph.androidModel.stubs.AndroidBoot; import com.ibm.wala.dalvik.ipa.callgraph.androidModel.stubs.AndroidStartComponentTool; 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.impl.AndroidEntryPoint; import com.ibm.wala.dalvik.ipa.callgraph.propagation.cfa.IntentStarters; import com.ibm.wala.dalvik.ipa.callgraph.propagation.cfa.IntentStarters.StarterFlags; import com.ibm.wala.dalvik.util.AndroidComponent; import com.ibm.wala.dalvik.util.AndroidEntryPointManager; import com.ibm.wala.dalvik.util.AndroidTypes; 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.IAnalysisCacheView; import com.ibm.wala.ipa.cha.IClassHierarchy; import com.ibm.wala.ipa.cha.IClassHierarchyDweller; import com.ibm.wala.ipa.summaries.MethodSummary; import com.ibm.wala.ipa.summaries.SummarizedMethod; import com.ibm.wala.ipa.summaries.SummarizedMethodWithNames; import com.ibm.wala.ipa.summaries.VolatileMethodSummary; import com.ibm.wala.shrike.shrikeBT.IInvokeInstruction; import com.ibm.wala.ssa.ConstantValue; import com.ibm.wala.ssa.SSAAbstractInvokeInstruction; import com.ibm.wala.ssa.SSAInstruction; import com.ibm.wala.ssa.SSAPhiInstruction; import com.ibm.wala.types.Descriptor; import com.ibm.wala.types.FieldReference; import com.ibm.wala.types.MethodReference; import com.ibm.wala.types.Selector; import com.ibm.wala.types.TypeName; import com.ibm.wala.types.TypeReference; import com.ibm.wala.util.CancelException; import com.ibm.wala.util.MonitorUtil; import com.ibm.wala.util.MonitorUtil.IProgressMonitor; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Set; // For debug: /** * The model to be executed at application start. * * <p>This method models the lifecycle of an Android Application. By doing so it calls all * AndroidEntryPoints set in the AnalysisOptions. * * <p>Between the calls to the AndroidEntryPoints special behavior is inserted. You can change that * behavior by implementing an AbstractAndroidModel or set one of the existing ones in the * AnalysisOptions. * * <p>Additionally care of how types are instantiated is taken. You can change this behavior by * setting the IInstanciationBehavior in the AnalysisOptions. * * <p>Smaller Models exist: * MiniModel calls all components of a specific type (for example all * Activities) * MicroModel calls a single specific component * ExternalModel doesn't call anything * but fiddles with the data on its own * * <p>All these Models are added to a synthetic AndroidModelClass. * * @author Tobias Blaschke &lt;code@tobiasblaschke.de&gt; */ public class AndroidModel /* makes SummarizedMethod */ implements IClassHierarchyDweller { private final Atom name = Atom.findOrCreateAsciiAtom("AndroidModel"); public MethodReference mRef; protected IClassHierarchy cha; protected AnalysisOptions options; protected IAnalysisCacheView cache; private AbstractAndroidModel labelSpecial; private final IInstantiationBehavior instanceBehavior; private SSAValueManager paramManager; private ParameterAccessor modelAcc; private ReuseParameters reuseParameters; protected final AnalysisScope scope; protected VolatileMethodSummary body; // private JavaInstructionFactory instructionFactory; private IProgressMonitor monitor; private int maxProgress; /* * static: "boot" only once. How to assert done by the right one? */ protected static boolean doBoot = true; protected IClass klass; protected boolean built; protected SummarizedMethod model; public AndroidModel( final IClassHierarchy cha, final AnalysisOptions options, final IAnalysisCacheView cache) { this.options = options; this.cha = cha; this.cache = cache; this.built = false; this.scope = options.getAnalysisScope(); this.instanceBehavior = AndroidEntryPointManager.MANAGER.getInstantiationBehavior(cha); } /** * Generates the model on a sub-set of Entrypoints. * * <p>Asks {@link #selectEntryPoint(AndroidEntryPoint)} for each EntryPoint known to the * AndroidEntryPointManager, if the EntryPoint should be included in the model. Then calls {@link * #build(Atom, Collection)} on these. * * @param name The name the generated method will be known as */ protected void build(Atom name) throws CancelException { final List<AndroidEntryPoint> restrictedEntries = new ArrayList<>(); for (AndroidEntryPoint ep : AndroidEntryPointManager.ENTRIES) { if (selectEntryPoint(ep)) { restrictedEntries.add(ep); } } build(name, restrictedEntries); } public Atom getName() { return this.name; } public boolean isStatic() { return true; } public TypeName getReturnType() { return TypeReference.VoidName; } public Descriptor getDescriptor() throws CancelException { return getMethod().getDescriptor(); } /** * Generate the SummarizedMethod for the model (in this.model). * * <p>The actual generated model depends on the on the properties of this overloaded class. Most * generated methods should reside in the AndroidModelClass and take AndroidComponents as well as * some parameters (these marked REUSE) to the EntryPoints of the components. * * <p>Use {@link #getMethod()} to retrieve the method generated here or getMethodAs to get a * version which is wrapped to another signature. * * @param name The name the generated method will be known as * @param entrypoints The functions to call additionally to boot-code and XXX */ protected void build(Atom name, Collection<? extends AndroidEntryPoint> entrypoints) throws CancelException { // register this.klass = cha.lookupClass(AndroidModelClass.ANDROID_MODEL_CLASS); if (this.klass == null) { // add to cha this.klass = AndroidModelClass.getInstance(cha); cha.addClass(this.klass); } this.reuseParameters = new ReuseParameters(this.instanceBehavior, this); // this.instructionFactory = new JavaInstructionFactory(); // TODO: TSIF // Complete the signature of the method reuseParameters.collectParameters(entrypoints); this.mRef = reuseParameters.toMethodReference(null); this.modelAcc = new ParameterAccessor(this.mRef, !isStatic()); this.paramManager = new SSAValueManager(modelAcc); final Selector selector = this.mRef.getSelector(); final AndroidModelClass mClass = AndroidModelClass.getInstance(cha); if (mClass.containsMethod(selector)) { assert (mClass.getMethod(selector) instanceof SummarizedMethod); this.model = (SummarizedMethod) mClass.getMethod(selector); return; } this.body = new VolatileMethodSummary(new MethodSummary(this.mRef)); this.body.setStatic(true); this.labelSpecial = AndroidEntryPointManager.MANAGER.makeModelBehavior( this.body, new TypeSafeInstructionFactory(cha), this.paramManager, entrypoints); this.monitor = AndroidEntryPointManager.MANAGER.getProgressMonitor(); this.maxProgress = entrypoints.size(); AndroidModel.doBoot &= AndroidEntryPointManager.MANAGER.getDoBootSequence(); // BUILD this.monitor.beginTask("Building " + name, this.maxProgress); populate(entrypoints); assert (cha.lookupClass(AndroidModelClass.ANDROID_MODEL_CLASS) != null) : "Adding the class failed!"; if (this.klass == null) { throw new IllegalStateException("Could not find ANDROID_MODEL_CLASS in cha."); } this.body.setLocalNames(this.paramManager.makeLocalNames()); this.model = new SummarizedMethodWithNames(this.mRef, this.body, this.klass) { @Override public TypeReference getParameterType(int i) { IClassHierarchy cha = getClassHierarchy(); TypeReference tRef = super.getParameterType(i); if (tRef.isClassType() && cha.lookupClass(tRef) == null) { for (IClass c : cha) { if (c.getName().toString().equals(tRef.getName().toString())) { return c.getReference(); } } } return tRef; } }; this.built = true; } private void register(SummarizedMethod model) { IClass klass = getDeclaringClass(); ((AndroidModelClass) klass).setMacroModel(model); } /** * Building the SummarizedMethod is delayed upon the first class to this method. * * @return the method for this model as generated by build() */ public SummarizedMethod getMethod() throws CancelException { if (!built) { build(this.name); register(this.model); } return this.model; } /** * The class the Method representing this Model resides in. * * <p>Most likely the AndroidModelClass. */ public IClass getDeclaringClass() { return this.klass; } /** * Overridden by models to restraint Entrypoints. * * <p>For each entrypoint this method is queried if it should be part of the model. * * @param ep The EntryPoint in question * @return if the given EntryPoint shall be part of the model */ protected boolean selectEntryPoint(AndroidEntryPoint ep) { return true; } /** * Add Instructions to the model. * * <p>{@link #build(Atom, Collection)} prepares the MethodSummary, then calls populate() to add * the instructions, then finishes the model. Populate is only an extra function to shorten * build(), calling it doesn't make sense in an other context. */ private void populate(Iterable<? extends AndroidEntryPoint> entrypoints) throws CancelException { assert !built : "You can only build once"; int currentProgress = 0; final TypeSafeInstructionFactory tsif = new TypeSafeInstructionFactory(this.cha); final Instantiator instantiator = new Instantiator(this.body, tsif, this.paramManager, this.cha, this.mRef, this.scope); boolean enteredASection = false; // // Add preparing code to the model // if (AndroidModel.doBoot) { // final Set<Parameter> allActivities = new // HashSet<Parameter>(modelAcc.allExtend(AndroidTypes.ActivityName, getClassHierarchy())); // assert(allActivities.size() > 0) : "There are no Activities in the Model"; // XXX // final IntentStarters.StartInfo toolInfo = // IntentStarters.StartInfo.makeContextFree(null); // final AndroidStartComponentTool tool = new AndroidStartComponentTool(this.cha, // this.mRef, toolInfo.getFlags(), // /* caller */ null, tsif, modelAcc, this.paramManager, this.body, /* self // */ null, toolInfo, /* callerNd */ null); final SSAValue application; { final SSAValue tmpApp = modelAcc.firstExtends(AndroidTypes.ApplicationName, this.cha); if (tmpApp != null) { application = tmpApp; } else { // Generate a real one? application = paramManager.getUnmanaged(AndroidTypes.Application, "app"); this.body.addConstant(application.getNumber(), new ConstantValue(null)); application.setAssigned(); } } final SSAValue nullIntent; { nullIntent = paramManager.getUnmanaged(AndroidTypes.Intent, "nullIntent"); this.body.addConstant(nullIntent.getNumber(), new ConstantValue(null)); nullIntent.setAssigned(); } final SSAValue nullBinder; { nullBinder = paramManager.getUnmanaged(AndroidTypes.IBinder, "nullBinder"); this.body.addConstant(nullBinder.getNumber(), new ConstantValue(null)); nullBinder.setAssigned(); } { final AndroidBoot boot = new AndroidBoot(); boot.addBootCode(tsif, paramManager, this.body); // tool.attachActivities(allActivities, application, boot.getMainThread(), /* Should be // application context TODO */ // boot.getPackageContext(), nullBinder, nullIntent); } // TODO: Assign context to the other components } for (final AndroidEntryPoint ep : entrypoints) { this.monitor.subTask(ep.getMethod().getReference().getSignature()); if (!selectEntryPoint(ep)) { assert false : "The ep should not reach here!"; currentProgress++; continue; } // // Is special handling to be inserted? // if (this.labelSpecial.hadSectionSwitch(ep.order)) { this.labelSpecial.enter(ep.getSection(), body.getNextProgramCounter()); enteredASection = true; } // // Collect arguments to ep // if there are multiple paramses call the entrypoint multiple times // List<List<SSAValue>> paramses = new ArrayList<>(1); { final List<Integer> mutliTypePositions = new ArrayList<>(); { // Add single-type parameters and collect positions for multi-type final List<SSAValue> params = new ArrayList<>(ep.getNumberOfParameters()); paramses.add(params); for (int i = 0; i < ep.getNumberOfParameters(); ++i) { if (ep.getParameterTypes(i).length != 1) { mutliTypePositions.add(i); params.add(null); // will get set later } else { for (final TypeReference type : ep.getParameterTypes(i)) { if (this.instanceBehavior.getBehavior(type.getName(), ep.getMethod(), null) == InstanceBehavior.REUSE) { params.add(this.paramManager.getCurrent(new TypeKey(type.getName()))); } else if (type.isPrimitiveType()) { params.add(paramManager.getUnmanaged(type, "p")); } else { // It is an CREATE parameter final boolean asManaged = false; final VariableKey key = null; // auto-generates UniqueKey final Set<SSAValue> seen = null; params.add(instantiator.createInstance(type, asManaged, key, seen)); } } } } } // Now for the mutliTypePositions: we'll build the Cartesian product for these for (int positionInMutliTypePosition = 0; positionInMutliTypePosition < mutliTypePositions.size(); ++positionInMutliTypePosition) { final Integer multiTypePosition = mutliTypePositions.get(positionInMutliTypePosition); final TypeReference[] typesOnPosition = ep.getParameterTypes(multiTypePosition); final int typeCountOnPosition = typesOnPosition.length; { // Extend the list size to hold the product final List<List<SSAValue>> new_paramses = new ArrayList<>(paramses.size() * typeCountOnPosition); for (int i = 0; i < typeCountOnPosition; ++i) { // new_paramses.addAll(paramses); *grrr* JVM! You could copy at least null - but // noooo... for (final List<SSAValue> params : paramses) { final List<SSAValue> new_params = new ArrayList<>(params.size()); new_params.addAll(params); new_paramses.add(new_params); } } paramses = new_paramses; } { // set the current multiTypePosition for (int i = 0; i < paramses.size(); ++i) { final List<SSAValue> params = paramses.get(i); assert (params.get(multiTypePosition) == null) : "Expected null, got " + params.get(multiTypePosition) + " iter " + i; // XXX: This could be faster, but well... final TypeReference type = typesOnPosition[(i * (positionInMutliTypePosition + 1)) % typeCountOnPosition]; if (this.instanceBehavior.getBehavior(type.getName(), ep.getMethod(), null) == InstanceBehavior.REUSE) { params.set( multiTypePosition, this.paramManager.getCurrent(new TypeKey(type.getName()))); } else if (type.isPrimitiveType()) { params.set(multiTypePosition, paramManager.getUnmanaged(type, "p")); } else { // It is an CREATE parameter final boolean asManaged = false; final VariableKey key = null; // auto-generates UniqueKey final Set<SSAValue> seen = null; params.set( multiTypePosition, instantiator.createInstance(type, asManaged, key, seen)); } } } } } /*{ // DEBUG if (paramses.size() > 1) { System.out.println("\n\nParamses on " + ep.getMethod().getSignature() + ":"); for (final List<SSAValue> params : paramses) { System.out.println("\t" + params); } } } // */ // // Insert the call optionally handling its return value // for (final List<SSAValue> params : paramses) { final int callPC = body.getNextProgramCounter(); final CallSiteReference site = ep.makeSite(callPC); final SSAAbstractInvokeInstruction invokation; final SSAValue exception = paramManager.getException(); // will hold the exception object of ep if (ep.getMethod().getReturnType().equals(TypeReference.Void)) { invokation = tsif.InvokeInstruction(callPC, params, exception, site); this.body.addStatement(invokation); } else { // Check if we have to mix in the return value of this ep using a Phi final TypeReference returnType = ep.getMethod().getReturnType(); final TypeKey returnKey = new TypeKey(returnType.getName()); if (this.paramManager.isSeen(returnKey)) { // if it's seen it most likely is a REUSE-Type. However probably it makes sense for // other types too so we don't test on isReuse. final SSAValue oldValue = this.paramManager.getCurrent(returnKey); this.paramManager.invalidate(returnKey); final SSAValue returnValue = paramManager.getUnallocated(returnType, returnKey); invokation = tsif.InvokeInstruction(callPC, returnValue, params, exception, site); this.body.addStatement(invokation); this.paramManager.setAllocation(returnValue, invokation); // ... and Phi things together ... this.paramManager.invalidate(returnKey); final SSAValue newValue = this.paramManager.getFree(returnType, returnKey); final int phiPC = body.getNextProgramCounter(); final List<SSAValue> toPhi = new ArrayList<>(2); toPhi.add(oldValue); toPhi.add(returnValue); final SSAPhiInstruction phi = tsif.PhiInstruction(phiPC, newValue, toPhi); this.body.addStatement(phi); this.paramManager.setPhi(newValue, phi); } else { // Just throw away the return value final SSAValue returnValue = paramManager.getUnmanaged(returnType, new SSAValue.UniqueKey()); invokation = tsif.InvokeInstruction(callPC, returnValue, params, exception, site); this.body.addStatement(invokation); } } } this.monitor.worked(++currentProgress); MonitorUtil.throwExceptionIfCanceled(this.monitor); } // Close all sections by "jumping over" the remaining labels if (enteredASection) { labelSpecial.finish(body.getNextProgramCounter()); } this.monitor.done(); } /** * Get method of the Model in an other Signature. * * <p>Generates a new Method that wraps the model so it can be called using the given Signature. * Flags control the behavior of that wrapper. * * <p>Arguments to the wrapping function are "connected through" to the model based on their type * only, so if there are multiple Arguments of the same type this may yield to unexpected * connections. * * <p>This method is called by the IntentCoentextInterpreter. * * @see com.ibm.wala.dalvik.ipa.callgraph.propagation.cfa.IntentContextInterpreter * @see com.ibm.wala.dalvik.ipa.callgraph.propagation.cfa.IntentStarters * @param asMethod The signature to generate * @param caller The class of the caller; only needed depending on the flags * @param info The IntentSterter used * @param callerNd CGNoodle of the caller - may be null * @return A wrapper that calls the model */ public SummarizedMethod getMethodAs( MethodReference asMethod, TypeReference caller, IntentStarters.StartInfo info, CGNode callerNd) throws CancelException { Set<StarterFlags> flags = null; if (info != null) { flags = info.getFlags(); } // System.out.println("\n\nAS: " + asMethod + "\n\n"); if (!built) { getMethod(); } if (asMethod == null) { throw new IllegalArgumentException("asMethod may not be null"); } if (flags == null) { flags = Collections.emptySet(); } final TypeSafeInstructionFactory instructionFactory = new TypeSafeInstructionFactory(getClassHierarchy()); final ParameterAccessor acc = new ParameterAccessor(asMethod, /* hasImplicitThis: */ true); // final AndroidModelParameterManager pm = new AndroidModelParameterManager(acc); final SSAValueManager pm = new SSAValueManager(acc); if (callerNd != null) { pm.breadCrumb = "Caller: " + caller + " Context: " + callerNd.getContext() + " Model: " + this.getClass() + " Name: " + this.getName(); } else { pm.breadCrumb = "Caller: " + caller + " Model: " + this.getClass(); } final VolatileMethodSummary redirect = new VolatileMethodSummary(new MethodSummary(asMethod)); redirect.setStatic(false); final Instantiator instantiator = new Instantiator(redirect, instructionFactory, pm, this.cha, asMethod, this.scope); final Parameter self; { self = acc.getThisAs(caller); pm.setAllocation(self, null); // self = acc.getThis(); } final ParameterAccessor modelAcc = new ParameterAccessor(this.model); /*{ // DEBUG System.out.println("FOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOO: Calleeeeeee" + this.model); for (SSAValue calleeParam : modelAcc.all()) { System.out.println("\tCalleeArg: " + calleeParam); } try { System.out.println("\tCalleeP1: " + modelAcc.getParameter(1)); System.out.println("\tCalleeM0: " + this.model.getParameterType(0)); System.out.println("\tCalleeP2: " + modelAcc.getParameter(2)); System.out.println("\tCalleeM1: " + this.model.getParameterType(1)); MethodReference modelRef = this.model.getReference(); System.out.println("\tmRef: " + modelRef); System.out.println("\tCalleeR0: " + modelRef.getParameterType(0)); System.out.println("\tCalleeR1: " + modelRef.getParameterType(1)); } catch (Exception e) { } }*/ final List<Parameter> modelsActivities = modelAcc.allExtend(AndroidTypes.ActivityName, getClassHierarchy()); // are in models scope final List<SSAValue> allActivities = new ArrayList<>(modelsActivities.size()); // create instances in this scope for (Parameter activity : modelsActivities) { final TypeReference activityType = activity.getType(); final Parameter inAsMethod = acc.firstOf(activityType); if (inAsMethod != null) { allActivities.add(inAsMethod); } else { final Atom fdName = activityType.getName().getClassName(); final AndroidModelClass mClass = AndroidModelClass.getInstance(cha); if (AndroidEntryPointManager.MANAGER.doFlatComponents()) { if (mClass.getField(fdName) != null) { final IField field = mClass.getField(fdName); final int instPC = redirect.getNextProgramCounter(); final SSAValue target = pm.getUnallocated( activityType, new SSAValue.WeaklyNamedKey(activityType.getName(), "got" + fdName.toString())); final SSAInstruction getInst = instructionFactory.GetInstruction(instPC, target, field.getReference()); redirect.addStatement(getInst); pm.setAllocation(target, getInst); allActivities.add(target); } else { final SSAValue newInstance = instantiator.createInstance(activityType, false, null, null); allActivities.add(newInstance); mClass.putField(fdName, activityType); final int instPC = redirect.getNextProgramCounter(); final FieldReference fdRef = FieldReference.findOrCreate(mClass.getReference(), fdName, activityType); final SSAInstruction putInst = instructionFactory.PutInstruction(instPC, newInstance, fdRef); redirect.addStatement(putInst); System.out.println("All activities new: " + newInstance); } } else { final SSAValue newInstance = instantiator.createInstance(activityType, false, null, null); allActivities.add(newInstance); } } } assert (allActivities.size() == modelsActivities.size()); // The defaults for connectThrough final Set<SSAValue> defaults = new HashSet<>(); { // Calls that don't take a bundle usually call through with a null-bundle final SSAValue nullBundle = pm.getUnmanaged(AndroidTypes.Bundle, "nullBundle"); redirect.addConstant(nullBundle.getNumber(), new ConstantValue(null)); nullBundle.setAssigned(); defaults.add(nullBundle); } { // We may have an incoming parameter of [Intent - unpack it to Intent final TypeName intentArray = TypeName.findOrCreate("[Landroid/content/Intent"); final SSAValue incoming = acc.firstOf(intentArray); // TODO: Take all not only the first if (incoming != null) { final VariableKey unpackedIntentKey = new WeaklyNamedKey(AndroidTypes.IntentName, "unpackedIntent"); final SSAValue unpackedIntent = pm.getUnallocated(AndroidTypes.Intent, unpackedIntentKey); final int pc = redirect.getNextProgramCounter(); final SSAInstruction fetch = instructionFactory.ArrayLoadInstruction(pc, unpackedIntent, incoming, 0); redirect.addStatement(fetch); pm.setAllocation(unpackedIntent, fetch); defaults.add(unpackedIntent); } } final SSAValue intent = acc.firstExtends(AndroidTypes.Intent, cha); final AndroidStartComponentTool tool = new AndroidStartComponentTool( getClassHierarchy(), asMethod, flags, caller, instructionFactory, acc, pm, redirect, self, info); final AndroidTypes.AndroidContextType contextType; final SSAValue androidContext; // of AndroidTypes.Context: The callers android-context androidContext = tool.fetchCallerContext(); contextType = tool.typeOfCallerContext(); try { // Add additional Info if Exception occurs... // TODO: Check, that caller is an activity where necessary! // final SSAValue iBinder = tool.fetchIBinder(androidContext); // tool.assignIBinder(iBinder, allActivities); if (intent != null) { tool.setIntent(intent, allActivities); } else if (!info.isSystemService()) { // it's normal for SystemServices } // Call the model { final List<SSAValue> redirectParams = acc.connectThrough( modelAcc, new HashSet<>(allActivities), defaults, getClassHierarchy(), /* IInstantiator this.createInstance(type, redirect, pm) */ instantiator, false, null, null); final int callPC = redirect.getNextProgramCounter(); final CallSiteReference site = CallSiteReference.make( callPC, this.model.getReference(), IInvokeInstruction.Dispatch.STATIC); final SSAAbstractInvokeInstruction invokation; final SSAValue exception = pm.getException(); if (this.model.getReference().getReturnType().equals(TypeReference.Void)) { invokation = instructionFactory.InvokeInstruction(callPC, redirectParams, exception, site); } else { // it's startExternal or SystemService if (this instanceof SystemServiceModel) { final SSAValue svc = pm.getUnmanaged(TypeReference.JavaLangObject, "systemService"); invokation = instructionFactory.InvokeInstruction(callPC, svc, redirectParams, exception, site); // SHORTCUT: redirect.addStatement(invokation); if (instructionFactory.isAssignableFrom( svc.getType(), svc.getValidIn().getReturnType())) { final int returnPC = redirect.getNextProgramCounter(); final SSAInstruction returnInstruction = instructionFactory.ReturnInstruction(returnPC, svc); redirect.addStatement(returnInstruction); } final IClass declaringClass = this.cha.lookupClass(asMethod.getDeclaringClass()); if (declaringClass == null) { throw new IllegalStateException( "Unable to retreive te IClass of " + asMethod.getDeclaringClass() + " from " + "Method " + asMethod); } redirect.setLocalNames(pm.makeLocalNames()); SummarizedMethod override = new SummarizedMethodWithNames(mRef, redirect, declaringClass); return override; } else if (this instanceof ExternalModel) { final SSAValue trash = pm.getUnmanaged(AndroidTypes.Intent, "trash"); invokation = instructionFactory.InvokeInstruction( callPC, trash, redirectParams, exception, site); } else { throw new UnsupportedOperationException("Can't handle a " + this.model.getClass()); } } redirect.addStatement(invokation); } // Optionally call onActivityResult if (flags.contains(StarterFlags.CALL_ON_ACTIVITY_RESULT) && // TODO: Test multiple activities !flags.contains(StarterFlags.CONTEXT_FREE)) { // TODO: Doesn't this work without context? // Collect all Activity.mResultCode and Activity.mResultData // Result information of all activities. final List<SSAValue> resultCodes = new ArrayList<>(); final List<SSAValue> resultData = new ArrayList<>(); final SSAValue mResultCode; // = Phi(resultCodes) final SSAValue mResultData; // = Phi(resultData) tool.fetchResults(resultCodes, resultData, allActivities); if (resultCodes.size() == 0) { throw new IllegalStateException( "The call " + asMethod + " from " + caller + " failed, as the model " + this.model + " did not take an activity to read the result from"); } mResultCode = tool.addPhi(resultCodes); mResultData = tool.addPhi(resultData); { // Send back the results // TODO: Assert caller is an Activity final SSAValue outRequestCode = acc.firstOf(TypeReference.Int); // TODO: Check is's the right parameter final int callPC = redirect.getNextProgramCounter(); // void onActivityResult (int requestCode, int resultCode, Intent data) final Selector mSel = Selector.make("onActivityResult(IILandroid/content/Intent;)V"); final MethodReference mRef = MethodReference.findOrCreate(caller, mSel); final CallSiteReference site = CallSiteReference.make(callPC, mRef, IInvokeInstruction.Dispatch.VIRTUAL); // final SSAValue exception = new SSAValue(pm.getUnmanaged(), // TypeReference.JavaLangException, asMethod, "exception"); final SSAValue exception = pm.getException(); final List<SSAValue> params = new ArrayList<>(); params.add(self); params.add(outRequestCode); // Was an agument to start... params.add(mResultCode); params.add(mResultData); final SSAInstruction invokation = instructionFactory.InvokeInstruction(callPC, params, exception, site); redirect.addStatement(invokation); } // */ } final IClass declaringClass = this.cha.lookupClass(asMethod.getDeclaringClass()); if (declaringClass == null) { throw new IllegalStateException( "Unable to retreive te IClass of " + asMethod.getDeclaringClass() + " from " + "Method " + asMethod); } // TODO: Throw into an other loader redirect.setLocalNames(pm.makeLocalNames()); SummarizedMethod override = new SummarizedMethodWithNames(mRef, redirect, declaringClass); // assert(asMethod.getReturnType().equals(TypeReference.Void)) : "getMethodAs does not support // return values. Requested: " + // asMethod.getReturnType().toString(); // TODO: Implement return override; } catch (Exception e) { e.printStackTrace(); System.err.println("\nOccured in getMethodAs with parameters of:"); System.err.println(acc.dump()); System.err.println("\tpm=\t" + pm); System.err.println("\tself=\t" + self); System.err.println("\tmodelAcc=\t" + acc.dump()); // final List<Parameter> modelsActivities = modelAcc.allExtend(AndroidTypes.ActivityName, // getClassHierarchy()); // are in models scope // final List<SSAValue> allActivities = new ArrayList<SSAValue>(modelsActivities.size()); // // create instances in this scope System.err.println("\tcontextType=\t" + contextType); System.err.println("\tandroidContetx=\t" + androidContext); System.err.println("\tasMethod=\t" + asMethod); System.err.println("\tcaller=\t" + caller); System.err.println("\tinfo=\t" + info); System.err.println("\tcallerND=\t" + callerNd); System.err.println("\tthis=\t" + this.getClass().toString()); System.err.println("\tthis.name=\t" + this.name); throw new IllegalStateException(e); } } /** * Creates an "encapsulated" version of the model. * * <p>The generated method will take no parameters. New instances for REUSE-Parameters will be * created. * * <p>This variant is useful for the start of an analysis. */ public IMethod getMethodEncap() throws CancelException { final MethodReference asMethod; { final TypeReference clazz = AndroidModelClass.ANDROID_MODEL_CLASS; final Atom methodName = Atom.concat(this.getName(), Atom.findOrCreateAsciiAtom("Encap")); // final TypeName returnType = this.getReturnType(); final TypeName returnType = TypeReference.VoidName; final Descriptor descr = Descriptor.findOrCreate(new TypeName[] {}, returnType); asMethod = MethodReference.findOrCreate(clazz, methodName, descr); } final AndroidModelClass mClass = AndroidModelClass.getInstance(cha); if (mClass.containsMethod(asMethod.getSelector())) { // There's already an encap for this method return mClass.getMethod(asMethod.getSelector()); } final VolatileMethodSummary encap = new VolatileMethodSummary(new MethodSummary(asMethod)); encap.setStatic(true); final TypeSafeInstructionFactory instructionFactory = new TypeSafeInstructionFactory(getClassHierarchy()); final ParameterAccessor acc = new ParameterAccessor(asMethod, /* hasImplicitThis: */ false); final SSAValueManager pm = new SSAValueManager(acc); pm.breadCrumb = "Encap: " + this.getClass().toString(); final SummarizedMethod model = getMethod(); final List<SSAValue> params = new ArrayList<>(); { // Collect Params final FlatInstantiator instantiator = new FlatInstantiator(encap, instructionFactory, pm, this.cha, asMethod, this.scope); for (int i = 0; i < model.getNumberOfParameters(); ++i) { final TypeReference argT = model.getParameterType(i); final SSAValue arg; if (AndroidEntryPointManager.MANAGER.doFlatComponents() && AndroidComponent.isAndroidComponent(argT, cha)) { // Get / Put filed in AndroidModelClass for Android-Components final Atom fdName = argT.getName().getClassName(); if (mClass.getField(fdName) != null) { final IField field = mClass.getField(fdName); final int instPC = encap.getNextProgramCounter(); arg = pm.getUnallocated( argT, new SSAValue.WeaklyNamedKey(argT.getName(), "got" + fdName.toString())); final SSAInstruction getInst = instructionFactory.GetInstruction(instPC, arg, field.getReference()); encap.addStatement(getInst); pm.setAllocation(arg, getInst); } else { arg = instantiator.createInstance(argT, false, null, null); mClass.putField(fdName, argT); final int instPC = encap.getNextProgramCounter(); final FieldReference fdRef = FieldReference.findOrCreate(mClass.getReference(), fdName, argT); final SSAInstruction putInst = instructionFactory.PutInstruction(instPC, arg, fdRef); encap.addStatement(putInst); } } else { final boolean managed = false; final SSAValue.VariableKey key = new SSAValue.TypeKey(argT.getName()); arg = instantiator.createInstance(argT, managed, key, null); } params.add(arg); } } { // Call the model final int callPC = encap.getNextProgramCounter(); final CallSiteReference site = CallSiteReference.make(callPC, model.getReference(), IInvokeInstruction.Dispatch.STATIC); final SSAValue exception = pm.getException(); final SSAAbstractInvokeInstruction invokation = instructionFactory.InvokeInstruction(callPC, params, exception, site); encap.addStatement(invokation); } encap.setLocalNames(pm.makeLocalNames()); final SummarizedMethod method = new SummarizedMethodWithNames(asMethod, encap, mClass); mClass.addMethod(method); return method; } @Override public IClassHierarchy getClassHierarchy() { return this.cha; } @Override public String toString() { return "<" + this.getClass() + " name=" + this.name + " />"; } }
42,706
40.382752
105
java
WALA
WALA-master/dalvik/src/main/java/com/ibm/wala/dalvik/ipa/callgraph/androidModel/AndroidModelClass.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.androidModel; import com.ibm.wala.classLoader.CallSiteReference; import com.ibm.wala.classLoader.FieldImpl; import com.ibm.wala.classLoader.IClass; import com.ibm.wala.classLoader.IField; import com.ibm.wala.classLoader.IMethod; import com.ibm.wala.classLoader.NewSiteReference; import com.ibm.wala.classLoader.SyntheticClass; import com.ibm.wala.core.util.ssa.SSAValue; import com.ibm.wala.core.util.ssa.TypeSafeInstructionFactory; import com.ibm.wala.core.util.strings.Atom; import com.ibm.wala.dalvik.util.AndroidEntryPointManager; import com.ibm.wala.ipa.cha.IClassHierarchy; import com.ibm.wala.ipa.summaries.MethodSummary; import com.ibm.wala.ipa.summaries.SummarizedMethod; import com.ibm.wala.ipa.summaries.SummarizedMethodWithNames; import com.ibm.wala.ipa.summaries.VolatileMethodSummary; import com.ibm.wala.shrike.shrikeBT.IInvokeInstruction; import com.ibm.wala.shrike.shrikeCT.ClassConstants; import com.ibm.wala.ssa.SSAInstruction; import com.ibm.wala.types.ClassLoaderReference; import com.ibm.wala.types.FieldReference; import com.ibm.wala.types.MethodReference; import com.ibm.wala.types.Selector; import com.ibm.wala.types.TypeName; import com.ibm.wala.types.TypeReference; import com.ibm.wala.util.collections.HashMapFactory; import com.ibm.wala.util.collections.HashSetFactory; 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 org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Encapsulates synthetic methods for modeling Androids lifecycle. * * <p>In the generated code this class may be found as "Lcom/ibm/wala/AndroidModelClass" * * @see com.ibm.wala.ipa.callgraph.impl.FakeRootClass * @author Tobias Blaschke &lt;code@tobiasblaschke.de&gt; TODO: Move this class into an other * loader? Currently: Primordial */ public final /* singleton */ class AndroidModelClass extends SyntheticClass { private static final Logger logger = LoggerFactory.getLogger(AndroidModelClass.class); public static final TypeReference ANDROID_MODEL_CLASS = TypeReference.findOrCreate( ClassLoaderReference.Primordial, TypeName.string2TypeName("Lcom/ibm/wala/AndroidModelClass")); private final IClassHierarchy cha; public static AndroidModelClass getInstance(IClassHierarchy cha) { IClass android = cha.lookupClass(ANDROID_MODEL_CLASS); AndroidModelClass mClass; if (android == null) { mClass = new AndroidModelClass(cha); } else if (!(android instanceof AndroidModelClass)) { throw new IllegalArgumentException( String.format( "android model class does not have expected type %s, but %s!", AndroidModelClass.class, android.getClass().toString())); } else { mClass = (AndroidModelClass) android; } return mClass; } private AndroidModelClass(IClassHierarchy cha) { super(ANDROID_MODEL_CLASS, cha); this.addMethod(this.clinit()); this.cha = cha; this.cha.addClass(this); } /** * Generate clinit for AndroidModelClass. * * <p>clinit initializes AndroidComponents */ private SummarizedMethod clinit() { final MethodReference clinitRef = MethodReference.findOrCreate(this.getReference(), MethodReference.clinitSelector); final VolatileMethodSummary clinit = new VolatileMethodSummary(new MethodSummary(clinitRef)); clinit.setStatic(true); final TypeSafeInstructionFactory instructionFactory = new TypeSafeInstructionFactory(cha); final Set<TypeReference> components = AndroidEntryPointManager.getComponents(); int ssaNo = 1; if (AndroidEntryPointManager.MANAGER.doFlatComponents()) { for (TypeReference component : components) { final SSAValue instance = new SSAValue(ssaNo++, component, clinitRef); { // New final int pc = clinit.getNextProgramCounter(); final NewSiteReference nRef = NewSiteReference.make(pc, component); final SSAInstruction instr = instructionFactory.NewInstruction(pc, instance, nRef); clinit.addStatement(instr); } { // Call cTor final int pc = clinit.getNextProgramCounter(); final MethodReference ctor = MethodReference.findOrCreate(component, MethodReference.initSelector); final CallSiteReference site = CallSiteReference.make(pc, ctor, IInvokeInstruction.Dispatch.SPECIAL); final SSAValue exception = new SSAValue(ssaNo++, TypeReference.JavaLangException, clinitRef); final List<SSAValue> params = new ArrayList<>(); params.add(instance); final SSAInstruction ctorCall = instructionFactory.InvokeInstruction(pc, params, exception, site); clinit.addStatement(ctorCall); } { // Put into AndroidModelClass final Atom fdName = component.getName().getClassName(); putField(fdName, component); final int pc = clinit.getNextProgramCounter(); final FieldReference fdRef = FieldReference.findOrCreate(this.getReference(), fdName, component); final SSAInstruction putInst = instructionFactory.PutInstruction(pc, instance, fdRef); clinit.addStatement(putInst); } } } return new SummarizedMethodWithNames(clinitRef, clinit, this); } // // Contents of the class: Methods // private IMethod macroModel = null; // private IMethod allActivitiesModel = null; private final Map<Selector, IMethod> methods = HashMapFactory.make(); // does not contain macroModel public boolean containsMethod(Selector selector) { return (((macroModel != null) && macroModel.getSelector().equals(selector)) || methods.containsKey(selector)); } @Override public IMethod getMethod(Selector selector) { // assert (macroModel != null) : "Macro Model was not set yet!"; if ((macroModel != null) && macroModel.getSelector().equals(selector)) { return macroModel; } if (methods.containsKey(selector)) { return methods.get(selector); } if (selector.equals(MethodReference.initSelector)) { logger.warn("AndroidModelClass is not intended to be initialized"); return null; } throw new IllegalArgumentException("Could not resolve " + selector); } @Override public Collection<IMethod> getDeclaredMethods() { Set<IMethod> methods = HashSetFactory.make(); if (this.macroModel != null) { methods.add(macroModel); } methods.addAll(this.methods.values()); return Collections.unmodifiableCollection(methods); } @Override public Collection<IMethod> getAllMethods() { return getDeclaredMethods(); } /* package private */ void setMacroModel(IMethod model) { assert (this.macroModel == null); this.macroModel = model; } public void addMethod(IMethod method) { if (this.methods.containsKey(method.getSelector())) { // TODO: Check this matches on signature not on contents! // TODO: What on different Context versions throw new IllegalStateException( "The AndroidModelClass already contains a Method called" + method.getName()); } assert (this.methods != null); this.methods.put(method.getSelector(), method); } @Override public IMethod getClassInitializer() { return getMethod(MethodReference.clinitSelector); } // // Contents of the class: Fields // We have none... // private final Map<Atom, IField> fields = new HashMap<>(); @Override public IField getField(Atom name) { return fields.getOrDefault(name, null); } public void putField(Atom name, TypeReference type) { final FieldReference fdRef = FieldReference.findOrCreate(this.getReference(), name, type); final int accessFlags = ClassConstants.ACC_STATIC | ClassConstants.ACC_PUBLIC; final IField field = new FieldImpl(this, fdRef, accessFlags, null, null); this.fields.put(name, field); } /** This class does not contain any fields. */ @Override public Collection<IField> getAllFields() { return fields.values(); } /** This class does not contain any fields. */ @Override public Collection<IField> getDeclaredStaticFields() { return fields.values(); } /** This class does not contain any fields. */ @Override public Collection<IField> getAllStaticFields() { return fields.values(); } /** This class does not contain any fields. */ @Override public Collection<IField> getDeclaredInstanceFields() throws UnsupportedOperationException { return Collections.emptySet(); } /** This class does not contain any fields. */ @Override public Collection<IField> getAllInstanceFields() { return Collections.emptySet(); } // // Class Modifiers // /** This is a public final class. */ @Override public int getModifiers() { return ClassConstants.ACC_PUBLIC | ClassConstants.ACC_FINAL; } @Override public boolean isPublic() { return true; } @Override public boolean isPrivate() { return false; } @Override public boolean isInterface() { return false; } @Override public boolean isAbstract() { return false; } @Override public boolean isArrayClass() { return false; } /** This is a subclass of the root class. */ @Override public IClass getSuperclass() throws UnsupportedOperationException { return getClassHierarchy().getRootClass(); } /** This class does not impement any interfaces. */ @Override public Collection<IClass> getAllImplementedInterfaces() { return Collections.emptySet(); } @Override public Collection<IClass> getDirectInterfaces() { return Collections.emptySet(); } // // Misc // @Override public boolean isReferenceType() { return getReference().isReferenceType(); } }
11,866
32.617564
97
java
WALA
WALA-master/dalvik/src/main/java/com/ibm/wala/dalvik/ipa/callgraph/androidModel/IntentModel.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.androidModel; import com.ibm.wala.core.util.strings.Atom; import com.ibm.wala.dalvik.ipa.callgraph.impl.AndroidEntryPoint; import com.ibm.wala.dalvik.util.AndroidComponent; import com.ibm.wala.ipa.callgraph.AnalysisOptions; import com.ibm.wala.ipa.callgraph.IAnalysisCacheView; import com.ibm.wala.ipa.cha.IClassHierarchy; import com.ibm.wala.ipa.summaries.SummarizedMethod; import com.ibm.wala.util.CancelException; /** * Like MicroModel but includes CallBacks. * * @author Tobias Blaschke &lt;code@tobiasblaschke.de&gt; * @since 2014-02-12 */ public class IntentModel extends AndroidModel { public final Atom name; public final Atom target; // private SummarizedMethod activityModel; /** * Restrict the model to Activities. * * <p>{@inheritDoc} */ @Override protected boolean selectEntryPoint(AndroidEntryPoint ep) { return ep.isMemberOf(this.target) || ep.belongsTo(AndroidComponent.APPLICATION) || ep.belongsTo(AndroidComponent.PROVIDER); } public IntentModel( final IClassHierarchy cha, final AnalysisOptions options, final IAnalysisCacheView cache, Atom target) { super(cha, options, cache); this.target = target; this.name = Atom.concat( Atom.findOrCreateAsciiAtom("intent"), target.right(target.rIndex((byte) '/') - 1)); } private void register(SummarizedMethod model) { AndroidModelClass mClass = AndroidModelClass.getInstance(cha); if (!mClass.containsMethod(model.getSelector())) { mClass.addMethod(model); } } @Override public Atom getName() { return this.name; } @Override public SummarizedMethod getMethod() throws CancelException { /*AndroidModelClass mClass = AndroidModelClass.getInstance(cha); if (mClass.containsMethod(null)) { Selector sel = new Selector(this.name return mClass.getMethod(); }*/ if (!built) { super.build(this.name); this.register(super.model); } return super.model; } }
3,947
33.631579
95
java
WALA
WALA-master/dalvik/src/main/java/com/ibm/wala/dalvik/ipa/callgraph/androidModel/MicroModel.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.androidModel; import com.ibm.wala.core.util.strings.Atom; import com.ibm.wala.dalvik.ipa.callgraph.impl.AndroidEntryPoint; import com.ibm.wala.ipa.callgraph.AnalysisOptions; import com.ibm.wala.ipa.callgraph.IAnalysisCacheView; import com.ibm.wala.ipa.cha.IClassHierarchy; import com.ibm.wala.ipa.summaries.SummarizedMethod; import com.ibm.wala.util.CancelException; /** * Model for single Target Class. * * <p>Is used by the IntentContextInterpreter if a Intent can be resolved internally. * * @author Tobias Blaschke &lt;code@tobiasblaschke.de&gt; * @since 2013-10-12 */ public class MicroModel extends AndroidModel { public final Atom name; public final Atom target; // private SummarizedMethod activityModel; /** * Restrict the model to Activities. * * <p>{@inheritDoc} */ @Override protected boolean selectEntryPoint(AndroidEntryPoint ep) { return ep.isMemberOf(this.target); } public MicroModel( final IClassHierarchy cha, final AnalysisOptions options, final IAnalysisCacheView cache, Atom target) { super(cha, options, cache); this.target = target; this.name = Atom.concat( Atom.findOrCreateAsciiAtom("start"), target.right(target.rIndex((byte) '/') - 1)); } private void register(SummarizedMethod model) { AndroidModelClass mClass = AndroidModelClass.getInstance(cha); if (!mClass.containsMethod(model.getSelector())) { mClass.addMethod(model); } } @Override public Atom getName() { return this.name; } @Override public SummarizedMethod getMethod() throws CancelException { /*AndroidModelClass mClass = AndroidModelClass.getInstance(cha); if (mClass.containsMethod(null)) { Selector sel = new Selector(this.name return mClass.getMethod(); }*/ if (!built) { super.build(this.name); this.register(super.model); } return super.model; } }
3,868
33.544643
94
java
WALA
WALA-master/dalvik/src/main/java/com/ibm/wala/dalvik/ipa/callgraph/androidModel/MiniModel.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.androidModel; import com.ibm.wala.core.util.strings.Atom; import com.ibm.wala.dalvik.ipa.callgraph.impl.AndroidEntryPoint; import com.ibm.wala.dalvik.util.AndroidComponent; import com.ibm.wala.ipa.callgraph.AnalysisOptions; import com.ibm.wala.ipa.callgraph.IAnalysisCacheView; import com.ibm.wala.ipa.cha.IClassHierarchy; import com.ibm.wala.ipa.summaries.SummarizedMethod; import com.ibm.wala.types.Descriptor; import com.ibm.wala.util.CancelException; /** * Models all classes derived from the given AndroidComponent. * * <p>So for example it contains all EntryPoints from all Activities. * * <p>It is like a "regular" AndroidModel but the calls are restricted to EntryPoints whose * target-class is of the type of the given AndroidComponent. * * <p>In the ClassHierarchy a MiniModel will be known as "AndroidModelClass.???Model" (where ??? is * the AndroidComponent) and be called by "AndroidModelClass.startUnknown???" (which is generated by * the UnknownTargetModel). * * <p>A MiniModel is used when a startComponent-call (startActivity, bindService, ...) is * encountered, but the Context at the call site is insufficient to determine the actual target. In * this case an UnknownTargetModel which uses an MiniModel and an ExternalModel is placed there. * * @author Tobias Blaschke &lt;code@tobiasblaschke.de&gt; * @since 2013-10-29 */ public class MiniModel extends AndroidModel { private final Atom name; private final AndroidComponent forCompo; /** * Restrict the model to Activities. * * <p>{@inheritDoc} */ @Override protected boolean selectEntryPoint(AndroidEntryPoint ep) { if (ep.belongsTo(forCompo)) { return true; } return false; } @Override public Descriptor getDescriptor() throws CancelException { final Descriptor descr = super.getDescriptor(); return descr; } public MiniModel( final IClassHierarchy cha, final AnalysisOptions options, final IAnalysisCacheView cache, final AndroidComponent forCompo) { super(cha, options, cache); this.forCompo = forCompo; this.name = Atom.findOrCreateAsciiAtom(forCompo.getPrettyName() + "Model"); // this.activityModel = getMethod(); } @Override public Atom getName() { return this.name; } @Override public SummarizedMethod getMethod() throws CancelException { if (!built) { super.build(this.name); this.register(super.model); } return super.model; } private void register(SummarizedMethod model) { AndroidModelClass mClass = AndroidModelClass.getInstance(cha); if (!mClass.containsMethod(model.getSelector())) { mClass.addMethod(super.model); } } @Override public String toString() { return "<" + this.getClass() + " name=" + this.name + " for=" + forCompo + " />"; } }
4,759
33.744526
100
java
WALA
WALA-master/dalvik/src/main/java/com/ibm/wala/dalvik/ipa/callgraph/androidModel/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. */ /** * Inserts synthetic code that resembles Androids lifecycle. * * <p>It generates a new synthetic class (AndroidModelClass) containing all methods necessary to do * so. * * <p>To model add a lifecycle-model one has to do the following steps: * * <p>1. Scan for the Entrypoints of the application {@code AndroidEntryPointLocator epl = new * AndroidEntryPointLocator(options); List<AndroidEntryPoint> entrypoints = epl.getEntryPoints(cha); * AndroidEntryPointManager.ENTRIES = entrypoints; } 2. Optionally read in the AndroidManifest.xml * {@code final AndroidManifestXMLReader reader = new AndroidManifestXMLReader(manifestFile); } 3. * Optionally change the order of entrypoints and change the instantiation behaviour 4. Create the * model and use it as the new entrypoint of the analysis {@code IMethod model = new * AndroidModel(cha, p.options, p.scfg.cache).getMethod(); } * * <p>The model generated that way will "start" all components of the App. The various start-calls * occurring in these components will not yet call anything useful. To change this there are two * possibilities * * <p>* Insert a MethodTargetSelector: This works context-insensitive so if a call of * "startActivity" is encountered a new model starting _all_ the Activities is generated. * * <p>TODO: This is about to change! {@code AnalysisOptions options; ActivityMiniModel activities = * new ActivityMiniModel(cha, p.options, p.scfg.cache); options.setSelector(new * DelegatingMethodTargetSelector(activities.overrideAll(), options.getMethodTargetSelector())); } * * <p>* Resolve the calls context-sensitive: In Android all calls to different components use an * Intent. The IntentContextSelector remembers all Intents generated in the course of the analysis * and attaches them to the start-calls as Context. * * <p>The IntentContextInterpreter then replaces the IR of the start-calls to start only the * resolved component (or a placeholder like startExternalACTIVITY) {@code final ContextSelector * contextSelector = new IntentContextSelector(new DefaultContextSelector(options, cha)) final * SSAContextInterpreter contextInterpreter = new FallbackContextInterpreter(new * DelegatingSSAContextInterpreter( new IntentContextInterpreter(cha, options, cache), new * DefaultSSAInterpreter(options, cache))); } * * <p>For the context-sensitive stuff to be able to resolve the targets either the * AndroidManifest.xml should have been read or overrides been placed manually (or both). * * @since 2013-10-25 * @author Tobias Blaschke &lt;code@tobiasblaschke.de&gt; */ package com.ibm.wala.dalvik.ipa.callgraph.androidModel;
4,529
51.674419
100
java
WALA
WALA-master/dalvik/src/main/java/com/ibm/wala/dalvik/ipa/callgraph/androidModel/parameters/AndroidModelParameterManager.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.androidModel.parameters; import com.ibm.wala.core.util.ssa.ParameterAccessor; import com.ibm.wala.core.util.ssa.SSAValue; import com.ibm.wala.ssa.SSAInstruction; import com.ibm.wala.types.MethodReference; import com.ibm.wala.types.TypeReference; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; /** * Manages SSA-Numbers for the arguments to Entrypoints. * * <p>This class comes in handy if you want to use loops or mix a return value of a function into * the parameter of a later function. It supports multiple levels of cascading code blocks and * delivers information which SSA-Value is the latest to use or which aught to be combined using a * Phi-Statement. * * <p>However it does no allocations or Phi-Statements on its own. It just juggles with the numbers. * * @see com.ibm.wala.dalvik.ipa.callgraph.androidModel.structure.AbstractAndroidModel * @author Tobias Blaschke &lt;code@toiasblaschke.de&gt; * @since 2013-09-19 * <p>TODO: * <ul> * <li>Track if a variable has been refered to to be able to prune unused Phi-Instructions * later * <li>Trim Memory consumption? The whole class should not be in * memory for long time so * this might be not neccessary. * </ul> */ public class AndroidModelParameterManager { private enum ValueStatus { /** Value has never been mentioned before */ UNUSED, /** Awaiting to be set using setAllocation */ UNALLOCATED, /** Set and ready to use */ ALLOCATED, /** Has to be assigned using a Phi-Instruction */ FREE, /** Should only be used as argument to a Phi Instruction */ INVALIDATED, /** Should not be referenced any more */ CLOSED, /** Well FREE and INVALIDATED */ FREE_INVALIDATED, /** Well FREE and CLOSED */ FREE_CLOSED } // TODO: nextLocal may be 0 on getUnamanged! /** The next variable not under management yet */ private int nextLocal; /** for managing cascaded code blocks */ private int currentScope = 0; /** For checking if type is CREATE or REUSE (optional) */ private IInstantiationBehavior behaviour = null; /** Description only used for toString() */ private String description; // private MethodReference forMethod; /** Representing a ssa-number - thus a version of an instance to a type. */ private static class ManagedParameter { public ValueStatus status = ValueStatus.UNUSED; public TypeReference type = null; public int ssa = -1; // public SSAInstruction setBy = null; public int setInScope = -1; } /** The main data-structure of the management */ private final Map<TypeReference, List<ManagedParameter>> seenTypes = new HashMap<>(); /** * Setting the behaviour may be handy in the later model. * * <p>However it brings no benefit to the AndroidModelParameterManager. */ public AndroidModelParameterManager(IInstantiationBehavior behaviour) { this.behaviour = behaviour; this.description = " based on behaviours of " + behaviour; // this.forMethod = null; // XXX } public AndroidModelParameterManager(MethodReference mRef, boolean isStatic) { this(new ParameterAccessor(mRef, isStatic)); this.description = " based on MethodReference " + mRef; // this.forMethod = mRef; } public AndroidModelParameterManager(ParameterAccessor acc) { this.behaviour = null; nextLocal = acc.getFirstAfter(); /* for (Parameter param: acc.all()) { setAllocation(param.getType(), param.getNumber()); }*/ this.description = " based on ParameterAccessor " + acc; // this.forMethod = acc.forMethod(); } // public AndroidModelParameterManager() { // this.behaviour = null; // } /* public void readDescriptior(Descriptor forMethod) { for (int i=0; i < forMethod.getParameters().length; ++i) { setAllocation(forMethod.getParameters()[i], i + 1); } }*/ /** * Register a variable _after_ allocation. * * <p>The proper way to add an allocation is to get a Variable using {@link #getUnallocated}. Then * assign it a value. And at last call this function. * * <p>You can however directly call the function if the type has not been seen before. * * @param type The type allocated * @param ssaValue an unallocated SSA-Variable to assign the allocation to * @param setBy The instruction that set the value * @throws IllegalStateException if you set more than one allocation for that type (TODO better * check!) * @throws IllegalArgumentException if type is null or ssaValue is zero or negative */ public void setAllocation(TypeReference type, int ssaValue, SSAInstruction setBy) { if (type == null) { throw new IllegalArgumentException("The argument type may not be null"); } if (ssaValue <= 0) { throw new IllegalArgumentException("The SSA-Variable may not be zero or negative."); } if (seenTypes.containsKey(type)) { for (ManagedParameter param : seenTypes.get(type)) { if (param.status == ValueStatus.UNALLOCATED) { // XXX: Allow more? assert param.type.equals(type) : "Inequal types"; if ((ssaValue + 1) > nextLocal) { nextLocal = ssaValue + 1; } param.status = ValueStatus.ALLOCATED; param.ssa = ssaValue; param.setInScope = currentScope; // param.setBy = setBy; return; } else { continue; } } throw new IllegalStateException( "The parameter " + type.getName() + " has already been allocated!"); } else { ManagedParameter param = new ManagedParameter(); param.status = ValueStatus.ALLOCATED; param.type = type; param.ssa = ssaValue; if ((ssaValue + 1) > nextLocal) { nextLocal = ssaValue + 1; } param.setInScope = currentScope; List<ManagedParameter> aParam = new ArrayList<>(); aParam.add(param); seenTypes.put(type, aParam); return; } } public void setAllocation(TypeReference type, int ssaValue) { setAllocation(type, ssaValue, null); } public void setAllocation(SSAValue val) { setAllocation(val.getType(), val.getNumber(), null); } /** * Register a Phi-Instruction _after_ added to the model. * * @param type the type the Phi-Instruction sets * @param ssaValue the number the SSA-Instruction assignes to * @param setBy the Phi-Instruction itself - may be null * @throws IllegalArgumentException if you assign to a number requested using {@link * #getFree(TypeReference)} but types mismach. * @throws IllegalStateException if you forgot to close some Phis */ public void setPhi(TypeReference type, int ssaValue, SSAInstruction setBy) { if (type == null) { throw new IllegalArgumentException("The argument type may not be null"); } if (ssaValue <= 0) { throw new IllegalArgumentException("The SSA-Variable may not be zero or negative."); } boolean didPhi = false; if (seenTypes.containsKey(type)) { for (ManagedParameter param : seenTypes.get(type)) { if ((param.status == ValueStatus.FREE) || (param.status == ValueStatus.FREE_INVALIDATED) || (param.status == ValueStatus.FREE_CLOSED)) { // XXX: Allow more? assert param.type.equals(type) : "Inequal types"; if (param.ssa != ssaValue) { if ((param.status == ValueStatus.FREE) && (param.setInScope == currentScope)) { param.status = ValueStatus.FREE_CLOSED; } continue; } switch (param.status) { case FREE: param.status = ValueStatus.ALLOCATED; break; case FREE_INVALIDATED: param.status = ValueStatus.INVALIDATED; break; case FREE_CLOSED: param.status = ValueStatus.CLOSED; break; } param.setInScope = currentScope; // param.setBy = setBy; didPhi = true; } else if (param.setInScope == currentScope) { if (param.status == ValueStatus.INVALIDATED) { param.status = ValueStatus.CLOSED; } else if (param.status == ValueStatus.FREE_INVALIDATED) { // TODO: FREE CLOSED param.status = ValueStatus.FREE_CLOSED; } } else if (param.setInScope < currentScope) { // param.status = ValueStatus.INVALIDATED; } else { // TODO: NO! I JUST WANTED TO ADD THEM! *grrr* // logger.error("MISSING PHI for " // throw new IllegalStateException("You forgot Phis in subordinate blocks"); } } assert didPhi; } else { ManagedParameter param = new ManagedParameter(); param.status = ValueStatus.ALLOCATED; param.type = type; param.setInScope = currentScope; param.ssa = ssaValue; if ((ssaValue + 1) > nextLocal) { nextLocal = ssaValue + 1; } List<ManagedParameter> aParam = new ArrayList<>(); aParam.add(param); seenTypes.put(type, aParam); } } /** * Returns and registers a free SSA-Number to a Type. * * <p>You have to set the type using a Phi-Instruction. Also you don't have to add that * instruction immediatly it is required that it is added before the Model gets finished. * * <p>You can request the List of unmet Phi-Instructions by using XXX * * @return an unused SSA-Number * @throws IllegalArgumentException if type is null */ public int getFree(TypeReference type) { if (type == null) { throw new IllegalArgumentException("The argument type may not be null"); } ManagedParameter param = new ManagedParameter(); param.status = ValueStatus.FREE; param.type = type; param.ssa = nextLocal++; param.setInScope = currentScope; if (seenTypes.containsKey(type)) { seenTypes.get(type).add(param); } else { List<ManagedParameter> aParam = new ArrayList<>(); aParam.add(param); seenTypes.put(type, aParam); } return param.ssa; } /** * Get an unused number to assign to. * * <p>There may only be one unallocated value for each type at a time. XXX: Really? * * @return SSA-Variable * @throws IllegalStateException if there is already an unallocated variable of that type * @throws IllegalArgumentException if type is null */ public int getUnallocated(TypeReference type) { if (type == null) { throw new IllegalArgumentException("The argument type may not be null"); } if (seenTypes.containsKey(type)) { for (ManagedParameter p : seenTypes.get(type)) { if (p.status == ValueStatus.UNALLOCATED) { throw new IllegalStateException( "There may be only one unallocated instance to a type (" + type + ") at a time"); } } } ManagedParameter param = new ManagedParameter(); param.status = ValueStatus.UNALLOCATED; param.type = type; param.ssa = nextLocal++; param.setInScope = currentScope; if (seenTypes.containsKey(type)) { seenTypes.get(type).add(param); } else { List<ManagedParameter> aParam = new ArrayList<>(); aParam.add(param); seenTypes.put(type, aParam); } return param.ssa; } /** * Retreive a SSA-Value that is not under management. * * <p>Use instead of 'nextLocal++', else SSA-Values will clash! * * @return SSA-Variable */ public int getUnmanaged() { int ret = nextLocal++; return ret; } /** * Retreive the SSA-Number that is valid for a type in the current scope. * * <p>Either that number origins from an allocation or a PhiInstruction (to be). * * @return a ssa number * @throws IllegalStateException if no number is assignable * @throws IllegalArgumentException if type was not seen before or is null */ public int getCurrent(TypeReference type) { if (type == null) { throw new IllegalArgumentException("The argument type may not be null"); } int candidateSSA = -1; int candidateScope = -1; if (seenTypes.containsKey(type)) { for (ManagedParameter param : seenTypes.get(type)) { if ((param.status == ValueStatus.FREE) || (param.status == ValueStatus.ALLOCATED)) { assert param.type.equals(type) : "Inequal types"; if (param.setInScope > currentScope) { continue; } else if (param.setInScope == currentScope) { return param.ssa; } else { if (param.setInScope > candidateScope) { candidateScope = param.setInScope; candidateSSA = param.ssa; } } } else { } } } else { throw new IllegalArgumentException("Type " + type + " has never been seen before!"); } if (candidateSSA < 0) { return candidateSSA; } else { throw new IllegalStateException("No suitable candidate has been found for " + type.getName()); } } /** * Retreive the SSA-Number that is valid for a type in the super-ordinate scope. * * <p>Either that number origins from an allocation or a PhiInstruction (to be). * * @return a ssa number * @throws IllegalStateException if no number is assignable * @throws IllegalArgumentException if type was not seen before or is null */ public int getSuper(TypeReference type) { if (type == null) { throw new IllegalArgumentException("The argument type may not be null"); } int ssa; currentScope--; assert (currentScope >= 0); ssa = getCurrent(type); currentScope++; return ssa; } /** @throws IllegalArgumentException if type was not seen before or is null */ public List<Integer> getAllForPhi(TypeReference type) { if (type == null) { throw new IllegalArgumentException("The argument type may not be null"); } List<Integer> ret = new ArrayList<>(); if (seenTypes.containsKey(type)) { for (ManagedParameter param : seenTypes.get(type)) { if ((param.status == ValueStatus.FREE) || (param.status == ValueStatus.ALLOCATED)) { assert param.type.equals(type) : "Inequal types"; ret.add(param.ssa); } else if ((param.status == ValueStatus.INVALIDATED) && param.setInScope > currentScope) { ret.add(param.ssa); } } } else { throw new IllegalArgumentException("Type " + type + " has never been seen before!"); } return ret; } /** * Return if the type is managed by this class. * * @param withSuper when true return true if a managed key may be cast to type, when false type * has to match exactly * @param type the type in question * @throws IllegalArgumentException if type is null */ public boolean isSeen(TypeReference type, boolean withSuper) { if (type == null) { throw new IllegalArgumentException("The argument type may not be null"); } if (withSuper) { return seenTypes.containsKey(type); } else { if (seenTypes.containsKey(type)) { if (seenTypes.get(type).get(0).type.equals(type)) { return true; } } return false; } } public boolean isSeen(TypeReference type) { return isSeen(type, true); } /** * Returns if an instance for that type needs to be allocated. * * <p>However this function does not respect weather a PhiInstruction is needed. * * @throws IllegalArgumentException if type is null */ public boolean needsAllocation(TypeReference type) { if (type == null) { throw new IllegalArgumentException("The argument type may not be null"); } if (seenTypes.containsKey(type)) { if (seenTypes.get(type).size() > 1) { // TODO INCORRECT may all be UNALLOCATED return false; } else { return (seenTypes.get(type).get(0).status == ValueStatus.UNALLOCATED); } } else { return true; } } /** * Returns if a PhiInstruction (still) has to be added. * * <p>This is true if the Value has changed in a deeper scope, has been invalidated or requested * using getFree * * @throws IllegalArgumentException if type is null or has not been seen before */ public boolean needsPhi(TypeReference type) { if (type == null) { throw new IllegalArgumentException("The argument type may not be null"); } boolean seenLive = false; if (seenTypes.containsKey(type)) { for (ManagedParameter param : seenTypes.get(type)) { // TODO: Check all these if ((param.status == ValueStatus.FREE)) { // TODO: What about scopes return true; } if (param.status == ValueStatus.ALLOCATED) { if (seenLive) { return true; } else { seenLive = true; } } } } else { throw new IllegalArgumentException("Type " + type + " has never been seen before!"); } throw new IllegalStateException("No suitable candidate has been found"); // TODO WRONG text } /** @throws IllegalArgumentException if type was not seen before or is null */ public void invalidate(TypeReference type) { if (type == null) { throw new IllegalArgumentException("The argument type may not be null"); } if (seenTypes.containsKey(type)) { for (ManagedParameter param : seenTypes.get(type)) { if ((param.status != ValueStatus.CLOSED) && (param.status != ValueStatus.FREE_CLOSED) && (param.status != ValueStatus.FREE_INVALIDATED) && (param.status != ValueStatus.INVALIDATED) && (param.setInScope == currentScope)) { assert param.type.equals(type); if (param.status == ValueStatus.FREE) { param.status = ValueStatus.FREE_INVALIDATED; } else { param.status = ValueStatus.INVALIDATED; } } } } } /** * Enter a subordinate scope. * * <p>Call this whenever a new code block starts i.e. when ever you would have to put a left * curly-bracket in yout java code. * * <p>This function influences the placement of Phi-Functions. Thus if you don't change values you * don't have to call it. * * @param doesLoop set to true if the scope is introduced for a loop * @return The depth */ public int scopeDown(boolean doesLoop) { // TODO: Rename scopeInto // TODO: Delete Parameters if therw already was scopeNo currentScope++; return currentScope; } /** * Leave a subordinate scope. * * <p>All changes are marked invalid thus to be expected to be collected by a PhiInstruction. * * @throws IllegalStateException if already at top level */ public int scopeUp() { // TODO: Rename scopeOut // First: Invalidate changed values for (List<ManagedParameter> plist : seenTypes.values()) { for (ManagedParameter param : plist) { if (param.setInScope == currentScope) { invalidate(param.type); } else if ((param.setInScope > currentScope) && ((param.status != ValueStatus.INVALIDATED) || (param.status != ValueStatus.CLOSED))) { throw new IllegalStateException( "Something went wrong in leaving a sub-subordinate scope"); } } } currentScope--; return currentScope; } /** * Handed through to an IInstantiationBehavior if set in the constructor. * * @return true if Type is a REUSE type * @throws IllegalStateException if AndroidModelParameterManager was constructed without an * IInstanciationBehavior */ public boolean isReuse(TypeReference type) { if (this.behaviour == null) { throw new IllegalStateException( "AndroidModelParameterManager was constructed without an IInstanciationBehavior"); } if (type.isPrimitiveType()) return false; final IInstantiationBehavior.InstanceBehavior beh = this.behaviour.getBehavior(type.getName(), null, null, null); // TODO: More info here! return (beh == IInstantiationBehavior.InstanceBehavior.REUSE); } /** * Shorthand for not({@link #isReuse(TypeReference)}. * * @return true if type is a CREATE-Type * @throws IllegalStateException if AndroidModelParameterManager was constructed without an * IInstanciationBehavior */ public boolean isCreate(TypeReference type) { return !isReuse(type); } @Override public String toString() { return "<AndroidModelParameterManager " + this.description + '>'; } }
22,745
32.061047
100
java
WALA
WALA-master/dalvik/src/main/java/com/ibm/wala/dalvik/ipa/callgraph/androidModel/parameters/DefaultInstantiationBehavior.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.androidModel.parameters; import com.ibm.wala.classLoader.IClass; import com.ibm.wala.classLoader.IClassLoader; import com.ibm.wala.core.util.strings.Atom; import com.ibm.wala.dalvik.util.AndroidTypes; import com.ibm.wala.ipa.cha.IClassHierarchy; import com.ibm.wala.types.MethodReference; import com.ibm.wala.types.TypeName; import com.ibm.wala.types.TypeReference; import java.io.IOException; import java.io.Serializable; import java.util.HashMap; import java.util.Map; /** * Contains some predefined behaviors. * * @author Tobias Blaschke &lt;code@tobiasblaschke.de&gt; * @since 2013-10-25 */ public class DefaultInstantiationBehavior extends IInstantiationBehavior { /* package-private */ static final class BehviourValue implements Serializable { private static final long serialVersionUID = 190943987799306506L; public final InstanceBehavior behaviour; public final Exactness exactness; public final BehviourValue cacheFrom; public BehviourValue( final InstanceBehavior behaviour, final Exactness exactness, final BehviourValue cacheFrom) { this.behaviour = behaviour; this.exactness = exactness; this.cacheFrom = cacheFrom; } /** If the value can be derived using an other mapping. */ public boolean isCached() { return this.cacheFrom != null; } } /* package-private */ static final class BehaviorKey<T> implements Serializable { private static final long serialVersionUID = -1932639921432060660L; // T is expected to be TypeName or Atom final T base; public BehaviorKey(T base) { this.base = base; } public static BehaviorKey<TypeName> mk(TypeName base) { return new BehaviorKey<>(base); } public static BehaviorKey<Atom> mk(Atom base) { return new BehaviorKey<>(base); } public static BehaviorKey<Atom> mkPackage(String pack) { return new BehaviorKey<>(Atom.findOrCreateAsciiAtom(pack)); } @Override public boolean equals(Object o) { if (o instanceof BehaviorKey) { BehaviorKey<?> other = (BehaviorKey<?>) o; return base.equals(other.base); } else { return false; } } @Override public int hashCode() { return this.base.hashCode(); } @Override public String toString() { return "<BehaviorKey of " + base.toString() + '>'; } } private final Map<BehaviorKey<?>, BehviourValue> behaviours = new HashMap<>(); private final transient IClassHierarchy cha; public DefaultInstantiationBehavior(final IClassHierarchy cha) { this.cha = cha; behaviours.put( BehaviorKey.mkPackage("Ljava/lang"), new BehviourValue(InstanceBehavior.CREATE, Exactness.EXACT, null)); behaviours.put( BehaviorKey.mk(TypeName.string2TypeName("Ljava/lang/Object")), new BehviourValue( // TypeReference.JavaLangObjectName is private InstanceBehavior.CREATE, Exactness.EXACT, null)); behaviours.put( BehaviorKey.mk(TypeReference.findOrCreateArrayOf(TypeReference.JavaLangObject).getName()), new BehviourValue(InstanceBehavior.CREATE, Exactness.EXACT, null)); behaviours.put( BehaviorKey.mk(AndroidTypes.BundleName), new BehviourValue(InstanceBehavior.REUSE, Exactness.EXACT, null)); behaviours.put( BehaviorKey.mk(AndroidTypes.ActivityName), new BehviourValue(InstanceBehavior.REUSE, Exactness.EXACT, null)); behaviours.put( BehaviorKey.mk(AndroidTypes.ServiceName), new BehviourValue(InstanceBehavior.REUSE, Exactness.EXACT, null)); behaviours.put( BehaviorKey.mk(AndroidTypes.BroadcastReceiverName), new BehviourValue(InstanceBehavior.REUSE, Exactness.EXACT, null)); behaviours.put( BehaviorKey.mk(AndroidTypes.ContentProviderName), new BehviourValue(InstanceBehavior.REUSE, Exactness.EXACT, null)); // Walas method to create instances has problems with the menu-stuff behaviours.put( BehaviorKey.mk(AndroidTypes.MenuName), new BehviourValue(InstanceBehavior.CREATE, Exactness.EXACT, null)); behaviours.put( BehaviorKey.mk(AndroidTypes.ContextMenuName), new BehviourValue(InstanceBehavior.CREATE, Exactness.EXACT, null)); behaviours.put( BehaviorKey.mk(AndroidTypes.MenuItemName), new BehviourValue(InstanceBehavior.CREATE, Exactness.EXACT, null)); // Wala can't handle: behaviours.put( BehaviorKey.mk(AndroidTypes.ActionModeName), new BehviourValue(InstanceBehavior.CREATE, Exactness.EXACT, null)); behaviours.put( BehaviorKey.mk(AndroidTypes.AttributeSetName), new BehviourValue(InstanceBehavior.CREATE, Exactness.EXACT, null)); behaviours.put( BehaviorKey.mk(AndroidTypes.ActionModeCallbackName), new BehviourValue(InstanceBehavior.CREATE, Exactness.EXACT, null)); behaviours.put( BehaviorKey.mk(AndroidTypes.KeyEventName), new BehviourValue(InstanceBehavior.CREATE, Exactness.EXACT, null)); behaviours.put( BehaviorKey.mkPackage("Landroid/support/v4/view"), new BehviourValue(InstanceBehavior.REUSE, Exactness.EXACT, null)); /* behaviours.put(Atom.findOrCreateAsciiAtom("Landroid/database"), IInstanciationBehavior.InstanceBehavior.REUSE); behaviours.put(Atom.findOrCreateAsciiAtom("Landroid/support/v4/app/FragmentActivity"), IInstanciationBehavior.InstanceBehavior.REUSE); */ } /** * @param asParameterTo not considered * @param inCall not considered * @param withName not considered */ @Override public InstanceBehavior getBehavior( final TypeName type, final TypeName asParameterTo, final MethodReference inCall, final String withName) { if (type == null) { throw new IllegalArgumentException("type may not be null"); } final BehaviorKey<TypeName> typeK = BehaviorKey.mk(type); if (behaviours.containsKey(typeK)) { BehviourValue typeV = behaviours.get(typeK); while (typeV.cacheFrom != null) { typeV = typeV.cacheFrom; } return typeV.behaviour; } // Search based on package { final Atom pack = type.getPackage(); if (pack != null) { final BehaviorKey<Atom> packK = BehaviorKey.mk(pack); if (behaviours.containsKey(packK)) { // Add (cache) the result final BehviourValue packV = behaviours.get(packK); final InstanceBehavior beh = packV.behaviour; behaviours.put(typeK, new BehviourValue(beh, Exactness.PACKAGE, packV)); return beh; } } } // Search the super-classes { if (this.cha != null) { IClass testClass = null; for (final IClassLoader loader : this.cha.getLoaders()) { testClass = loader.lookupClass(type); if (testClass != null) { testClass = testClass.getSuperclass(); break; } } while (testClass != null) { final BehaviorKey<TypeName> testKey = BehaviorKey.mk(testClass.getName()); if (behaviours.containsKey(testKey)) { // Add (cahce) the result final BehviourValue value = behaviours.get(testKey); final InstanceBehavior beh = value.behaviour; behaviours.put(typeK, new BehviourValue(beh, Exactness.INHERITED, value)); return beh; } testClass = testClass.getSuperclass(); } } else { } } // */ // Search based on prefix { String prefix = type.toString(); while (prefix.contains("/")) { prefix = prefix.substring(0, prefix.lastIndexOf('/') - 1); final BehaviorKey<Atom> prefixKey = BehaviorKey.mk(Atom.findOrCreateAsciiAtom(prefix)); if (behaviours.containsKey(prefixKey)) { // cache final BehviourValue value = behaviours.get(prefixKey); final InstanceBehavior beh = value.behaviour; behaviours.put(typeK, new BehviourValue(beh, Exactness.PREFIX, value)); return beh; } } } // */ // Fall back to default { final InstanceBehavior beh = getDafultBehavior(); final BehviourValue packV = new BehviourValue(beh, Exactness.DEFAULT, null); behaviours.put(typeK, packV); return beh; } } /** * {@inheritDoc} * * <p>The DefaultInstanciationBehavior only knows EXACT, PACKAGE, PREFIX and DEFAULT */ @Override public Exactness getExactness( final TypeName type, final TypeName asParameterTo, final MethodReference inCall, final String withName) { if (type == null) { throw new IllegalArgumentException("type may not be null"); } final BehaviorKey<TypeName> typeK = BehaviorKey.mk(type); if (!behaviours.containsKey(typeK)) { // Use sideeffect: caches. getBehavior(type, asParameterTo, inCall, withName); } return behaviours.get(typeK).exactness; } /** @return InstanceBehavior.REUSE */ @Override public InstanceBehavior getDafultBehavior() { return InstanceBehavior.REUSE; } /** Convert a TypeName back to an Atom. */ protected static Atom type2atom(TypeName type) { return Atom.findOrCreateAsciiAtom(type.toString()); } // // (De-)Serialization stuff follows // /** The last eight digits encode the date. */ private static final long serialVersionUID = 89220020131212L; /** Including the cache may be useful to get all seen types. */ public transient boolean serializationIncludesCache = true; private void writeObject(java.io.ObjectOutputStream stream) throws IOException { if (this.serializationIncludesCache) { stream.writeObject(this.behaviours); } else { final Map<BehaviorKey<?>, BehviourValue> strippedBehaviours = new HashMap<>(); for (final Map.Entry<BehaviorKey<?>, BehviourValue> entry : this.behaviours.entrySet()) { final BehviourValue val = entry.getValue(); if (!val.isCached()) { strippedBehaviours.put(entry.getKey(), val); } } stream.writeObject(strippedBehaviours); } } /** * For no apparent reason not intended to be deserialized. * * <p>During the implementation I thought of the DefaultInstantiationBehavior to be immutable so * hard-coded behaviors don't get mixed with loaded ones. It may be deserialized but using a * LoadedInstantiationBehavior instead may be a better way (as it starts in an empty state) */ @SuppressWarnings("unchecked") private void readObject(java.io.ObjectInputStream stream) throws IOException, ClassNotFoundException { DefaultInstantiationBehavior.this.behaviours.clear(); this.behaviours.putAll((Map<BehaviorKey<?>, BehviourValue>) stream.readObject()); } }
12,797
34.451524
138
java
WALA
WALA-master/dalvik/src/main/java/com/ibm/wala/dalvik/ipa/callgraph/androidModel/parameters/FlatInstantiator.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.androidModel.parameters; import com.ibm.wala.analysis.typeInference.ConeType; import com.ibm.wala.analysis.typeInference.PrimitiveType; import com.ibm.wala.analysis.typeInference.TypeAbstraction; import com.ibm.wala.classLoader.ArrayClass; import com.ibm.wala.classLoader.CallSiteReference; import com.ibm.wala.classLoader.IClass; import com.ibm.wala.classLoader.IMethod; import com.ibm.wala.classLoader.NewSiteReference; import com.ibm.wala.core.util.ssa.IInstantiator; import com.ibm.wala.core.util.ssa.ParameterAccessor; import com.ibm.wala.core.util.ssa.SSAValue; import com.ibm.wala.core.util.ssa.SSAValue.UniqueKey; import com.ibm.wala.core.util.ssa.SSAValue.VariableKey; import com.ibm.wala.core.util.ssa.SSAValueManager; import com.ibm.wala.core.util.ssa.TypeSafeInstructionFactory; import com.ibm.wala.ipa.callgraph.AnalysisScope; import com.ibm.wala.ipa.cha.IClassHierarchy; import com.ibm.wala.ipa.summaries.VolatileMethodSummary; import com.ibm.wala.shrike.shrikeBT.IInvokeInstruction; import com.ibm.wala.ssa.ConstantValue; import com.ibm.wala.ssa.SSAInstruction; import com.ibm.wala.ssa.SSANewInstruction; import com.ibm.wala.types.MethodReference; import com.ibm.wala.types.TypeReference; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Set; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Add code to create an instance of a type in a synthetic method. * * <p>This variant limits recursion depth. * * @author Tobias Blaschke &lt;code@tobiasblaschke.de&gt; */ public class FlatInstantiator implements IInstantiator { private static final Logger logger = LoggerFactory.getLogger(FlatInstantiator.class); final IClassHierarchy cha; final VolatileMethodSummary body; final TypeSafeInstructionFactory instructionFactory; final SSAValueManager pm; final MethodReference scope; final AnalysisScope analysisScope; final int maxDepth; public FlatInstantiator( final VolatileMethodSummary body, final TypeSafeInstructionFactory instructionFactory, final SSAValueManager pm, final IClassHierarchy cha, final MethodReference scope, final AnalysisScope analysisScope) { this.body = body; this.instructionFactory = instructionFactory; this.pm = pm; this.cha = cha; this.scope = scope; this.analysisScope = analysisScope; this.maxDepth = 1; } public FlatInstantiator( final VolatileMethodSummary body, final TypeSafeInstructionFactory instructionFactory, final SSAValueManager pm, final IClassHierarchy cha, final MethodReference scope, final AnalysisScope analysisScope, final int maxDepth) { this.body = body; this.instructionFactory = instructionFactory; this.pm = pm; this.cha = cha; this.scope = scope; this.analysisScope = analysisScope; this.maxDepth = maxDepth; } private boolean isExcluded(IClass cls) { if (this.analysisScope.getExclusions() != null && this.analysisScope.getExclusions().contains(cls.getName().toString())) { // XXX FUUUUU logger.info("Hit exclusions with {}", cls); return true; } else { return false; } } /** * Creates a new instance of type calling all that's necessary. * * <p>If T is a class-type all its constructors are searched for the one found best suited (takes * the least arguments, ...). New instances are created for all parameters, then the constructor * is called. * * <p>If T represents multiple types (is an interface, abstract class, ...) _all_ implementors of * that type are instantiated After that they get Phi-ed together. * * <p>If T is an array-type a new array of length 1 is generated. * * <p>TODO: Do we want to mix in REUSE-Parameters? */ public SSAValue createInstance( final TypeReference T, final boolean asManaged, VariableKey key, Set<? extends SSAValue> seen) { return createInstance(T, asManaged, key, seen, 0); } private SSAValue createInstance( final TypeReference T, final boolean asManaged, VariableKey key, Set<? extends SSAValue> seen, int currentDepth) { if (T == null) { throw new IllegalArgumentException("Can't create an instance of null"); } if (seen == null) { logger.debug("Empty seen"); seen = new HashSet<>(); } if (currentDepth > this.maxDepth) { final SSAValue instance = this.pm.getUnmanaged(T, key); instance.setAssigned(); return instance; } { // Special type? final SpecializedInstantiator sInst = new SpecializedInstantiator( body, instructionFactory, pm, cha, scope, analysisScope, this); if (SpecializedInstantiator.understands(T)) { return sInst.createInstance(T, asManaged, key, seen, currentDepth); } } final IClass klass = this.cha.lookupClass(T); final SSAValue instance; { // fetch new value if (asManaged) { if (key == null) { throw new IllegalArgumentException("A managed variable needs a key - null given."); } if ((klass != null) && (klass.isAbstract() || klass.isInterface())) { // We'll need a phi instance = this.pm.getFree(T, key); } else { instance = this.pm.getUnallocated(T, key); } } else { if (key == null) { key = new UniqueKey(); } instance = this.pm.getUnmanaged(T, key); } } if (T.isPrimitiveType()) { createPrimitive(instance); return instance; } else if (klass == null) { if (!T.getName().toString().startsWith("Landroid/")) { logger.error("The Type {} is not in the ClassHierarchy! Returning null as instance", T); } else { logger.debug("The Type {} is not in the ClassHierarchy! Returning null as instance", T); } this.body.addConstant(instance.getNumber(), new ConstantValue(null)); instance.setAssigned(); return instance; } else if (isExcluded(klass)) { this.body.addConstant( instance.getNumber(), new ConstantValue(null)); // TODO: null or nothing? instance.setAssigned(); return instance; } final Set<TypeReference> types = getTypes(T); logger.info("Creating instance of {} is {}", T, types); if (types.isEmpty()) { throw new IllegalStateException("Types of " + T + " are empty"); } if ((types.size() == 1) && !klass.isAbstract() && !klass.isArrayClass() && !klass.isInterface()) { // It's a "regular" class final SSANewInstruction newInst = addNew(instance); selectAndCallCtor(instance, seen, currentDepth); if (asManaged) { this.pm.setAllocation(instance, newInst); } assert (newInst.getDef() == instance.getNumber()); return instance; } else if (klass.isArrayClass()) { logger.info("Creating Array-Class {}", klass); final TypeReference payloadType = T.getArrayElementType(); SSAValue payload = null; { for (final SSAValue see : seen) { if (ParameterAccessor.isAssignable(see.getType(), payloadType, this.cha)) { // Happens on Array of interfaces logger.trace("Reusing {} for array payload {}", see, payload); payload = see; } } if (payload == null) { payload = createInstance(payloadType, false, new UniqueKey(), seen, currentDepth); } } // assert (types.size() == 1); // TODO // Generate an array of length 1 final SSANewInstruction newInst; { final int pc = this.body.getNextProgramCounter(); final NewSiteReference nRef = NewSiteReference.make(pc, instance.getType()); final SSAValue arrayLength = this.pm.getUnmanaged(TypeReference.Int, new UniqueKey()); this.body.addConstant(arrayLength.getNumber(), new ConstantValue(1)); arrayLength.setAssigned(); final ArrayList<SSAValue> params = new ArrayList<>(1); params.add(arrayLength); newInst = this.instructionFactory.NewInstruction(pc, instance, nRef, params); this.body.addStatement(newInst); assert (instance.getNumber() == newInst.getDef()); } // Put a payload into the array { final int pc = this.body.getNextProgramCounter(); final SSAInstruction write = this.instructionFactory.ArrayStoreInstruction(pc, instance, 0, payload); body.addStatement(write); } assert (newInst.getDef() == instance.getNumber()); return instance; } else { // Abstract, Interface or array logger.debug("Not a regular class {}", T); final Set<SSAValue> subInstances = new HashSet<>(); for (final TypeReference type : types) { final IClass subKlass = this.cha.lookupClass(type); if (subKlass.isAbstract() || subKlass.isInterface()) { // All "regular" classes in consideration should already be in types continue; } { // Create instance of subInstance final SSAValue subInstance = pm.getUnmanaged(type, new UniqueKey()); final SSANewInstruction newInst = addNew(subInstance); selectAndCallCtor(subInstance, seen, currentDepth); assert (subInstance.getNumber() == newInst.getDef()) : "Unexpected: number and def differ: " + subInstance.getNumber() + ", " + newInst.getDef(); final Set<SSAValue> newSeen = new HashSet<>(seen); // Narf newSeen.add(subInstance); seen = newSeen; subInstances.add(subInstance); } } TypeAbstraction abstraction = null; { // Build the abstraction for (final TypeReference type : types) { final IClass cls; if (type.isPrimitiveType()) { cls = null; } else { cls = this.cha.lookupClass(type); assert (cls != null); } if (abstraction == null) { // TODO: assert primitive stays primitive if (type.isPrimitiveType()) { // XXX: May this happen here? abstraction = PrimitiveType.getPrimitive(type); } else { abstraction = new ConeType(cls); } } else { if (type.isPrimitiveType()) { abstraction = abstraction.meet(PrimitiveType.getPrimitive(type)); } else { abstraction = abstraction.meet(new ConeType(cls)); } } } // XXX: What to do with the abstraction now? } { // Phi together everything if (subInstances.size() > 0) { final int pc = this.body.getNextProgramCounter(); final SSAInstruction phi = this.instructionFactory.PhiInstruction(pc, instance, subInstances); body.addStatement(phi); if (asManaged) { this.pm.setPhi(instance, phi); } } else { logger.warn("No sub-instances for: {} - setting to null", instance); this.body.addConstant(instance.getNumber(), new ConstantValue(null)); instance.setAssigned(); } } } return instance; } private static void createPrimitive(SSAValue instance) { // XXX; something else? instance.setAssigned(); } /** Add a NewInstruction to the body. */ private SSANewInstruction addNew(SSAValue val) { final int pc = this.body.getNextProgramCounter(); final NewSiteReference nRef = NewSiteReference.make(pc, val.getType()); final SSANewInstruction newInstr = this.instructionFactory.NewInstruction(pc, val, nRef); this.body.addStatement(newInstr); assert (val.getNumber() == newInstr.getDef()); return newInstr; } // /** // * Add a call to a single clinit to the body. // * // * @param val the "this" to call clinit on // * @param inClass the class to call its clinit of // */ /*private void addCallCLinit(SSAValue val, TypeReference inClass) { final int pc = this.body.getNextProgramCounter(); final MethodReference mRef = MethodReference.findOrCreate(inClass, MethodReference.clinitSelector); final SSAValue exception = pm.getException(); final CallSiteReference site = CallSiteReference.make(pc, mRef, IInvokeInstruction.Dispatch.STATIC); final List<SSAValue> params = new ArrayList<SSAValue>(1); params.add(val); final SSAInstruction ctorCall = instructionFactory.InvokeInstruction(pc, params, exception, site); body.addStatement(ctorCall); } */ /** * Add a call to the given constructor to the body. * * @param self the "this" to call the constructor on * @param ctor the constructor to call * @param ctorParams parameters to the ctor _without_ implicit this */ protected void addCallCtor(SSAValue self, MethodReference ctor, List<SSAValue> ctorParams) { final int pc = this.body.getNextProgramCounter(); final SSAValue exception = pm.getException(); final CallSiteReference site = CallSiteReference.make(pc, ctor, IInvokeInstruction.Dispatch.SPECIAL); final List<SSAValue> params = new ArrayList<>(1 + ctorParams.size()); params.add(self); params.addAll(ctorParams); final SSAInstruction ctorCall = instructionFactory.InvokeInstruction(pc, params, exception, site); body.addStatement(ctorCall); } private MethodReference selectAndCallCtor( SSAValue val, final Set<? extends SSAValue> overrides, final int currentDepth) { final IMethod cTor = lookupConstructor(val.getType()); final ParameterAccessor ctorAcc = new ParameterAccessor(cTor); assert ctorAcc.hasImplicitThis() : "CTor detected as not having implicit this pointer"; logger.debug("Acc for: {}", this.scope); final ParameterAccessor acc = new ParameterAccessor(this.scope, false); // TODO pm needs a connectThrough too! // TODO false is false // TODO: The overrides may lead to use before definition // if (acc.firstOf(val.getType().getName()) != null) { final SSAValue nullSelf = pm.getUnmanaged(val.getType(), new UniqueKey()); this.body.addConstant(nullSelf.getNumber(), new ConstantValue(null)); nullSelf.setAssigned(); // } final Set<SSAValue> seen = new HashSet<>(1 + overrides.size()); seen.add(nullSelf); seen.addAll(overrides); logger.debug("Recursing for: {}", cTor); logger.debug("With seen: {}", seen); final List<SSAValue> ctorParams = acc.connectThrough( ctorAcc, overrides, /* defaults */ null, this.cha, this, /* managed */ false, /* key */ null, seen, currentDepth + 1); // XXX This starts the recursion! addCallCtor(val, cTor.getReference(), ctorParams); return cTor.getReference(); } /** * Get all sub-types a type represents until concrete ones are reached. * * <p>A concrete type only represents itself. * * @throws IllegalArgumentException if T is a primitive. */ private Set<TypeReference> getTypes(final TypeReference T) { final IClass cls = this.cha.lookupClass(T); if (isExcluded(cls)) { return new HashSet<>(); } return getTypes(T, Collections.<TypeReference>emptySet()); } /** Used internally to avoid endless recursion on getTypes(). */ private Set<TypeReference> getTypes(final TypeReference T, final Set<TypeReference> seen) { logger.debug("getTypes({}, {})", T, seen); final Set<TypeReference> ret = new HashSet<>(); ret.add(T); if (T.isPrimitiveType()) { logger.warn("getTypes called on a primitive"); return ret; // throw new IllegalArgumentException("Not you that call primitive type on :P"); } final IClass cls = this.cha.lookupClass(T); if (cls == null) { logger.error("The type {} is not in the ClassHierarchy - try continuing anyway", T); return ret; // throw new IllegalArgumentException("The type " + T + " is not in the ClassHierarchy"); } else if (isExcluded(cls)) { return ret; } else if (seen.contains(T)) { return ret; } if (cls.isInterface()) { final Set<IClass> impls = cha.getImplementors(T); if (impls.isEmpty()) { // throw new IllegalStateException("The interface " + T + " has no known implementors"); if (!T.getName().toString().startsWith("Landroid/")) { logger.error("The interface {} has no known implementors - skipping over it", T); } else { logger.debug("The interface {} has no known implementors - skipping over it", T); } return ret; // XXX: This is a bad idea? } else { // ADD all for (IClass impl : impls) { if (impl.isAbstract()) { ret.addAll(getTypes(impl.getReference(), ret)); // impl added through recursion } else { ret.add(impl.getReference()); } } } } else if (cls.isAbstract()) { final Collection<IClass> subs = cha.computeSubClasses(T); if (subs.isEmpty()) { throw new IllegalStateException( "The class " + T + " is abstract but has no subclasses known to the ClassHierarchy"); } else { for (final IClass sub : subs) { if (seen.contains(sub.getReference())) { logger.debug("Seen: {}", sub); continue; } if (sub.isAbstract()) { // Recurse on abstract classes ret.addAll(getTypes(sub.getReference(), ret)); // sub added through recursion } else { ret.add(sub.getReference()); } } } } else if (cls.isArrayClass()) { final ArrayClass aCls = (ArrayClass) cls; final int dim = aCls.getDimensionality(); if (aCls.isOfPrimitives()) { ret.add(aCls.getReference()); } else { final IClass inner = aCls.getInnermostElementClass(); if (inner == null) { throw new IllegalStateException("The array " + T + " has no inner class"); } if (inner.isInterface() || inner.isAbstract()) { final Set<TypeReference> innerTypes = getTypes(inner.getReference(), Collections.<TypeReference>emptySet()); for (TypeReference iT : innerTypes) { TypeReference aT = TypeReference.findOrCreateArrayOf(iT); for (int i = 1; i < dim; ++i) { aT = TypeReference.findOrCreateArrayOf(aT); } ret.add(aT); } } else { ret.add(TypeReference.findOrCreateArrayOf(inner.getReference())); } } } return ret; } // /** Path back to Object (including T itself). */ // private List<TypeReference> getAllSuper(final TypeReference T) { // if (T.isPrimitiveType()) { // throw new IllegalArgumentException("Not you that call primitive type on :P"); // } // final List<TypeReference> ret = new ArrayList<TypeReference>(); // // IClass cls = this.cha.lookupClass(T); // if (cls == null) { // throw new IllegalArgumentException("The type " + T + " is not in the // ClassHierarchy"); // } // // while (cls != null) { // ret.add(cls.getReference()); // cls = cls.getSuperclass(); // } // // return ret; // } // /** The Constructor starts with 'this()' or 'super()'. */ /*private boolean callsCtor(MethodReference ctor) { if (ctor == null) { throw new IllegalArgumentException("Null ctor"); } final Set<IMethod> methods = cha.getPossibleTargets(ctor); if (methods == null) { throw new IllegalArgumentException("Unable to look up IMethod for ctor " + ctor); } if (methods.size() != 1) { throw new UnsupportedOperationException("Unexpected multiple candidates for ctor " + ctor + " are " + methods); } final IMethod method = methods.iterator().next(); assert (method.isInit()); final SSAInstruction firstInstruction = this.cache.getIR(method).iterateAllInstructions().next(); logger.debug("First instruction of ctor is: " + firstInstruction); if (firstInstruction instanceof SSAAbstractInvokeInstruction) { final SSAAbstractInvokeInstruction invokation = (SSAAbstractInvokeInstruction) firstInstruction; return invokation.isSpecial(); // Always? } return false; }*/ /** Selects the constructor of T found to be bes suited. */ private IMethod lookupConstructor(TypeReference T) { IMethod ctor = null; int score = -10000; final IClass klass = cha.lookupClass(T); if (klass == null) { throw new IllegalArgumentException("Unable to look up the class for " + T); } if (klass.isInterface() || klass.isAbstract()) { throw new IllegalArgumentException("Class is interface or abstract"); } for (final IMethod im : klass.getDeclaredMethods()) { if (!im.isInit()) continue; int candidScore = 0; final int paramCount = im.getNumberOfParameters(); if (im.isPrivate()) { score -= 10; } else if (im.isProtected()) { score -= 1; } for (int i = 1; i < paramCount; ++i) { final TypeReference paramType = im.getParameterType(i); if (paramType.isPrimitiveType()) { candidScore -= 1; } else if (paramType.isArrayType()) { // TODO: Reevaluate scores candidScore -= 30; if (paramType.getInnermostElementType().equals(T)) { // Array of itself candidScore -= 1000; } } else if (paramType.isClassType()) { candidScore -= 101; } else if (paramType.isReferenceType()) { // TODO: Avoid interfaces if (paramType.equals(T)) { candidScore -= 1000; } else { candidScore -= 7; } if (paramType.equals(TypeReference.JavaLangObject)) { candidScore -= 1500; } } else { // ?! candidScore -= 800; } } if (candidScore > score) { ctor = im; score = candidScore; } logger.debug("CTor {} got score {}", im, candidScore); } if (ctor == null) { logger.warn("Still found no CTor for {}", T); return cha.resolveMethod(klass, MethodReference.initSelector); } else { return ctor; } } /** Satisfy the interface. */ @Override @SuppressWarnings("unchecked") public int createInstance(TypeReference type, Object... instantiatorArgs) { // public SSAValue createInstance(final TypeReference T, final boolean asManaged, VariableKey // key, Set<SSAValue> seen) { if (!(instantiatorArgs[0] instanceof Boolean)) { throw new IllegalArgumentException("Argument 0 to createInstance has to be boolean."); } if (!((instantiatorArgs[1] == null) || (instantiatorArgs[1] instanceof VariableKey))) { throw new IllegalArgumentException( "Argument 1 to createInstance has to be null or an instance of VariableKey"); } if (!((instantiatorArgs[2] == null) || (instantiatorArgs[2] instanceof Set))) { throw new IllegalArgumentException( "Argument 2 to createInstance has to be null or an instance of Set<? extends SSAValue>, " + "got: " + instantiatorArgs[2].getClass()); } final int currentDepth; { if (instantiatorArgs.length == 4) { currentDepth = (Integer) instantiatorArgs[3]; } else { currentDepth = 0; } } if (instantiatorArgs[2] != null) { final Set<?> seen = (Set<?>) instantiatorArgs[2]; if (!seen.isEmpty()) { final Object o = seen.iterator().next(); if (!(o instanceof SSAValue)) { throw new IllegalArgumentException( "Argument 2 to createInstance has to be null or an instance of Set<? extends SSAValue>, " + "got Set<" + o.getClass() + '>'); } } } return createInstance( type, (Boolean) instantiatorArgs[0], (VariableKey) instantiatorArgs[1], (Set<? extends SSAValue>) instantiatorArgs[2], currentDepth) .getNumber(); } }
26,605
34.954054
121
java
WALA
WALA-master/dalvik/src/main/java/com/ibm/wala/dalvik/ipa/callgraph/androidModel/parameters/IInstantiationBehavior.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.androidModel.parameters; import com.ibm.wala.classLoader.IMethod; import com.ibm.wala.types.MethodReference; import com.ibm.wala.types.TypeName; import java.io.Serializable; /** @author Tobias Blaschke &lt;code@tobiasblaschke.de&gt; */ public abstract class IInstantiationBehavior implements Serializable { private static final long serialVersionUID = -3698760758700891479L; /** The handling for a variable occurring in the AndroidModel. */ public enum InstanceBehavior { /** Create a new instance on each occurrence. */ CREATE, /** Use a single instance throughout the model (uses Phi-in). */ REUSE, // CREUSE; } /** * Information on how the IInstanciationBehavior made its decision for {@link InstanceBehavior} */ public enum Exactness { /** The decision was made based on a exact known mapping from the given data. */ EXACT, /** No direct mapping was found for the type, the one returned is from a superclass. */ INHERITED, /** The value is based on the package of the variable. */ PACKAGE, PREFIX, /** No mapping was found, the default-value was used as a fall-back. */ DEFAULT; } /** * Returns how the model should behave on the type. * * <p>See the documentation of {@link InstanceBehavior} for the description of the possible * behaviours. * * <p>Although this function takes a parameter withName one should not rely on its value. * * @param type The type of the variable in question * @param asParameterTo The component whose function the variable shall be used as parameter to. * @param inCall The call in question * @param withName The name of the parameter in inCall (this might not work) * @return The behaviour to use */ public abstract InstanceBehavior getBehavior( TypeName type, TypeName asParameterTo, MethodReference inCall, String withName); /** * Returns how the model should behave on the type. * * @param param The parameter in question of being reuse * @param inCallTo The callee to query the REUSEness for */ public InstanceBehavior getBehavior( final TypeName param, final IMethod inCallTo, final String withName) { final TypeName asParameterTo; final MethodReference inCall; if ((inCallTo != null)) { // XXX: && (inCallTo != ALL_TARGETS)) { asParameterTo = inCallTo.getDeclaringClass().getName(); inCall = inCallTo.getReference(); /*{ // DEBUG System.out.println("isReuse: "); System.out.println("\tparam = \t\t" + param); System.out.println("\tasParameterTo =\t" + asParameterTo); System.out.println("\tinCall =\t" + inCall); System.out.println("\twithName =\t" + withName); } // */ } else { asParameterTo = null; inCall = null; } return getBehavior(param, asParameterTo, inCall, withName); } /** * The Exactness depends on how the behavior to a type was determined. * * <p>Currently it has no effect on the model but it may come in handy if you want to cascade * classes for determining the IInstanciationBehavior. */ public abstract Exactness getExactness( TypeName type, TypeName asParameterTo, MethodReference inCall, String withName); public abstract InstanceBehavior getDafultBehavior(); }
5,249
38.473684
98
java
WALA
WALA-master/dalvik/src/main/java/com/ibm/wala/dalvik/ipa/callgraph/androidModel/parameters/Instantiator.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.androidModel.parameters; import com.ibm.wala.analysis.typeInference.ConeType; import com.ibm.wala.analysis.typeInference.PrimitiveType; import com.ibm.wala.analysis.typeInference.TypeAbstraction; import com.ibm.wala.classLoader.ArrayClass; import com.ibm.wala.classLoader.CallSiteReference; import com.ibm.wala.classLoader.IClass; import com.ibm.wala.classLoader.IField; import com.ibm.wala.classLoader.IMethod; import com.ibm.wala.classLoader.NewSiteReference; import com.ibm.wala.core.util.ssa.IInstantiator; import com.ibm.wala.core.util.ssa.ParameterAccessor; import com.ibm.wala.core.util.ssa.SSAValue; import com.ibm.wala.core.util.ssa.SSAValue.UniqueKey; import com.ibm.wala.core.util.ssa.SSAValue.VariableKey; import com.ibm.wala.core.util.ssa.SSAValueManager; import com.ibm.wala.core.util.ssa.TypeSafeInstructionFactory; import com.ibm.wala.core.util.strings.Atom; import com.ibm.wala.dalvik.ipa.callgraph.androidModel.AndroidModelClass; import com.ibm.wala.dalvik.util.AndroidEntryPointManager; import com.ibm.wala.ipa.callgraph.AnalysisScope; import com.ibm.wala.ipa.cha.IClassHierarchy; import com.ibm.wala.ipa.summaries.VolatileMethodSummary; import com.ibm.wala.shrike.shrikeBT.IInvokeInstruction; import com.ibm.wala.ssa.ConstantValue; import com.ibm.wala.ssa.SSAInstruction; import com.ibm.wala.ssa.SSANewInstruction; import com.ibm.wala.types.MethodReference; import com.ibm.wala.types.TypeReference; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Set; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Add code to create an instance of a type in a synthetic method. * * <p>Creates an instance of (hopefully) anything. * * @author Tobias Blaschke &lt;code@tobiasblaschke.de&gt; */ public class Instantiator implements IInstantiator { private static final Logger logger = LoggerFactory.getLogger(Instantiator.class); final IClassHierarchy cha; final VolatileMethodSummary body; final TypeSafeInstructionFactory instructionFactory; final SSAValueManager pm; final MethodReference scope; final AnalysisScope analysisScope; public Instantiator( final VolatileMethodSummary body, final TypeSafeInstructionFactory instructionFactory, final SSAValueManager pm, final IClassHierarchy cha, final MethodReference scope, final AnalysisScope analysisScope) { this.body = body; this.instructionFactory = instructionFactory; this.pm = pm; this.cha = cha; this.scope = scope; this.analysisScope = analysisScope; } private boolean isExcluded(IClass cls) { if (this.analysisScope.getExclusions() != null && this.analysisScope.getExclusions().contains(cls.getName().toString())) { // XXX FUUUUU logger.info("Hit exclusions with {}", cls); return true; } else { return false; } } /** * Creates a new instance of type calling all that's necessary. * * <p>If T is a class-type all its constructors are searched for the one found best suited (takes * the least arguments, ...). New instances are created for all parameters, then the constructor * is called. * * <p>If T represents multiple types (is an interface, abstract class, ...) _all_ implementors of * that type are instantiated After that they get Phi-ed together. * * <p>If T is an array-type a new array of length 1 is generated. * * <p>TODO: Do we want to mix in REUSE-Parameters? */ public SSAValue createInstance( final TypeReference T, final boolean asManaged, VariableKey key, Set<? extends SSAValue> seen) { if (T == null) { throw new IllegalArgumentException("Can't create an instance of null"); } if (seen == null) { logger.debug("Empty seen"); seen = new HashSet<>(); } { // Special type? if (SpecializedInstantiator.understands(T)) { final SpecializedInstantiator sInst = new SpecializedInstantiator( body, instructionFactory, pm, cha, scope, analysisScope, this); return sInst.createInstance(T, asManaged, key, seen); } } final IClass klass = this.cha.lookupClass(T); final SSAValue instance; { // fetch new value if (asManaged) { if (key == null) { throw new IllegalArgumentException("A managed variable needs a key - null given."); } if ((klass != null) && (klass.isAbstract() || klass.isInterface())) { // We'll need a phi instance = this.pm.getFree(T, key); } else { instance = this.pm.getUnallocated(T, key); } } else { if (key == null) { key = new UniqueKey(); } instance = this.pm.getUnmanaged(T, key); } } { // Try fetch Android-Components from AndroidModelClass if (com.ibm.wala.dalvik.util.AndroidComponent.isAndroidComponent(T, cha)) { if (AndroidEntryPointManager.MANAGER.doFlatComponents()) { final AndroidModelClass mClass = AndroidModelClass.getInstance(cha); final Atom fdName = T.getName().getClassName(); if (mClass.getField(fdName) != null) { final IField field = mClass.getField(fdName); final int instPC = this.body.getNextProgramCounter(); final SSAInstruction getInst = instructionFactory.GetInstruction(instPC, instance, field.getReference()); this.body.addStatement(getInst); pm.setAllocation(instance, getInst); return instance; } else { logger.info("NEW Component {} \n\tbreadCrumb: {}", instance, pm.breadCrumb); } } else { logger.info("NEW Component {} \n\tbreadCrumb: {}", instance, pm.breadCrumb); } } } // */ if (T.isPrimitiveType()) { createPrimitive(instance); return instance; } else if (klass == null) { if (!T.getName().toString().startsWith("Landroid/")) { logger.error("The Type {} is not in the ClassHierarchy! Returning null as instance", T); } else { logger.debug("The Type {} is not in the ClassHierarchy! Returning null as instance", T); } this.body.addConstant(instance.getNumber(), new ConstantValue(null)); instance.setAssigned(); return instance; } else if (isExcluded(klass)) { this.body.addConstant( instance.getNumber(), new ConstantValue(null)); // TODO: null or nothing? instance.setAssigned(); return instance; } final Set<TypeReference> types = getTypes(T); logger.info("Creating instance of {} is {}", T, types); if (types.isEmpty()) { throw new IllegalStateException("Types of " + T + " are empty"); } if ((types.size() == 1) && !klass.isAbstract() && !klass.isArrayClass() && !klass.isInterface()) { // It's a "regular" class final SSANewInstruction newInst = addNew(instance); selectAndCallCtor(instance, seen); if (asManaged) { this.pm.setAllocation(instance, newInst); } assert (newInst.getDef() == instance.getNumber()); return instance; } else if (klass.isArrayClass()) { logger.info("Creating Array-Class {}", klass); final TypeReference payloadType = T.getArrayElementType(); SSAValue payload = null; { for (final SSAValue see : seen) { if (ParameterAccessor.isAssignable(see.getType(), payloadType, this.cha)) { // Happens on Array of interfaces logger.trace("Reusing {} for array payload {}", see, payload); payload = see; } } if (payload == null) { payload = createInstance(payloadType, false, new UniqueKey(), seen); } } // assert (types.size() == 1); // TODO // Generate an array of length 1 final SSANewInstruction newInst; { final int pc = this.body.getNextProgramCounter(); final NewSiteReference nRef = NewSiteReference.make(pc, instance.getType()); final SSAValue arrayLength = this.pm.getUnmanaged(TypeReference.Int, new UniqueKey()); this.body.addConstant(arrayLength.getNumber(), new ConstantValue(1)); arrayLength.setAssigned(); final ArrayList<SSAValue> params = new ArrayList<>(1); params.add(arrayLength); newInst = this.instructionFactory.NewInstruction(pc, instance, nRef, params); this.body.addStatement(newInst); assert (instance.getNumber() == newInst.getDef()); } // Put a payload into the array { final int pc = this.body.getNextProgramCounter(); final SSAInstruction write = this.instructionFactory.ArrayStoreInstruction(pc, instance, 0, payload); body.addStatement(write); } assert (newInst.getDef() == instance.getNumber()); return instance; } else { // Abstract, Interface or array logger.debug("Not a regular class {}", T); final Set<SSAValue> subInstances = new HashSet<>(); for (final TypeReference type : types) { final IClass subKlass = this.cha.lookupClass(type); if (subKlass.isAbstract() || subKlass.isInterface()) { // All "regular" classes in consideration should already be in types continue; } { // Create instance of subInstance final SSAValue subInstance = pm.getUnmanaged(type, new UniqueKey()); final SSANewInstruction newInst = addNew(subInstance); selectAndCallCtor(subInstance, seen); assert (subInstance.getNumber() == newInst.getDef()) : "Unexpected: number and def differ: " + subInstance.getNumber() + ", " + newInst.getDef(); final Set<SSAValue> newSeen = new HashSet<>(seen); // Narf newSeen.add(subInstance); seen = newSeen; subInstances.add(subInstance); } } TypeAbstraction abstraction = null; { // Build the abstraction for (final TypeReference type : types) { final IClass cls; if (type.isPrimitiveType()) { cls = null; } else { cls = this.cha.lookupClass(type); assert (cls != null); } if (abstraction == null) { // TODO: assert primitive stays primitive if (type.isPrimitiveType()) { // XXX: May this happen here? abstraction = PrimitiveType.getPrimitive(type); } else { abstraction = new ConeType(cls); } } else { if (type.isPrimitiveType()) { abstraction = abstraction.meet(PrimitiveType.getPrimitive(type)); } else { abstraction = abstraction.meet(new ConeType(cls)); } } } // XXX: What to do with the abstraction now? } { // Phi together everything if (subInstances.size() > 0) { final int pc = this.body.getNextProgramCounter(); final SSAInstruction phi = this.instructionFactory.PhiInstruction(pc, instance, subInstances); body.addStatement(phi); if (asManaged) { this.pm.setPhi(instance, phi); } } else { logger.warn("No sub-instances for: {} - setting to null", instance); this.body.addConstant(instance.getNumber(), new ConstantValue(null)); instance.setAssigned(); } } } return instance; } private static void createPrimitive(SSAValue instance) { // XXX; something else? instance.setAssigned(); } /** Add a NewInstruction to the body. */ private SSANewInstruction addNew(SSAValue val) { final int pc = this.body.getNextProgramCounter(); final NewSiteReference nRef = NewSiteReference.make(pc, val.getType()); final SSANewInstruction newInstr = this.instructionFactory.NewInstruction(pc, val, nRef); this.body.addStatement(newInstr); assert (val.getNumber() == newInstr.getDef()); return newInstr; } // /** // * Add a call to a single clinit to the body. // * // * @param val the "this" to call clinit on // * @param inClass the class to call its clinit of // */ /*private void addCallCLinit(SSAValue val, TypeReference inClass) { final int pc = this.body.getNextProgramCounter(); final MethodReference mRef = MethodReference.findOrCreate(inClass, MethodReference.clinitSelector); final SSAValue exception = pm.getException(); final CallSiteReference site = CallSiteReference.make(pc, mRef, IInvokeInstruction.Dispatch.STATIC); final List<SSAValue> params = new ArrayList<SSAValue>(1); params.add(val); final SSAInstruction ctorCall = instructionFactory.InvokeInstruction(pc, params, exception, site); body.addStatement(ctorCall); } */ /** * Add a call to the given constructor to the body. * * @param self the "this" to call the constructor on * @param ctor the constructor to call * @param ctorParams parameters to the ctor _without_ implicit this */ private void addCallCtor(SSAValue self, MethodReference ctor, List<SSAValue> ctorParams) { final int pc = this.body.getNextProgramCounter(); final SSAValue exception = pm.getException(); final CallSiteReference site = CallSiteReference.make(pc, ctor, IInvokeInstruction.Dispatch.SPECIAL); final List<SSAValue> params = new ArrayList<>(1 + ctorParams.size()); params.add(self); params.addAll(ctorParams); final SSAInstruction ctorCall = instructionFactory.InvokeInstruction(pc, params, exception, site); body.addStatement(ctorCall); } private MethodReference selectAndCallCtor(SSAValue val, final Set<? extends SSAValue> overrides) { final IMethod cTor = lookupConstructor(val.getType()); final ParameterAccessor ctorAcc = new ParameterAccessor(cTor); assert ctorAcc.hasImplicitThis() : "CTor detected as not having implicit this pointer"; logger.debug("Acc for: {}", this.scope); final ParameterAccessor acc = new ParameterAccessor(this.scope, false); // TODO pm needs a connectThrough too! // TODO false is false // TODO: The overrides may lead to use before definition // if (acc.firstOf(val.getType().getName()) != null) { final SSAValue nullSelf = pm.getUnmanaged(val.getType(), new UniqueKey()); this.body.addConstant(nullSelf.getNumber(), new ConstantValue(null)); nullSelf.setAssigned(); // } final Set<SSAValue> seen = new HashSet<>(1 + overrides.size()); seen.add(nullSelf); seen.addAll(overrides); logger.debug("Recursing for: {}", cTor); logger.debug("With seen: {}", seen); final List<SSAValue> ctorParams = acc.connectThrough( ctorAcc, overrides, /* defaults */ null, this.cha, this, /* managed */ false, /* key */ null, seen); // XXX This starts the recursion! addCallCtor(val, cTor.getReference(), ctorParams); return cTor.getReference(); } /** * Get all sub-types a type represents until concrete ones are reached. * * <p>A concrete type only represents itself. * * @throws IllegalArgumentException if T is a primitive. */ private Set<TypeReference> getTypes(final TypeReference T) { final IClass cls = this.cha.lookupClass(T); if (isExcluded(cls)) { return new HashSet<>(); } return getTypes(T, Collections.<TypeReference>emptySet()); } /** Used internally to avoid endless recursion on getTypes(). */ private Set<TypeReference> getTypes(final TypeReference T, final Set<TypeReference> seen) { logger.debug("getTypes({}, {})", T, seen); final Set<TypeReference> ret = new HashSet<>(); ret.add(T); if (T.isPrimitiveType()) { logger.warn("getTypes called on a primitive"); return ret; // throw new IllegalArgumentException("Not you that call primitive type on :P"); } final IClass cls = this.cha.lookupClass(T); if (cls == null) { logger.error("The type {} is not in the ClassHierarchy - try continuing anyway", T); return ret; // throw new IllegalArgumentException("The type " + T + " is not in the ClassHierarchy"); } else if (isExcluded(cls)) { return ret; } else if (seen.contains(T)) { return ret; } if (cls.isInterface()) { final Set<IClass> impls = cha.getImplementors(T); if (impls.isEmpty()) { // throw new IllegalStateException("The interface " + T + " has no known implementors"); if (!T.getName().toString().startsWith("Landroid/")) { logger.error("The interface {} has no known implementors - skipping over it", T); } else { logger.debug("The interface {} has no known implementors - skipping over it", T); } return ret; // XXX: This is a bad idea? } else { // ADD all for (IClass impl : impls) { if (impl.isAbstract()) { ret.addAll(getTypes(impl.getReference(), ret)); // impl added through recursion } else { ret.add(impl.getReference()); } } } } else if (cls.isAbstract()) { final Collection<IClass> subs = cha.computeSubClasses(T); if (subs.isEmpty()) { throw new IllegalStateException( "The class " + T + " is abstract but has no subclasses known to the ClassHierarchy"); } else { for (final IClass sub : subs) { if (seen.contains(sub.getReference())) { logger.debug("Seen: {}", sub); continue; } if (sub.isAbstract()) { // Recurse on abstract classes ret.addAll(getTypes(sub.getReference(), ret)); // sub added through recursion } else { ret.add(sub.getReference()); } } } } else if (cls.isArrayClass()) { final ArrayClass aCls = (ArrayClass) cls; final int dim = aCls.getDimensionality(); if (aCls.isOfPrimitives()) { ret.add(aCls.getReference()); } else { final IClass inner = aCls.getInnermostElementClass(); if (inner == null) { throw new IllegalStateException("The array " + T + " has no inner class"); } if (inner.isInterface() || inner.isAbstract()) { final Set<TypeReference> innerTypes = getTypes(inner.getReference(), Collections.<TypeReference>emptySet()); for (TypeReference iT : innerTypes) { TypeReference aT = TypeReference.findOrCreateArrayOf(iT); for (int i = 1; i < dim; ++i) { aT = TypeReference.findOrCreateArrayOf(aT); } ret.add(aT); } } else { ret.add(TypeReference.findOrCreateArrayOf(inner.getReference())); } } } return ret; } /** Path back to Object (including T itself). */ @SuppressWarnings("unused") private List<TypeReference> getAllSuper(final TypeReference T) { if (T.isPrimitiveType()) { throw new IllegalArgumentException("Not you that call primitive type on :P"); } final List<TypeReference> ret = new ArrayList<>(); IClass cls = this.cha.lookupClass(T); if (cls == null) { throw new IllegalArgumentException("The type " + T + " is not in the ClassHierarchy"); } while (cls != null) { ret.add(cls.getReference()); cls = cls.getSuperclass(); } return ret; } // /** The Constructor starts with 'this()' or 'super()'. */ /*private boolean callsCtor(MethodReference ctor) { if (ctor == null) { throw new IllegalArgumentException("Null ctor"); } final Set<IMethod> methods = cha.getPossibleTargets(ctor); if (methods == null) { throw new IllegalArgumentException("Unable to look up IMethod for ctor " + ctor); } if (methods.size() != 1) { throw new UnsupportedOperationException("Unexpected multiple candidates for ctor " + ctor + " are " + methods); } final IMethod method = methods.iterator().next(); assert (method.isInit()); final SSAInstruction firstInstruction = this.cache.getIR(method).iterateAllInstructions().next(); logger.debug("First instruction of ctor is: " + firstInstruction); if (firstInstruction instanceof SSAAbstractInvokeInstruction) { final SSAAbstractInvokeInstruction invokation = (SSAAbstractInvokeInstruction) firstInstruction; return invokation.isSpecial(); // Always? } return false; }*/ /** Selects the constructor of T found to be bes suited. */ private IMethod lookupConstructor(TypeReference T) { IMethod ctor = null; int score = -10000; final IClass klass = cha.lookupClass(T); if (klass == null) { throw new IllegalArgumentException("Unable to look up the class for " + T); } if (klass.isInterface() || klass.isAbstract()) { throw new IllegalArgumentException("Class is interface or abstract"); } for (final IMethod im : klass.getDeclaredMethods()) { if (!im.isInit()) continue; int candidScore = 0; final int paramCount = im.getNumberOfParameters(); if (im.isPrivate()) { score -= 10; } else if (im.isProtected()) { score -= 1; } for (int i = 1; i < paramCount; ++i) { final TypeReference paramType = im.getParameterType(i); if (paramType.isPrimitiveType()) { candidScore -= 1; } else if (paramType.isArrayType()) { // TODO: Reevaluate scores candidScore -= 30; if (paramType.getInnermostElementType().equals(T)) { // Array of itself candidScore -= 1000; } } else if (paramType.isClassType()) { candidScore -= 101; } else if (paramType.isReferenceType()) { // TODO: Avoid interfaces if (paramType.equals(T)) { candidScore -= 1000; } else { candidScore -= 7; } if (paramType.equals(TypeReference.JavaLangObject)) { candidScore -= 1500; } } else { // ?! candidScore -= 800; } } if (candidScore > score) { ctor = im; score = candidScore; } logger.debug("CTor {} got score {}", im, candidScore); } if (ctor == null) { logger.warn("Still found no CTor for {}", T); return cha.resolveMethod(klass, MethodReference.initSelector); } else { return ctor; } } /** Satisfy the interface. */ @Override @SuppressWarnings("unchecked") public int createInstance(TypeReference type, Object... instantiatorArgs) { // public SSAValue createInstance(final TypeReference T, final boolean asManaged, VariableKey // key, Set<SSAValue> seen) { if (!(instantiatorArgs[0] instanceof Boolean)) { throw new IllegalArgumentException("Argument 0 to createInstance has to be boolean."); } if (!((instantiatorArgs[1] == null) || (instantiatorArgs[1] instanceof VariableKey))) { throw new IllegalArgumentException( "Argument 1 to createInstance has to be null or an instance of VariableKey"); } if (!((instantiatorArgs[2] == null) || (instantiatorArgs[2] instanceof Set))) { throw new IllegalArgumentException( "Argument 2 to createInstance has to be null or an instance of Set<? extends SSAValue>, " + "got: " + instantiatorArgs[2].getClass()); } if (instantiatorArgs[2] != null) { final Set<?> seen = (Set<?>) instantiatorArgs[2]; if (!seen.isEmpty()) { final Object o = seen.iterator().next(); if (!(o instanceof SSAValue)) { throw new IllegalArgumentException( "Argument 2 to createInstance has to be null or an instance of Set<? extends SSAValue>, " + "got Set<" + o.getClass() + '>'); } } } return createInstance( type, (Boolean) instantiatorArgs[0], (VariableKey) instantiatorArgs[1], (Set<? extends SSAValue>) instantiatorArgs[2]) .getNumber(); } }
26,375
35.837989
121
java
WALA
WALA-master/dalvik/src/main/java/com/ibm/wala/dalvik/ipa/callgraph/androidModel/parameters/LoadedInstantiationBehavior.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.androidModel.parameters; import com.ibm.wala.classLoader.IClass; import com.ibm.wala.classLoader.IClassLoader; import com.ibm.wala.core.util.strings.Atom; import com.ibm.wala.ipa.cha.IClassHierarchy; import com.ibm.wala.types.MethodReference; import com.ibm.wala.types.TypeName; import java.io.IOException; import java.io.Serializable; import java.util.HashMap; import java.util.Map; import java.util.Objects; /** * Behavior loaded from a file. * * <p>This class generates an empty mutable IInstantiationBehavior. * * @author Tobias Blaschke &lt;code@tobiasblaschke.de&gt; * @since 2013-10-25 */ public class LoadedInstantiationBehavior extends IInstantiationBehavior { private static final class BehviourValue implements Serializable { private static final long serialVersionUID = -7558845015122601212L; public final InstanceBehavior behaviour; public final Exactness exactness; public final BehviourValue cacheFrom; public BehviourValue( final InstanceBehavior behaviour, final Exactness exactness, final BehviourValue cacheFrom) { this.behaviour = behaviour; this.exactness = exactness; this.cacheFrom = cacheFrom; } @Override public String toString() { return "<BehaviorValue " + behaviour + " - " + exactness + " = " + cacheFrom + '>'; } /** If the value can be derived using an other mapping. */ public boolean isCached() { return this.cacheFrom != null; } } private static final class BehaviorKey<T> implements Serializable { private static final long serialVersionUID = 73530; // T is expected to be TypeName or Atom final T base; public BehaviorKey(T base) { this.base = base; } public static BehaviorKey<TypeName> mk(TypeName base) { return new BehaviorKey<>(base); } public static BehaviorKey<Atom> mk(Atom base) { return new BehaviorKey<>(base); } @Override public boolean equals(Object o) { if (o instanceof BehaviorKey) { BehaviorKey<?> other = (BehaviorKey<?>) o; return base.equals(other.base); } else { return false; } } @Override public int hashCode() { return this.base.hashCode(); } @Override public String toString() { return "<BehaviorKey of " + base.getClass() + ' ' + base + " hash=" + this.hashCode() + "/>"; } } private InstanceBehavior defaultBehavior = null; private final Map<BehaviorKey<?>, BehviourValue> behaviours = new HashMap<>(); private final IClassHierarchy cha; public LoadedInstantiationBehavior(IClassHierarchy cha) { this.cha = cha; } public void setDefaultBehavior(InstanceBehavior defaultBehavior) { this.defaultBehavior = defaultBehavior; } /** * @param asParameterTo not considered * @param inCall not considered * @param withName not considered */ @Override public InstanceBehavior getBehavior( final TypeName type, final TypeName asParameterTo, final MethodReference inCall, final String withName) { if (type == null) { throw new IllegalArgumentException("type may not be null"); } final BehaviorKey<TypeName> typeK = BehaviorKey.mk(type); if (behaviours.containsKey(typeK)) { BehviourValue typeV = behaviours.get(typeK); while (typeV.cacheFrom != null) { typeV = typeV.cacheFrom; } return typeV.behaviour; } // System.out.println(typeK.toString() + " not in " + behaviours); // Search based on package { final Atom pack = type.getPackage(); if (pack != null) { final BehaviorKey<Atom> packK = BehaviorKey.mk(pack); if (behaviours.containsKey(packK)) { // Add (cache) the result final BehviourValue packV = behaviours.get(packK); final InstanceBehavior beh = packV.behaviour; behaviours.put(typeK, new BehviourValue(beh, Exactness.PACKAGE, packV)); return beh; } } } // Search the super-classes { if (this.cha != null) { IClass testClass = null; for (final IClassLoader loader : this.cha.getLoaders()) { testClass = loader.lookupClass(type); if (testClass != null) { testClass = testClass.getSuperclass(); break; } } while (testClass != null) { final BehaviorKey<TypeName> testKey = BehaviorKey.mk(testClass.getName()); if (behaviours.containsKey(testKey)) { // Add (cache) the result final BehviourValue value = behaviours.get(testKey); final InstanceBehavior beh = value.behaviour; behaviours.put(typeK, new BehviourValue(beh, Exactness.INHERITED, value)); return beh; } testClass = testClass.getSuperclass(); } } else { } } // Search based on prefix { String prefix = type.toString(); while (prefix.contains("/")) { prefix = prefix.substring(0, prefix.lastIndexOf('/') - 1); final BehaviorKey<Atom> prefixKey = BehaviorKey.mk(Atom.findOrCreateAsciiAtom(prefix)); if (behaviours.containsKey(prefixKey)) { // cache final BehviourValue value = behaviours.get(prefixKey); final InstanceBehavior beh = value.behaviour; behaviours.put(typeK, new BehviourValue(beh, Exactness.PREFIX, value)); return beh; } } } // */ // Fall back to default { final InstanceBehavior beh = getDafultBehavior(); final BehviourValue packV = new BehviourValue(beh, Exactness.DEFAULT, null); behaviours.put(typeK, packV); return beh; } } /** * {@inheritDoc} * * <p>The DefaultInstanciationBehavior only knows EXACT, PACKAGE, PREFIX and DEFAULT */ @Override public Exactness getExactness( final TypeName type, final TypeName asParameterTo, final MethodReference inCall, final String withName) { if (type == null) { throw new IllegalArgumentException("type may not be null"); } final BehaviorKey<TypeName> typeK = BehaviorKey.mk(type); if (!behaviours.containsKey(typeK)) { // Use sideeffect: caches. getBehavior(type, asParameterTo, inCall, withName); } return behaviours.get(typeK).exactness; } /** */ @Override public InstanceBehavior getDafultBehavior() { return Objects.requireNonNullElse(defaultBehavior, InstanceBehavior.REUSE); } public void setBehavior( final TypeName type, final InstanceBehavior beh, final Exactness exactness) { final BehaviorKey<TypeName> typeK = BehaviorKey.mk(type); final BehviourValue val = new BehviourValue(beh, exactness, null); behaviours.put(typeK, val); } public void setBehavior(final Atom pack, final InstanceBehavior beh, final Exactness exactness) { final BehaviorKey<Atom> typeK = BehaviorKey.mk(pack); final BehviourValue val = new BehviourValue(beh, exactness, null); behaviours.put(typeK, val); } /** Convert a TypeName back to an Atom. */ protected static Atom type2atom(TypeName type) { return Atom.findOrCreateAsciiAtom(type.toString()); } // // (De-)Serialization stuff follows // /** The last eight digits encode the date. */ private static final long serialVersionUID = 810020131212L; /** Including the cache may be useful to get all seen types. */ public transient boolean serializationIncludesCache = true; private void writeObject(java.io.ObjectOutputStream stream) throws IOException { if (this.serializationIncludesCache) { stream.writeObject(this.behaviours); } else { final Map<BehaviorKey<?>, BehviourValue> strippedBehaviours = new HashMap<>(); for (final Map.Entry<BehaviorKey<?>, BehviourValue> entry : this.behaviours.entrySet()) { final BehviourValue val = entry.getValue(); if (!val.isCached()) { strippedBehaviours.put(entry.getKey(), val); } } stream.writeObject(strippedBehaviours); } } @SuppressWarnings("unchecked") private void readObject(java.io.ObjectInputStream stream) throws IOException, ClassNotFoundException { this.behaviours.clear(); this.behaviours.putAll((Map<BehaviorKey<?>, BehviourValue>) stream.readObject()); } }
10,317
31.24375
99
java
WALA
WALA-master/dalvik/src/main/java/com/ibm/wala/dalvik/ipa/callgraph/androidModel/parameters/ReuseParameters.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.androidModel.parameters; import com.ibm.wala.classLoader.IMethod; import com.ibm.wala.core.util.ssa.ParameterAccessor.BasedOn; import com.ibm.wala.core.util.ssa.ParameterAccessor.ParamerterDisposition; import com.ibm.wala.core.util.ssa.ParameterAccessor.Parameter; import com.ibm.wala.core.util.strings.Atom; import com.ibm.wala.dalvik.ipa.callgraph.androidModel.AndroidModel; import com.ibm.wala.dalvik.ipa.callgraph.androidModel.parameters.IInstantiationBehavior.InstanceBehavior; import com.ibm.wala.ipa.callgraph.Entrypoint; import com.ibm.wala.types.ClassLoaderReference; import com.ibm.wala.types.Descriptor; import com.ibm.wala.types.MethodReference; import com.ibm.wala.types.TypeName; import com.ibm.wala.types.TypeReference; import java.util.ArrayList; import java.util.List; /** * Helper for building the Descriptor of a model. * * <p>Parameters used in a model can be either marked as CREATE or REUSE. This information is * derived from the IInstantiationBehavior. * * <p>This class only handles parameters marked as REUSE: These will be parameters to the function * representing the model itself. On all uses of a variable named REUSE the same Instance * (optionally altered using Phi) will be used. * * <p>ReuseParameters collects all those parameters and builds the Descriptor of the later model. * * <p>Also ReuseParameters may be queried how to access these parameters the use of * ParameterAccessor is the better way to get them. * * @see com.ibm.wala.dalvik.ipa.callgraph.androidModel.parameters.IInstantiationBehavior * @see com.ibm.wala.core.util.ssa.ParameterAccessor * @author Tobias Blaschke &lt;code@tobiasblaschke.de&gt; * @since 2013-11-02 */ public class ReuseParameters { public static class ReuseParameter extends Parameter { protected ReuseParameter( final int number, final String name, final TypeReference type, final MethodReference mRef, final int descriptorOffset) { super( number, name, type, ParamerterDisposition.PARAM, BasedOn.IMETHOD, mRef, descriptorOffset); } } private final IMethod ALL_TARGETS = null; private final IInstantiationBehavior instanceBehavior; private final AndroidModel forModel; private List<TypeName> reuseParameters; /** * @param instanceBehavior The Behavior to query if the parameter is REUSE * @param forModel The AndroidModel in which context the status is to be determined */ public ReuseParameters( final IInstantiationBehavior instanceBehavior, final AndroidModel forModel) { this.instanceBehavior = instanceBehavior; this.forModel = forModel; } // private int firstParamSSA() { // return 1; // TODO // } /** * Searches the given entrypoints for those parameters. * * <p>A call to this function resets the internal knowledge of REUSE-Parameters. So in order to * get a union of these parameters a union of the given entrypoints has to be built. * * @param entrypoints The entrypoints to consider in the search. */ public void collectParameters(final Iterable<? extends Entrypoint> entrypoints) { // int paramsToModel = firstParamSSA(); this.reuseParameters = new ArrayList<>(); for (final Entrypoint ep : entrypoints) { final int paramCount = ep.getNumberOfParameters(); for (int i = 0; i < paramCount; ++i) { { // determine paramType final TypeReference[] types = ep.getParameterTypes(i); if (types.length < 1) { throw new IllegalStateException( "The Etrypoint " + ep + " did not return any types for its " + i + "th parameter"); } // Assert the rest of the types have the same name for (TypeReference type : types) { final TypeName paramType = type.getName(); if (isReuse(paramType, ALL_TARGETS)) { if (!reuseParameters.contains(paramType)) { // XXX: Why not use a Set? reuseParameters.add(paramType); } } } } } } } /** * Get the ssa-number for a parameter to an IMethod. * * @see com.ibm.wala.core.util.ssa.ParameterAccessor */ private static int ssaFor(IMethod inCallTo, int paramNo) { assert (paramNo >= 0); assert (paramNo < inCallTo.getNumberOfParameters()); if (inCallTo.isStatic()) { return paramNo + 1; } else { return paramNo + 1; // TODO 2 or 1? } } /** * Get the first paramNo of a given type. * * @see com.ibm.wala.core.util.ssa.ParameterAccessor */ private static int firstOf(TypeName type, IMethod inCallTo) { for (int i = 0; i < inCallTo.getNumberOfParameters(); ++i) { if (inCallTo.getParameterType(i).getName().equals(type)) { return i; } } throw new IllegalArgumentException(type.toString() + " is not a parameter to " + inCallTo); } /** * Is the parameter REUSE in a call from forModel to inCallTo. * * <p>The 'forModel' was set in the constructor. Even so a parameter occurs in the descriptor it * does not have to be REUSE for all calls. * * <p>The result of this method may vary over time :/ * * @param param The parameter in question of being reuse * @param inCallTo The callee to query the REUSEness for */ public boolean isReuse( TypeName param, IMethod inCallTo) { // TODO: Use IInstantiationBehavior.getBehavior(TypeName param, IMethod // inCallTo) final TypeName asParameterTo; final MethodReference inCall; /*final*/ String withName; if ((inCallTo != null) && (inCallTo != ALL_TARGETS)) { final int bcIndex = 0; // The PC to get the variable name from final int localNumber = ssaFor(inCallTo, firstOf(param, inCallTo)); try { withName = inCallTo.getLocalVariableName(bcIndex, localNumber); } catch (UnsupportedOperationException e) { // DexIMethod doesn't implement this :( withName = null; } asParameterTo = inCallTo.getDeclaringClass().getName(); inCall = inCallTo.getReference(); /*{ // DEBUG System.out.println("isReuse: "); System.out.println("\tparam = \t\t" + param); System.out.println("\tasParameterTo =\t" + asParameterTo); System.out.println("\tinCall =\t" + inCall); System.out.println("\twithName =\t" + withName); } // */ } else { withName = null; asParameterTo = null; inCall = null; } final InstanceBehavior beh = this.instanceBehavior.getBehavior(param, asParameterTo, inCall, withName); return (beh == InstanceBehavior.REUSE); } /** * Generate the descriptor to use for the model. * * @param returnType the return type of the later function */ private Descriptor toDescriptor(TypeName returnType) { // Keep private! final TypeName[] aTypes = reuseParameters.toArray(new TypeName[0]); return Descriptor.findOrCreate(aTypes, returnType); } public MethodReference toMethodReference(final AndroidModelParameterManager pm) { final TypeReference clazz = this.forModel.getDeclaringClass().getReference(); final Atom name = this.forModel.getName(); final TypeName returnType = this.forModel.getReturnType(); final Descriptor descr = toDescriptor(returnType); final MethodReference mRef = MethodReference.findOrCreate(clazz, name, descr); // TODO: Build Parameters and register them if (pm != null) { int paramSSA = 1; if (!this.forModel.isStatic()) { paramSSA = 2; } final int descriptorOffset; if (this.forModel.isStatic()) { descriptorOffset = 0; // TODO Verify! } else { descriptorOffset = -1; // TODO Verify! } for (final TypeName param : reuseParameters) { final String tName = null; // TODO final TypeReference tRef = TypeReference.find(ClassLoaderReference.Primordial, param); // TODO: Loaders! final ReuseParameter rp = new ReuseParameter(paramSSA, tName, tRef, mRef, descriptorOffset); pm.setAllocation(rp); // pm.setAllocation(tRef, paramSSA); // TODO: Old-school call paramSSA++; } } return mRef; } }
10,214
36.01087
105
java
WALA
WALA-master/dalvik/src/main/java/com/ibm/wala/dalvik/ipa/callgraph/androidModel/parameters/SpecializedInstantiator.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.androidModel.parameters; import com.ibm.wala.classLoader.IField; import com.ibm.wala.core.util.ssa.IInstantiator; import com.ibm.wala.core.util.ssa.ParameterAccessor; import com.ibm.wala.core.util.ssa.SSAValue; import com.ibm.wala.core.util.ssa.SSAValue.UniqueKey; import com.ibm.wala.core.util.ssa.SSAValue.VariableKey; import com.ibm.wala.core.util.ssa.SSAValueManager; import com.ibm.wala.core.util.ssa.TypeSafeInstructionFactory; import com.ibm.wala.dalvik.ipa.callgraph.androidModel.AndroidModelClass; import com.ibm.wala.dalvik.util.AndroidEntryPointManager; import com.ibm.wala.dalvik.util.AndroidTypes; import com.ibm.wala.ipa.callgraph.AnalysisScope; import com.ibm.wala.ipa.cha.IClassHierarchy; import com.ibm.wala.ipa.summaries.VolatileMethodSummary; import com.ibm.wala.ssa.ConstantValue; import com.ibm.wala.ssa.SSAInstruction; import com.ibm.wala.types.Descriptor; import com.ibm.wala.types.MethodReference; import com.ibm.wala.types.TypeName; import com.ibm.wala.types.TypeReference; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; /** * Instantiates certain android-types differently. * * <p>For example instantiating an android.content.Context would pull in all Android-components in * scope resulting in a massivly overapproximated model. * * @author Tobias Blaschke &lt;code@tobiasblaschke.de&gt; */ public class SpecializedInstantiator extends FlatInstantiator { final IInstantiator parent; public SpecializedInstantiator( final VolatileMethodSummary body, final TypeSafeInstructionFactory instructionFactory, final SSAValueManager pm, final IClassHierarchy cha, final MethodReference scope, final AnalysisScope analysisScope, final IInstantiator parent) { super(body, instructionFactory, pm, cha, scope, analysisScope, 100); this.parent = parent; } /** * Creates a new instance of type calling all that's necessary. * * <p>If T is a class-type all its constructors are searched for the one found best suited (takes * the least arguments, ...). New instances are created for all parameters, then the constructor * is called. * * <p>If T represents multiple types (is an interface, abstract class, ...) _all_ implementors of * that type are instantiated After that they get Phi-ed together. * * <p>If T is an array-type a new array of length 1 is generated. * * <p>TODO: Do we want to mix in REUSE-Parameters? */ @Override public SSAValue createInstance( final TypeReference T, final boolean asManaged, VariableKey key, Set<? extends SSAValue> seen) { return createInstance(T, asManaged, key, seen, 0); } /* package private */ SSAValue createInstance( final TypeReference T, final boolean asManaged, VariableKey key, Set<? extends SSAValue> seen, int currentDepth) { if (seen == null) { seen = new HashSet<>(); } if (currentDepth > this.maxDepth) { final SSAValue instance = this.pm.getUnmanaged(T, key); instance.setAssigned(); return instance; } // final IClass klass = this.cha.lookupClass(T); { // fetch new value if (asManaged) { if (key == null) { throw new IllegalArgumentException("A managed variable needs a key - null given."); } } else { if (key == null) { key = new UniqueKey(); } } } assert understands(T); if (T.equals(AndroidTypes.Context)) { return createContext(T, key); } if (T.equals(AndroidTypes.ContextWrapper)) { return createContextWrapper(T, key); } return null; } private static final Set<TypeReference> understandTypes = new HashSet<>(); static { understandTypes.add(AndroidTypes.Context); understandTypes.add(AndroidTypes.ContextWrapper); } public static boolean understands(TypeReference T) { return understandTypes.contains(T); } // Now for the specialized types... /** Creates a new instance of android/content/Context. */ public SSAValue createContext(final TypeReference T, VariableKey key) { final List<SSAValue> appComponents = new ArrayList<>(); { // TODO: Can we create a tighter conterxt? // TODO: Force an Application-Context? if (AndroidEntryPointManager.MANAGER.doFlatComponents()) { final AndroidModelClass mClass = AndroidModelClass.getInstance(cha); // At a given time context is expected to be only of one component already seen. // If it's seen there is a field in AndroidModelClass. for (final IField f : mClass.getAllFields()) { assert f.isStatic() : "All fields of AndroidModelClass are expected to be static! " + f + " is not."; final TypeReference fdType = f.getReference().getFieldType(); { // Test assignable if (!ParameterAccessor.isAssignable(fdType, T, cha)) { assert false : "Unexpected but not fatal - remove assertion if this happens"; continue; } } final VariableKey iKey = new SSAValue.TypeKey(fdType.getName()); final SSAValue instance; if (this.pm.isSeen(iKey)) { instance = this.pm.getCurrent(iKey); } else { final int pc = this.body.getNextProgramCounter(); final VariableKey subKey = new SSAValue.WeaklyNamedKey( fdType.getName(), "ctx" + fdType.getName().getClassName().toString()); instance = this.pm.getUnallocated(fdType, subKey); final SSAInstruction getInst = instructionFactory.GetInstruction(pc, instance, f.getReference()); this.body.addStatement(getInst); this.pm.setAllocation(instance, getInst); } appComponents.add(instance); } } else { for (TypeReference component : AndroidEntryPointManager.getComponents()) { final VariableKey iKey = new SSAValue.TypeKey(component.getName()); if (this.pm.isSeen(iKey)) { final SSAValue instance; instance = this.pm.getCurrent(iKey); assert (instance.getNumber() > 0); appComponents.add(instance); } } } } final SSAValue instance; if (appComponents.size() == 1) { instance = appComponents.get(0); } else if (appComponents.size() > 0) { { // Phi them together final int pc = this.body.getNextProgramCounter(); instance = this.pm.getFree(T, key); assert (pc > 0); assert (instance.getNumber() > 0); final SSAInstruction phi = instructionFactory.PhiInstruction(pc, instance, appComponents); this.body.addStatement(phi); this.pm.setPhi(instance, phi); } } else { instance = this.pm.getUnmanaged(T, key); this.body.addConstant(instance.getNumber(), new ConstantValue(null)); instance.setAssigned(); } return instance; } public SSAValue createContextWrapper(final TypeReference T, VariableKey key) { final VariableKey contextKey = new SSAValue.TypeKey(AndroidTypes.ContextName); final SSAValue context; { if (this.pm.isSeen(contextKey)) { context = this.pm.getCurrent(contextKey); } else { context = createContext(AndroidTypes.Context, contextKey); } } final SSAValue instance = this.pm.getUnallocated(T, key); { // call: ContextWrapper(Context base) final MethodReference ctor = MethodReference.findOrCreate( T, MethodReference.initAtom, Descriptor.findOrCreate( new TypeName[] {AndroidTypes.ContextName}, TypeReference.VoidName)); final List<SSAValue> params = new ArrayList<>(); params.add(context); addCallCtor(instance, ctor, params); } return instance; } /** Satisfy the interface. */ @Override @SuppressWarnings("unchecked") public int createInstance(TypeReference type, Object... instantiatorArgs) { // public SSAValue createInstance(final TypeReference T, final boolean asManaged, VariableKey // key, Set<SSAValue> seen) { if (!(instantiatorArgs[0] instanceof Boolean)) { throw new IllegalArgumentException("Argument 0 to createInstance has to be boolean."); } if (!((instantiatorArgs[1] == null) || (instantiatorArgs[1] instanceof VariableKey))) { throw new IllegalArgumentException( "Argument 1 to createInstance has to be null or an instance of VariableKey"); } if (!((instantiatorArgs[2] == null) || (instantiatorArgs[2] instanceof Set))) { throw new IllegalArgumentException( "Argument 2 to createInstance has to be null or an instance of Set<? extends SSAValue>, " + "got: " + instantiatorArgs[2].getClass()); } final int currentDepth; { if (instantiatorArgs.length == 4) { currentDepth = (Integer) instantiatorArgs[3]; } else { currentDepth = 0; } } if (instantiatorArgs[2] != null) { final Set<?> seen = (Set<?>) instantiatorArgs[2]; if (!seen.isEmpty()) { final Object o = seen.iterator().next(); if (!(o instanceof SSAValue)) { throw new IllegalArgumentException( "Argument 2 to createInstance has to be null or an instance of Set<? extends SSAValue>, " + "got Set<" + o.getClass() + '>'); } } } return createInstance( type, (Boolean) instantiatorArgs[0], (VariableKey) instantiatorArgs[1], (Set<? extends SSAValue>) instantiatorArgs[2], currentDepth) .getNumber(); } }
11,810
35.119266
103
java
WALA
WALA-master/dalvik/src/main/java/com/ibm/wala/dalvik/ipa/callgraph/androidModel/parameters/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. */ /** * Controls how variable-instances are handled in the AndroidModel. * * <p>The IInstantiationBehavior controls when to create a new instance of a given type or when to * use existing one. The AndroidModelParameterManager helps keeping track of the various instances. * * @see com.ibm.wala.dalvik.ipa.callgraph.androidModel.parameters.IInstantiationBehavior * @since 2013-10-25 * @author Tobias Blaschke &lt;code@tobiasblaschke.de&gt; */ package com.ibm.wala.dalvik.ipa.callgraph.androidModel.parameters;
2,401
45.192308
99
java
WALA
WALA-master/dalvik/src/main/java/com/ibm/wala/dalvik/ipa/callgraph/androidModel/structure/AbstractAndroidModel.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.androidModel.structure; import com.ibm.wala.core.util.ssa.SSAValueManager; import com.ibm.wala.core.util.ssa.TypeSafeInstructionFactory; import com.ibm.wala.dalvik.ipa.callgraph.impl.AndroidEntryPoint; import com.ibm.wala.dalvik.ipa.callgraph.impl.AndroidEntryPoint.ExecutionOrder; import com.ibm.wala.dalvik.ipa.callgraph.impl.AndroidEntryPoint.IExecutionOrder; import com.ibm.wala.ipa.callgraph.Entrypoint; import com.ibm.wala.ipa.summaries.VolatileMethodSummary; import com.ibm.wala.types.TypeReference; import java.util.ArrayList; import java.util.List; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Aids in handling code to be inserted at given points into the model. * * <p>Overload this class to change the structure of the model. When the model is being built the * enterLABEL-functions are called when ever a label gets stepped over. * * <p>You can then add instructions to the body using the insts-Instruction factory. Instructions * don't have to be in ascending order. Instead they will be sorted by their IIndex once the model * gets finished. * * <p>If you want to add loops to the model you might want to have a look at * AndroidModelParameterManager which aids in keeping track of SSA-Variables and adding * Phi-Functions. * * @see com.ibm.wala.dalvik.ipa.callgraph.impl.AndroidEntryPoint.ExecutionOrder * @see com.ibm.wala.dalvik.ipa.callgraph.androidModel.parameters.AndroidModelParameterManager * @author Tobias Blaschke &lt;code@tobiasblaschke.de&gt; * @since 2013-09-07 */ public abstract class AbstractAndroidModel { private static final Logger logger = LoggerFactory.getLogger(AbstractAndroidModel.class); private ExecutionOrder currentSection = null; protected VolatileMethodSummary body = null; protected TypeSafeInstructionFactory insts = null; protected SSAValueManager paramManager = null; protected Iterable<? extends Entrypoint> entryPoints = null; private IExecutionOrder lastQueriedMethod = null; // Used for sanity checks only // // Helper functions // /** * Return a List of all Types returned by functions between start (inclusive) and end (exclusive). * * @return That list * @throws IllegalArgumentException if an EntryPoint was not an AndroidEntryPoint */ protected List<TypeReference> returnTypesBetween(IExecutionOrder start, IExecutionOrder end) { assert (start != null) : "The argument start was null"; assert (end != null) : "The argument end was null"; List<TypeReference> returnTypes = new ArrayList<>(); for (Entrypoint ep : this.entryPoints) { if (ep instanceof AndroidEntryPoint) { AndroidEntryPoint aep = (AndroidEntryPoint) ep; if ((aep.compareTo(start) >= 0) && (aep.compareTo(end) <= 0)) { if (!(aep.getMethod().getReturnType().equals(TypeReference.Void) || aep.getMethod().getReturnType().isPrimitiveType())) { if (!returnTypes.contains(aep.getMethod().getReturnType())) { // TODO: Use a set? returnTypes.add(aep.getMethod().getReturnType()); } } } } else { throw new IllegalArgumentException( "Entrypoint (given to Constructor) is not an AndroidEntryPoint!"); } } return returnTypes; } // // The rest :) // /** * If you don't intend to use the paramManager, you can pass null. However all other parameters * are required. * * @param body The MethodSummary to add instructions to * @param insts Will be used to generate the instructions * @param paramManager aids in handling SSA-Values * @param entryPoints This iterable has to contain only instances of AnroidEntryPoint. */ public AbstractAndroidModel( VolatileMethodSummary body, TypeSafeInstructionFactory insts, SSAValueManager paramManager, Iterable<? extends Entrypoint> entryPoints) { if (body == null) { throw new IllegalArgumentException("The argument body may not be null."); } if (insts == null) { throw new IllegalArgumentException("The argument insts may not be null."); } if (entryPoints == null) { throw new IllegalArgumentException("The argument entryPoints may not be null."); } // if (!(entryPoints.hasNext())) { // throw new IllegalArgumentException("The iterable entryPoints may not be empty."); // } this.body = body; this.insts = insts; this.paramManager = paramManager; this.entryPoints = entryPoints; } /** * Determines for an AndroidEntryPoint if a label got skipped over. * * <p>If a label got skipped over special handling code has to be inserted before the entrypoints * invocation. * * <p>This function is expected to be called on entrypoints in ascending order. * * <p>You are expected to call {@link * #enter(com.ibm.wala.dalvik.ipa.callgraph.impl.AndroidEntryPoint.ExecutionOrder, int)} iff a * Label got skipped over. * * @param order The entrypoint in question * @return true if a label got stepped over * @throws IllegalArgumentException If the entrypoints weren't in ascending order * @throws IllegalStateException if you didn't call enter() */ public final boolean hadSectionSwitch(IExecutionOrder order) { if (order == null) { throw new IllegalArgumentException("the argument order may not be null."); } if (this.currentSection == null) { if (this.lastQueriedMethod != null) { throw new IllegalStateException( "You didn't call AbstractAndroidModel.enter(AT_FIRST) after a section-switch"); } // The first method is added to the model // don't set this.currentSection here or enter() will not actually enter;) this.lastQueriedMethod = order; return true; } if (order.compareTo(lastQueriedMethod) < 0) { throw new IllegalArgumentException( "This method is meant to be called on AndoidEntrypoints in ascending order"); } if ((currentSection.compareTo(lastQueriedMethod.getSection()) != 0) && (order.getSection().compareTo(lastQueriedMethod.getSection()) == 0)) { throw new IllegalStateException( "You didn't call AbstractAndroidModel.enter(" + order.getSection() + ") after a section-switch"); } this.lastQueriedMethod = order; return (this.currentSection.compareTo(order.getSection()) < 0); } /** * Gets called when Label ExecutionOrder.AT_FIRST got stepped over. * * <p>In most cases you don't want to invoke this function directly but to use {@code * enter(ExecutionOrder.AT_FIRST, int)} instead. * * <p>Sideeffects: currentSection is updated, instructions are inserted into the body * * @param PC Program Counter instructions shall be placed at. In most cases you'll simply pass * body.getNextProgramCounter() * @return Program Counter after insertion of the code */ protected int enterAT_FIRST(int PC) { return PC; } /** * Gets called when Label ExecutionOrder.BEFORE_LOOP got stepped over. * * <p>In most cases you don't want to invoke this function directly but to use {@code * enter(ExecutionOrder.BEFORE_LOOP, int)} instead * * <p>Sideeffects: currentSection is updated, instructions are inserted into the body * * @param PC Program Counter instructions shall be placed at. In most cases you'll simply pass * body.getNextProgramCounter() * @return Program Counter after insertion of the code */ protected int enterBEFORE_LOOP(int PC) { return PC; } /** * Gets called when Label ExecutionOrder.START_OF_LOOP got stepped over. * * <p>In most cases you don't want to invoke this function directly but to use {@code * enter(ExecutionOrder.START_OF_LOOP, int)} instead * * <p>Sideeffects: currentSection is updated, instructions are inserted into the body * * @param PC Program Counter instructions shall be placed at. In most cases you'll simply pass * body.getNextProgramCounter() * @return Program Counter after insertion of the code */ protected int enterSTART_OF_LOOP(int PC) { return PC; } /** * Gets called when Label ExecutionOrder.MIDDLE_OF_LOOP got stepped over. * * <p>In most cases you don't want to invoke this function directly but to use {@code * enter(ExecutionOrder.MIDDLE_OF_LOOP, int)} instead * * <p>Sideeffects: currentSection is updated, instructions are inserted into the body * * @param PC Program Counter instructions shall be placed at. In most cases you'll simply pass * body.getNextProgramCounter() * @return Program Counter after insertion of the code */ protected int enterMIDDLE_OF_LOOP(int PC) { return PC; } /** * Gets called when Label ExecutionOrder.MULTIPLE_TIMES_IN_LOOP got stepped over. * * <p>In most cases you don't want to invoke this function directly but to use {@code * enter(ExecutionOrder.MULTIPLE_TIMES_IN_LOOP, int)} instead * * <p>Sideeffects: currentSection is updated, instructions are inserted into the body * * @param PC Program Counter instructions shall be placed at. In most cases you'll simply pass * body.getNextProgramCounter() * @return Program Counter after insertion of the code */ protected int enterMULTIPLE_TIMES_IN_LOOP(int PC) { return PC; } /** * Gets called when Label ExecutionOrder.END_OF_LOOP got stepped over. * * <p>In most cases you don't want to invoke this function directly but to use {@code * enter(ExecutionOrder.END_OF_LOOP, int)} instead * * <p>Sideeffects: currentSection is updated, instructions are inserted into the body * * @param PC Program Counter instructions shall be placed at. In most cases you'll simply pass * body.getNextProgramCounter() * @return Program Counter after insertion of the code */ protected int enterEND_OF_LOOP(int PC) { return PC; } /** * Gets called when Label ExecutionOrder.AFTER_LOOP got stepped over. * * <p>In most cases you don't want to invoke this function directly but to use {@code * enter(ExecutionOrder.AFTER_LOOP, int)} instead * * <p>Sideeffects: currentSection is updated, instructions are inserted into the body * * @param PC Program Counter instructions shall be placed at. In most cases you'll simply pass * body.getNextProgramCounter() * @return Program Counter after insertion of the code */ protected int enterAFTER_LOOP(int PC) { return PC; } /** * Gets called when Label ExecutionOrder.AT_LAST got stepped over. * * <p>In most cases you don't want to invoke this function directly but to use {@code * enter(ExecutionOrder.AT_LAST, int)} instead * * <p>Sideeffects: currentSection is updated, instructions are inserted into the body * * @param PC Program Counter instructions shall be placed at. In most cases you'll simply pass * body.getNextProgramCounter() * @return Program Counter after insertion of the code */ protected int enterAT_LAST(int PC) { return PC; } /** * Gets called when the model gets finished. * * <p>In most cases you don't want to invoke this function directly but to use {@link * #finish(int)} instead * * <p>Sideeffects: instructions are inserted into the body * * @param PC Program Counter instructions shall be placed at. In most cases you'll simply pass * body.getNextProgramCounter() * @return Program Counter after insertion of the code */ protected int leaveAT_LAST(int PC) { return PC; } /** * Dispatches to the enterLABEL-functions. Does also call functions to any labels that got stepped * over. * * @param section The Section to enter * @param PC Program Counter instructions shall be placed at. In most cases you'll simply pass * body.getNextProgramCounter() * @return Program Counter after insertion of the code * @throws IllegalArgumentException if you didn't use sections in ascending order, pc is negative */ public int enter(ExecutionOrder section, int PC) { section = section.getSection(); // Just to be shure if ((this.currentSection != null) && (this.currentSection.compareTo(section) >= 0)) { if (this.currentSection.compareTo(section) == 0) { logger.error("You entered {} twice! Ignoring second atempt.", section); } else { throw new IllegalArgumentException( "Sections must be in ascending order! When trying to " + "enter " + this.currentSection + " from " + section); } } if (PC < 0) { throw new IllegalArgumentException("The PC can't be negative!"); } if (section.compareTo(AndroidEntryPoint.ExecutionOrder.AT_FIRST) == 0) { if (this.currentSection != null) { throw new IllegalArgumentException("Sections must be in ascending order!"); } } if ((this.currentSection == null) && (section.compareTo(AndroidEntryPoint.ExecutionOrder.AT_FIRST) >= 0)) { logger.info("ENTER: AT_FIRST"); PC = enterAT_FIRST(PC); this.currentSection = AndroidEntryPoint.ExecutionOrder.AT_FIRST; } if ((this.currentSection.compareTo(AndroidEntryPoint.ExecutionOrder.AT_FIRST) <= 0) && (section.compareTo(AndroidEntryPoint.ExecutionOrder.BEFORE_LOOP) >= 0)) { logger.info("ENTER: BEFORE_LOOP"); PC = enterBEFORE_LOOP(PC); this.currentSection = AndroidEntryPoint.ExecutionOrder.BEFORE_LOOP; } if ((this.currentSection.compareTo(AndroidEntryPoint.ExecutionOrder.BEFORE_LOOP) <= 0) && (section.compareTo(AndroidEntryPoint.ExecutionOrder.START_OF_LOOP) >= 0)) { logger.info("ENTER: START_OF_LOOP"); PC = enterSTART_OF_LOOP(PC); this.currentSection = AndroidEntryPoint.ExecutionOrder.START_OF_LOOP; } if ((this.currentSection.compareTo(AndroidEntryPoint.ExecutionOrder.START_OF_LOOP) <= 0) && (section.compareTo(AndroidEntryPoint.ExecutionOrder.MIDDLE_OF_LOOP) >= 0)) { logger.info("ENTER: MIDDLE_OF_LOOP"); PC = enterMIDDLE_OF_LOOP(PC); this.currentSection = AndroidEntryPoint.ExecutionOrder.MIDDLE_OF_LOOP; } if ((this.currentSection.compareTo(AndroidEntryPoint.ExecutionOrder.MIDDLE_OF_LOOP) <= 0) && (section.compareTo(AndroidEntryPoint.ExecutionOrder.MULTIPLE_TIMES_IN_LOOP) >= 0)) { PC = enterMULTIPLE_TIMES_IN_LOOP(PC); logger.info("ENTER: MULTIPLE_TIMES_IN_LOOP"); this.currentSection = AndroidEntryPoint.ExecutionOrder.MULTIPLE_TIMES_IN_LOOP; } if ((this.currentSection.compareTo(AndroidEntryPoint.ExecutionOrder.MULTIPLE_TIMES_IN_LOOP) <= 0) && (section.compareTo(AndroidEntryPoint.ExecutionOrder.END_OF_LOOP) >= 0)) { logger.info("ENTER: END_OF_LOOP"); PC = enterEND_OF_LOOP(PC); this.currentSection = AndroidEntryPoint.ExecutionOrder.END_OF_LOOP; } if ((this.currentSection.compareTo(AndroidEntryPoint.ExecutionOrder.END_OF_LOOP) <= 0) && (section.compareTo(AndroidEntryPoint.ExecutionOrder.AFTER_LOOP) >= 0)) { logger.info("ENTER: AFTER_LOOP"); PC = enterAFTER_LOOP(PC); this.currentSection = AndroidEntryPoint.ExecutionOrder.AFTER_LOOP; } if ((this.currentSection.compareTo(AndroidEntryPoint.ExecutionOrder.AFTER_LOOP) <= 0) && (section.compareTo(AndroidEntryPoint.ExecutionOrder.AT_LAST) >= 0)) { logger.info("ENTER: AT_LAST"); PC = enterAT_LAST(PC); this.currentSection = AndroidEntryPoint.ExecutionOrder.AT_LAST; } return PC; } /** * Calls all remaining enterLABEL-functions, finally calls leaveAT_LAST. * * <p>Then Locks the model and frees some memory. * * @param PC Program Counter instructions shall be placed at. In most cases you'll simply pass * body.getNextProgramCounter() * @return Program Counter after insertion of the code * @throws IllegalStateException if called on an empty model */ public int finish(int PC) { /* package private */ if (this.currentSection == null) { throw new IllegalStateException( "Called finish() on a model that doesn't " + "contain any sections - an empty model of" + this.body.getMethod().toString()); } if ((this.currentSection.compareTo(AndroidEntryPoint.ExecutionOrder.AT_LAST) < 0)) { PC = enter(AndroidEntryPoint.ExecutionOrder.AT_LAST, PC); } PC = leaveAT_LAST(PC); // Lock everything: currentSection = new ExecutionOrder(Integer.MAX_VALUE); // Free memory: body = null; insts = null; paramManager = null; entryPoints = null; lastQueriedMethod = null; return PC; } }
18,740
38.289308
100
java
WALA
WALA-master/dalvik/src/main/java/com/ibm/wala/dalvik/ipa/callgraph/androidModel/structure/LoopAndroidModel.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.androidModel.structure; import com.ibm.wala.core.util.ssa.SSAValue; import com.ibm.wala.core.util.ssa.SSAValue.NamedKey; import com.ibm.wala.core.util.ssa.SSAValue.TypeKey; import com.ibm.wala.core.util.ssa.SSAValue.VariableKey; import com.ibm.wala.core.util.ssa.SSAValueManager; import com.ibm.wala.core.util.ssa.TypeSafeInstructionFactory; import com.ibm.wala.dalvik.ipa.callgraph.impl.AndroidEntryPoint.ExecutionOrder; import com.ibm.wala.ipa.callgraph.Entrypoint; import com.ibm.wala.ipa.summaries.VolatileMethodSummary; import com.ibm.wala.shrike.shrikeBT.IConditionalBranchInstruction; import com.ibm.wala.ssa.ConstantValue; import com.ibm.wala.ssa.SSAPhiInstruction; import com.ibm.wala.types.TypeReference; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Builds an Android Model incorporating two loops. * * <p>Functions are inserted in sequence until ExecutionOrder.START_OF_LOOP is reached. This loop is * closed later when AFTER_LOOP gets stepped over. * * <p>Functions in MULTIPLE_TIMES_IN_LOOP are in a single inner loop. * * <p>This structure may be used to model an Application where no state is kept over the restart of * the Application (instance-state) or when the potential restart of the App shall be ignored. * * @author Tobias Blaschke &lt;code@tobiasblaschke.de&gt; */ public class LoopAndroidModel extends SingleStartAndroidModel { private static final Logger logger = LoggerFactory.getLogger(LoopAndroidModel.class); // protected VolatileMethodSummary body; // protected JavaInstructionFactory insts; // protected DexFakeRootMethod.ReuseParameters paramTypes; /** * @param body The MethodSummary to add instructions to * @param insts Will be used to generate the instructions */ public LoopAndroidModel( VolatileMethodSummary body, TypeSafeInstructionFactory insts, SSAValueManager paramManager, Iterable<? extends Entrypoint> entryPoints) { super(body, insts, paramManager, entryPoints); } private int outerLoopPC = -1; Map<TypeReference, SSAValue> outerStartingPhis; /** * Prepares the PC to get looped to. * * <p>Thus it tries to assure a new basic block starts here. Additionally it reserves some space * for the insertion of Phi-Functions. * * <p>{@inheritDoc} */ @Override protected int enterSTART_OF_LOOP(int PC) { logger.info("PC {} is the jump target of START_OF_LOOP", PC); this.outerLoopPC = PC; PC = body.getNextProgramCounter(); paramManager.scopeDown(true); // Top-Half of Phi-Handling outerStartingPhis = new HashMap<>(); List<TypeReference> outerPhisNeeded = returnTypesBetween(ExecutionOrder.START_OF_LOOP, ExecutionOrder.AFTER_LOOP); for (TypeReference phiType : outerPhisNeeded) { final TypeKey phiKey = new TypeKey(phiType.getName()); if (paramManager.isSeen(phiKey, false)) { final SSAValue newValue = paramManager.getFree(phiType, phiKey); outerStartingPhis.put(phiType, newValue); } } body.reserveProgramCounters(outerPhisNeeded.size()); // Actual Phis will be placed by the bottom-half handler... PC = body.getNextProgramCounter(); // Needed if no calls return PC; } /** * Loops to START_OF_LOOP. * * <p>It inserts a gotoInstruction and fills the space reserved before with actual PhiInstructions * * <p>{@inheritDoc} */ @Override protected int enterAFTER_LOOP(int PC) { assert (outerLoopPC > 0) : "Somehow you managed to get the loop-target negative. This is wierd!"; // Insert the Phis at the beginning of the Block int phiPC = outerLoopPC + 1; boolean oldAllowReserved = body.allowReserved(true); logger.info("Setting block-inner Phis"); for (final SSAValue oldPhi : outerStartingPhis.values()) { final List<SSAValue> forPhi = new ArrayList<>(2); forPhi.add(paramManager.getSuper(oldPhi.key)); forPhi.add(paramManager.getCurrent(oldPhi.key)); SSAPhiInstruction phi = insts.PhiInstruction(phiPC, oldPhi, forPhi); phiPC++; body.addStatement(phi); paramManager.setPhi(oldPhi, phi); } body.allowReserved(oldAllowReserved); // Close the Loop logger.info("Closing Loop"); logger.info("PC {}: Goto {}", PC, outerLoopPC); NamedKey trueKey = new SSAValue.NamedKey(TypeReference.BooleanName, "true"); SSAValue trueVal = paramManager.getFree(TypeReference.Boolean, trueKey); paramManager.setPhi(trueVal, null); body.addConstant(trueVal.getNumber(), new ConstantValue(true)); body.addStatement( insts.ConditionalBranchInstruction( PC, IConditionalBranchInstruction.Operator.EQ, TypeReference.Boolean, trueVal.getNumber(), trueVal.getNumber(), outerLoopPC)); paramManager.scopeUp(); // Add Phi-Statements at the beginning of this block... logger.info("Setting outer-block Phis"); for (Map.Entry<TypeReference, SSAValue> entry : outerStartingPhis.entrySet()) { final VariableKey phiKey = entry.getValue().key; PC = body.getNextProgramCounter(); List<SSAValue> all = paramManager.getAllForPhi(phiKey); final TypeReference phiType = entry.getKey(); logger.debug("Into phi {} for {}", all, phiType.getName()); // Narf ... unpacking... paramManager.invalidate(phiKey); final SSAValue newValue = paramManager.getFree(phiType, phiKey); SSAPhiInstruction phi = insts.PhiInstruction(PC, newValue, all); body.addStatement(phi); paramManager.setPhi(newValue, phi); } PC = body.getNextProgramCounter(); return PC; } /** * Does not insert any special handling. * * <p>{@inheritDoc} */ @Override protected int leaveAT_LAST(int PC) { logger.info("Leaving Model with PC = {}", PC); return PC; } }
7,911
36.67619
100
java
WALA
WALA-master/dalvik/src/main/java/com/ibm/wala/dalvik/ipa/callgraph/androidModel/structure/LoopKillAndroidModel.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.androidModel.structure; import com.ibm.wala.core.util.ssa.SSAValue; import com.ibm.wala.core.util.ssa.SSAValue.NamedKey; import com.ibm.wala.core.util.ssa.SSAValue.TypeKey; import com.ibm.wala.core.util.ssa.SSAValue.VariableKey; import com.ibm.wala.core.util.ssa.SSAValueManager; import com.ibm.wala.core.util.ssa.TypeSafeInstructionFactory; import com.ibm.wala.dalvik.ipa.callgraph.impl.AndroidEntryPoint.ExecutionOrder; import com.ibm.wala.ipa.callgraph.Entrypoint; import com.ibm.wala.ipa.summaries.VolatileMethodSummary; import com.ibm.wala.shrike.shrikeBT.IConditionalBranchInstruction; import com.ibm.wala.ssa.ConstantValue; import com.ibm.wala.ssa.SSAPhiInstruction; import com.ibm.wala.types.TypeReference; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Builds an Android Model incorporating three loops. * * <p>This variant adds a nother loop to the LoopAndroidModel. This additional loop emulates the * start of an Application with a savedIstanceState: * * <p>When memory on a device gets short Apps may be removed from memory. When they are needed again * they get started using that savedIstanceState. * * @see com.ibm.wala.dalvik.ipa.callgraph.androidModel.structure.LoopAndroidModel * @author Tobias Blaschke &lt;code@tobiasblaschke.de&gt; */ public class LoopKillAndroidModel extends LoopAndroidModel { private static final Logger logger = LoggerFactory.getLogger(LoopKillAndroidModel.class); // protected VolatileMethodSummary body; // protected JavaInstructionFactory insts; // protected DexFakeRootMethod.ReuseParameters paramTypes; /** * @param body The MethodSummary to add instructions to * @param insts Will be used to generate the instructions */ public LoopKillAndroidModel( VolatileMethodSummary body, TypeSafeInstructionFactory insts, SSAValueManager paramManager, Iterable<? extends Entrypoint> entryPoints) { super(body, insts, paramManager, entryPoints); } private int outerLoopPC = -1; Map<TypeReference, SSAValue> outerStartingPhis; /** * Loop starts here. * * <p>{@inheritDoc} */ @Override protected int enterAT_FIRST(int PC) { logger.info("PC {} is the jump target of START_OF_LOOP", PC); this.outerLoopPC = PC; PC = body.getNextProgramCounter(); paramManager.scopeDown(true); // Top-Half of Phi-Handling outerStartingPhis = new HashMap<>(); List<TypeReference> outerPhisNeeded = returnTypesBetween(ExecutionOrder.START_OF_LOOP, ExecutionOrder.AFTER_LOOP); for (TypeReference phiType : outerPhisNeeded) { final TypeKey phiKey = new TypeKey(phiType.getName()); if (paramManager.isSeen(phiKey, false)) { final SSAValue newValue = paramManager.getFree(phiType, phiKey); outerStartingPhis.put(phiType, newValue); } } body.reserveProgramCounters(outerPhisNeeded.size()); // Actual Phis will be placed by the bottom-half handler... PC = body.getNextProgramCounter(); // Needed if no calls return PC; } /** * Loops to AT_FIRST. * * <p>It inserts a gotoInstruction and fills the space reserved before with actual PhiInstructions * * <p>{@inheritDoc} */ @Override protected int leaveAT_LAST(int PC) { assert (outerLoopPC > 0) : "Somehow you managed to get the loop-target negative. This is wierd!"; // Insert the Phis at the beginning of the Block int phiPC = outerLoopPC + 1; boolean oldAllowReserved = body.allowReserved(true); logger.info("Setting block-inner Phis"); for (final SSAValue oldPhi : outerStartingPhis.values()) { final List<SSAValue> forPhi = new ArrayList<>(2); forPhi.add(paramManager.getSuper(oldPhi.key)); forPhi.add(paramManager.getCurrent(oldPhi.key)); SSAPhiInstruction phi = insts.PhiInstruction(phiPC, oldPhi, forPhi); phiPC++; body.addStatement(phi); paramManager.setPhi(oldPhi, phi); } body.allowReserved(oldAllowReserved); // Close the Loop logger.info("Closing Loop"); logger.info("PC {}: Goto {}", PC, outerLoopPC); NamedKey trueKey = new SSAValue.NamedKey(TypeReference.BooleanName, "true"); SSAValue trueVal = paramManager.getFree(TypeReference.Boolean, trueKey); paramManager.setPhi(trueVal, null); body.addConstant(trueVal.getNumber(), new ConstantValue(true)); body.addStatement( insts.ConditionalBranchInstruction( PC, IConditionalBranchInstruction.Operator.EQ, TypeReference.Boolean, trueVal.getNumber(), trueVal.getNumber(), outerLoopPC)); paramManager.scopeUp(); // Add Phi-Statements at the beginning of this block... logger.info("Setting outer-block Phis"); for (Map.Entry<TypeReference, SSAValue> entry : outerStartingPhis.entrySet()) { final VariableKey phiKey = entry.getValue().key; PC = body.getNextProgramCounter(); List<SSAValue> all = paramManager.getAllForPhi(phiKey); final TypeReference phiType = entry.getKey(); logger.debug("Into phi {} for {}", all, phiType.getName()); // Narf ... unpacking... paramManager.invalidate(phiKey); final SSAValue newValue = paramManager.getFree(phiType, phiKey); SSAPhiInstruction phi = insts.PhiInstruction(PC, newValue, all); body.addStatement(phi); paramManager.setPhi(newValue, phi); } PC = body.getNextProgramCounter(); return PC; } }
7,504
37.290816
100
java
WALA
WALA-master/dalvik/src/main/java/com/ibm/wala/dalvik/ipa/callgraph/androidModel/structure/SequentialAndroidModel.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.androidModel.structure; import com.ibm.wala.core.util.ssa.SSAValueManager; import com.ibm.wala.core.util.ssa.TypeSafeInstructionFactory; import com.ibm.wala.ipa.callgraph.Entrypoint; import com.ibm.wala.ipa.summaries.VolatileMethodSummary; /** * Functions get called once in sequential order. * * <p>No loops are inserted into the model. * * <p>This model should not be particular useful in practice. However it might come in handy for * debugging purposes or as a skeleton for an other Model. * * @author Tobias Blaschke &lt;code@tobiasblaschke.de&gt; * @since 2013-09-18 */ public final class SequentialAndroidModel extends AbstractAndroidModel { // private static final Logger logger = LoggerFactory.getLogger(SequentialAndroidModel.class); // protected VolatileMethodSummary body; // protected JavaInstructionFactory insts; // protected DexFakeRootMethod.ReuseParameters paramTypes; /** * @param body The MethodSummary to add instructions to * @param insts Will be used to generate the instructions */ public SequentialAndroidModel( VolatileMethodSummary body, TypeSafeInstructionFactory insts, SSAValueManager paramManager, Iterable<? extends Entrypoint> entryPoints) { super(body, insts, paramManager, entryPoints); } /** * Does not insert any special handling. * * <p>{@inheritDoc} */ @Override protected int enterAT_FIRST(int PC) { return PC; } /** * Does not insert any special handling. * * <p>{@inheritDoc} */ @Override protected int enterBEFORE_LOOP(int PC) { return PC; } /** * Does not insert any special handling. * * <p>{@inheritDoc} */ @Override protected int enterSTART_OF_LOOP(int PC) { return PC; } /** * Does not insert any special handling. * * <p>{@inheritDoc} */ @Override protected int enterMIDDLE_OF_LOOP(int PC) { return PC; } /** * Does not insert any special handling. * * <p>{@inheritDoc} */ @Override protected int enterMULTIPLE_TIMES_IN_LOOP(int PC) { return PC; } /** * Does not insert any special handling. * * <p>{@inheritDoc} */ @Override protected int enterEND_OF_LOOP(int PC) { return PC; } /** * Does not insert any special handling. * * <p>{@inheritDoc} */ @Override protected int enterAFTER_LOOP(int PC) { return PC; } /** * Does not insert any special handling. * * <p>{@inheritDoc} */ @Override protected int enterAT_LAST(int PC) { return PC; } /** * Does not insert any special handling. * * <p>{@inheritDoc} */ @Override protected int leaveAT_LAST(int PC) { return PC; } }
4,638
26.613095
99
java
WALA
WALA-master/dalvik/src/main/java/com/ibm/wala/dalvik/ipa/callgraph/androidModel/structure/SingleStartAndroidModel.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.androidModel.structure; import com.ibm.wala.core.util.ssa.SSAValue; import com.ibm.wala.core.util.ssa.SSAValue.NamedKey; import com.ibm.wala.core.util.ssa.SSAValue.TypeKey; import com.ibm.wala.core.util.ssa.SSAValue.VariableKey; import com.ibm.wala.core.util.ssa.SSAValueManager; import com.ibm.wala.core.util.ssa.TypeSafeInstructionFactory; import com.ibm.wala.dalvik.ipa.callgraph.impl.AndroidEntryPoint.ExecutionOrder; import com.ibm.wala.ipa.callgraph.Entrypoint; import com.ibm.wala.ipa.summaries.VolatileMethodSummary; import com.ibm.wala.shrike.shrikeBT.IConditionalBranchInstruction; import com.ibm.wala.ssa.ConstantValue; import com.ibm.wala.ssa.SSAPhiInstruction; import com.ibm.wala.types.TypeReference; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Builds an Android Model incorporating a single loop. * * <p>This class models a single run of an Andoird-Component: E.g. The view of an Activity gets * shown only once. * * <p>The incorporated loop is wrapped around user-interaction methods. These are in the section * MULTIPLE_TIMES_IN_LOOP. * * @see com.ibm.wala.dalvik.ipa.callgraph.androidModel.structure.LoopAndroidModel * @see com.ibm.wala.dalvik.ipa.callgraph.androidModel.structure.LoopKillAndroidModel * @author Tobias Blaschke &lt;code@tobiasblaschke.de&gt; */ public class SingleStartAndroidModel extends AbstractAndroidModel { private static final Logger logger = LoggerFactory.getLogger(SingleStartAndroidModel.class); // protected VolatileMethodSummary body; // protected JavaInstructionFactory insts; // protected DexFakeRootMethod.ReuseParameters paramTypes; /** * @param body The MethodSummary to add instructions to * @param insts Will be used to generate the instructions */ public SingleStartAndroidModel( VolatileMethodSummary body, TypeSafeInstructionFactory insts, SSAValueManager paramManager, Iterable<? extends Entrypoint> entryPoints) { super(body, insts, paramManager, entryPoints); } private int outerLoopPC = -1; Map<TypeReference, SSAValue> outerStartingPhis; /** * Prepares the PC to get looped to. * * <p>Thus it tries to assure a new basic block starts here. Additionally it reserves some space * for the insertion of Phi-Functions. * * <p>{@inheritDoc} */ @Override protected int enterMULTIPLE_TIMES_IN_LOOP(int PC) { logger.info("PC {} is the jump target of START_OF_LOOP", PC); this.outerLoopPC = PC; PC = body.getNextProgramCounter(); paramManager.scopeDown(true); // Top-Half of Phi-Handling outerStartingPhis = new HashMap<>(); List<TypeReference> outerPhisNeeded = returnTypesBetween(ExecutionOrder.START_OF_LOOP, ExecutionOrder.AFTER_LOOP); for (TypeReference phiType : outerPhisNeeded) { final TypeKey phiKey = new TypeKey(phiType.getName()); if (paramManager.isSeen(phiKey, false)) { final SSAValue newValue = paramManager.getFree(phiType, phiKey); outerStartingPhis.put(phiType, newValue); } } body.reserveProgramCounters(outerPhisNeeded.size()); // Actual Phis will be placed by the bottom-half handler... PC = body.getNextProgramCounter(); // Needed if no calls return PC; } /** * Loops to MULTIPLE_TIMES_IN_LOOP. * * <p>It inserts a gotoInstruction and fills the space reserved before with actual PhiInstructions * * <p>{@inheritDoc} */ @Override protected int enterEND_OF_LOOP(int PC) { assert (outerLoopPC > 0) : "Somehow you managed to get the loop-target negative. This is wierd!"; // Insert the Phis at the beginning of the Block int phiPC = outerLoopPC + 1; boolean oldAllowReserved = body.allowReserved(true); logger.info("Setting block-inner Phis"); for (final SSAValue oldPhi : outerStartingPhis.values()) { final List<SSAValue> forPhi = new ArrayList<>(2); forPhi.add(paramManager.getSuper(oldPhi.key)); forPhi.add(paramManager.getCurrent(oldPhi.key)); SSAPhiInstruction phi = insts.PhiInstruction(phiPC, oldPhi, forPhi); phiPC++; body.addStatement(phi); paramManager.setPhi(oldPhi, phi); } body.allowReserved(oldAllowReserved); // Close the Loop logger.info("Closing Loop"); logger.info("PC {}: Goto {}", PC, outerLoopPC); if (PC != outerLoopPC) { NamedKey trueKey = new SSAValue.NamedKey(TypeReference.BooleanName, "true"); SSAValue trueVal = paramManager.getFree(TypeReference.Boolean, trueKey); paramManager.setPhi(trueVal, null); body.addConstant(trueVal.getNumber(), new ConstantValue(true)); body.addStatement( insts.ConditionalBranchInstruction( PC, IConditionalBranchInstruction.Operator.EQ, TypeReference.Boolean, trueVal.getNumber(), trueVal.getNumber(), outerLoopPC)); } paramManager.scopeUp(); // Add Phi-Statements at the beginning of this block... logger.info("Setting outer-block Phis"); for (Map.Entry<TypeReference, SSAValue> entry : outerStartingPhis.entrySet()) { final SSAValue ssaValue = entry.getValue(); final VariableKey phiKey = ssaValue.key; PC = body.getNextProgramCounter(); List<SSAValue> all = paramManager.getAllForPhi(phiKey); final TypeReference phiType = entry.getKey(); logger.debug("Into phi {} for {}", all, phiType.getName()); // Narf ... unpacking... paramManager.invalidate(phiKey); final SSAValue newValue = paramManager.getFree(phiType, phiKey); SSAPhiInstruction phi = insts.PhiInstruction(PC, newValue, all); body.addStatement(phi); paramManager.setPhi(newValue, phi); } PC = body.getNextProgramCounter(); return PC; } }
7,836
37.99005
100
java
WALA
WALA-master/dalvik/src/main/java/com/ibm/wala/dalvik/ipa/callgraph/androidModel/structure/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. */ /** * Controls the overall structure of the later model. * * <p>This is done by inserting code into the model at given points. This way for example all the * loops are inserted into the model. * * <p>All Classes in this package extend AbstractAndroidModel. * * @see com.ibm.wala.dalvik.ipa.callgraph.androidModel.structure.AbstractAndroidModel * @since 2013-10-25 * @author Tobias Blaschke &lt;code@tobiasblaschke.de&gt; */ package com.ibm.wala.dalvik.ipa.callgraph.androidModel.structure;
2,386
43.203704
97
java
WALA
WALA-master/dalvik/src/main/java/com/ibm/wala/dalvik/ipa/callgraph/androidModel/stubs/AndroidBoot.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.androidModel.stubs; import com.ibm.wala.classLoader.CallSiteReference; import com.ibm.wala.classLoader.NewSiteReference; import com.ibm.wala.core.util.ssa.SSAValue; import com.ibm.wala.core.util.ssa.SSAValueManager; import com.ibm.wala.core.util.ssa.TypeSafeInstructionFactory; import com.ibm.wala.core.util.strings.Atom; import com.ibm.wala.dalvik.util.AndroidTypes; import com.ibm.wala.ipa.summaries.VolatileMethodSummary; import com.ibm.wala.shrike.shrikeBT.IInvokeInstruction; import com.ibm.wala.ssa.ConstantValue; import com.ibm.wala.ssa.SSAInstruction; import com.ibm.wala.types.Descriptor; import com.ibm.wala.types.FieldReference; import com.ibm.wala.types.MethodReference; import com.ibm.wala.types.Selector; import com.ibm.wala.types.TypeName; import com.ibm.wala.types.TypeReference; import java.util.ArrayList; import java.util.List; /** * Create some Android-Environment. * * <p>Used by the AndroidModel to assign some fields in the analyzed Application if the settings * instruct it to do so. * * @see com.ibm.wala.dalvik.ipa.callgraph.androidModel.AndroidModel * @see com.ibm.wala.dalvik.util.AndroidEntryPointManager * @author Tobias Blaschke &lt;code@tobiasblaschke.de&gt; * @since 2013-10-23 */ public class AndroidBoot { // private static Logger logger = LoggerFactory.getLogger(AndroidBoot.class); public enum BootAction { /** Create an instance of android.app.ContextImpl for the system. */ CREATE_SYSTEM_CONTEXT, /** Crate an instance of android.app.ContextImpl for the apk. */ CREATE_APK_CONTEXT, } // public static Set<BootAction> BOOT_ALL = EnumSet.allOf(BootAction); // private final MethodReference scope; private TypeSafeInstructionFactory instructionFactory; // private ParameterAccessor acc; private SSAValueManager pm; private VolatileMethodSummary body; // public AndroidBoot() { // this.scope = null; // Place something here? // } private SSAValue mainThread = null; private SSAValue systemContext = null; private SSAValue packageContext = null; public void addBootCode( final TypeSafeInstructionFactory instructionFactory, final SSAValueManager pm, final VolatileMethodSummary body) { this.instructionFactory = instructionFactory; // this.acc = acc; this.pm = pm; this.body = body; mainThread = createMainThred(); systemContext = createSystemContext(mainThread); packageContext = createPackageContext(mainThread); } public SSAValue getSystemContext() { if (systemContext == null) { throw new IllegalStateException("No value for systemContext - was addBootCode called?"); } return systemContext; } public SSAValue getPackageContext() { if (packageContext == null) { throw new IllegalStateException("No value for packageContext - was addBootCode called?"); } return packageContext; } public SSAValue getMainThread() { if (mainThread == null) { throw new IllegalStateException("No value for mainThread - was addBootCode called?"); } return mainThread; } /** Create the main-thread as activity-thread. */ private SSAValue createMainThred() { final SSAValue mainThread = this.pm.getUnmanaged(AndroidTypes.ActivityThread, "mMainThred"); { // New-Site final int pc = this.body.getNextProgramCounter(); final NewSiteReference nRef = NewSiteReference.make(pc, AndroidTypes.ActivityThread); final SSAInstruction newInstr = this.instructionFactory.NewInstruction(pc, mainThread, nRef); body.addStatement(newInstr); } /*{ // clinit final int pc = this.body.getNextProgramCounter(); final MethodReference mRef = MethodReference.findOrCreate(AndroidTypes.ActivityThread, MethodReference.clinitSelector); final SSAValue exception = new SSAValue(this.pm.getUnmanaged(), TypeReference.JavaLangException, this.scope, "ctor_exc" ); final CallSiteReference site = CallSiteReference.make(pc, mRef, IInvokeInstruction.Dispatch.SPECIAL); final List<SSAValue> params = new ArrayList<SSAValue>(1); params.add(mainThread); final SSAInstruction ctorCall = instructionFactory.InvokeInstruction(pc, params, exception, site); body.addStatement(ctorCall); }*/ { // CTor-Call final int pc = this.body.getNextProgramCounter(); final MethodReference mRef = MethodReference.findOrCreate(AndroidTypes.ActivityThread, MethodReference.initSelector); final SSAValue exception = this.pm.getUnmanaged(TypeReference.JavaLangException, "ctor_exc"); final CallSiteReference site = CallSiteReference.make(pc, mRef, IInvokeInstruction.Dispatch.SPECIAL); final List<SSAValue> params = new ArrayList<>(1); params.add(mainThread); final SSAInstruction ctorCall = instructionFactory.InvokeInstruction(pc, params, exception, site); body.addStatement(ctorCall); } return mainThread; } /** * Create an instance of android.app.ContextImpl for the system. * * @see android.app.ContextImpl.createPackageContextAsUser */ @SuppressWarnings("JavadocReference") private SSAValue createSystemContext(SSAValue mainThread) { final SSAValue systemContext = this.pm.getUnmanaged(AndroidTypes.ContextImpl, "systemContextImpl"); { // Call ContextImpl.getSystemContext() final int pc = this.body.getNextProgramCounter(); final Descriptor desc = Descriptor.findOrCreate(new TypeName[0], AndroidTypes.ContextImplName); final Selector mSel = new Selector(Atom.findOrCreateAsciiAtom("getSystemContext"), desc); final MethodReference mRef = MethodReference.findOrCreate(AndroidTypes.ActivityThread, mSel); final CallSiteReference site = CallSiteReference.make(pc, mRef, IInvokeInstruction.Dispatch.VIRTUAL); final SSAValue exception = this.pm.getException(); final List<SSAValue> params = new ArrayList<>(1); params.add(mainThread); final SSAInstruction call = instructionFactory.InvokeInstruction(pc, systemContext, params, exception, site); body.addStatement(call); } { // putting mRestricted = false final SSAValue falseConst = this.pm.getUnmanaged(TypeReference.Boolean, "falseConst"); this.body.addConstant(falseConst.getNumber(), new ConstantValue(false)); falseConst.setAssigned(); final int pc = this.body.getNextProgramCounter(); final FieldReference mRestricted = FieldReference.findOrCreate( AndroidTypes.ContextImpl, Atom.findOrCreateAsciiAtom("mRestricted"), TypeReference.Boolean); final SSAInstruction putInst = instructionFactory.PutInstruction(pc, systemContext, falseConst, mRestricted); body.addStatement(putInst); } return systemContext; } /** * Create an instance of android.app.ContextImpl for the apk. * * @see android.app.ContextImpl.createPackageContextAsUser */ @SuppressWarnings("JavadocReference") private SSAValue createPackageContext(final SSAValue mainThread) { final SSAValue packageContext = this.pm.getUnmanaged(AndroidTypes.ContextImpl, "packageContextImpl"); { // New-Site final int pc = this.body.getNextProgramCounter(); final NewSiteReference nRef = NewSiteReference.make(pc, AndroidTypes.ContextImpl); final SSAInstruction newInstr = this.instructionFactory.NewInstruction(pc, packageContext, nRef); body.addStatement(newInstr); } /*{ // clnint final int pc = this.body.getNextProgramCounter(); final MethodReference mRef = MethodReference.findOrCreate(AndroidTypes.ContextImpl, MethodReference.clinitSelector); final SSAValue exception = new SSAValue(this.pm.getUnmanaged(), TypeReference.JavaLangException, this.scope, "ctor_exc" ); final CallSiteReference site = CallSiteReference.make(pc, mRef, IInvokeInstruction.Dispatch.SPECIAL); final List<SSAValue> params = new ArrayList<SSAValue>(1); params.add(packageContext); final SSAInstruction ctorCall = instructionFactory.InvokeInstruction(pc, params, exception, site); body.addStatement(ctorCall); }*/ { // CTor-Call final int pc = this.body.getNextProgramCounter(); final MethodReference mRef = MethodReference.findOrCreate(AndroidTypes.ContextImpl, MethodReference.initSelector); final SSAValue exception = this.pm.getUnmanaged(TypeReference.JavaLangException, "ctor_exc"); final CallSiteReference site = CallSiteReference.make(pc, mRef, IInvokeInstruction.Dispatch.SPECIAL); final List<SSAValue> params = new ArrayList<>(1); params.add(packageContext); final SSAInstruction ctorCall = instructionFactory.InvokeInstruction(pc, params, exception, site); body.addStatement(ctorCall); } { // putting mRestricted = false final SSAValue falseConst = this.pm.getUnmanaged(TypeReference.Boolean, "falseConst"); this.body.addConstant(falseConst.getNumber(), new ConstantValue(false)); falseConst.setAssigned(); final int pc = this.body.getNextProgramCounter(); final FieldReference mRestricted = FieldReference.findOrCreate( AndroidTypes.ContextImpl, Atom.findOrCreateAsciiAtom("mRestricted"), TypeReference.Boolean); final SSAInstruction putInst = instructionFactory.PutInstruction(pc, packageContext, falseConst, mRestricted); body.addStatement(putInst); } final SSAValue packageName; { // Generating pacakge name packageName = this.pm.getUnmanaged(TypeReference.JavaLangString, "packageName"); this.body.addConstant(packageName.getNumber(), new ConstantValue("foo")); // TODO: Fetch name packageName.setAssigned(); } final SSAValue uid = this.pm.getUnmanaged(AndroidTypes.UserHandle, "uid"); { // New UserHandle final int pc = this.body.getNextProgramCounter(); final NewSiteReference nRef = NewSiteReference.make(pc, AndroidTypes.UserHandle); final SSAInstruction newInstr = this.instructionFactory.NewInstruction(pc, uid, nRef); body.addStatement(newInstr); } /*{ // UserHandle(1000) // TODO: seems android-subs do not contain this final SSAValue nrUid = new SSAValue(this.pm.getUnmanaged(), TypeReference.Int, this.scope, "nrUid"); this.body.addConstant(nrUid.getNumber(), new ConstantValue(1000)); // First regular linux user nrUid.setAssigned(); final int pc = this.body.getNextProgramCounter(); final Descriptor descr = Descriptor.findOrCreate(new TypeName[] { TypeReference.IntName }, TypeReference.VoidName); final Selector mSel = new Selector(MethodReference.initAtom, descr); final MethodReference mRef = MethodReference.findOrCreate(AndroidTypes.UserHandle, mSel); final SSAValue exception = new SSAValue(this.pm.getUnmanaged(), TypeReference.JavaLangException, this.scope, "ctor_exc" ); final CallSiteReference site = CallSiteReference.make(pc, mRef, IInvokeInstruction.Dispatch.SPECIAL); final List<SSAValue> params = new ArrayList<SSAValue>(2); params.add(uid); params.add(nrUid); final SSAInstruction ctorCall = instructionFactory.InvokeInstruction(pc, params, exception, site); body.addStatement(ctorCall); } // */ /*{ // packageContext.init(pi = null, null, mMainThread, mResources = null, mBasePackageName, user); TODO: Not in android stubs final SSAValue nullApk = new SSAValue(this.pm.getUnmanaged(), AndroidTypes.LoadedApk, this.scope, "nullApk"); // TODO this.body.addConstant(nullApk.getNumber(), new ConstantValue(null)); nullApk.setAssigned(); final SSAValue nullIBinder = new SSAValue(this.pm.getUnmanaged(), AndroidTypes.IBinder, this.scope, "nullBinder"); this.body.addConstant(nullIBinder.getNumber(), new ConstantValue(null)); nullIBinder.setAssigned(); final SSAValue nullResources = new SSAValue(this.pm.getUnmanaged(), AndroidTypes.Resources, this.scope, "nullResources"); // TODO this.body.addConstant(nullResources.getNumber(), new ConstantValue(null)); nullResources.setAssigned(); final int pc = this.body.getNextProgramCounter(); final Descriptor desc = Descriptor.findOrCreate(new TypeName[] { AndroidTypes.LoadedApkName, AndroidTypes.IBinderName, AndroidTypes.ActivityThreadName, AndroidTypes.ResourcesName, TypeName.string2TypeName("Ljava/lang/String"), // Private?! TypeReference.JavaLangStringName, AndroidTypes.UserHandleName}, TypeReference.VoidName); final Selector mSel = new Selector(Atom.findOrCreateAsciiAtom("init"), desc); // the name of the function is actually init final MethodReference mRef = MethodReference.findOrCreate(AndroidTypes.ContextImpl, mSel); final SSAValue exception = new SSAValue(this.pm.getUnmanaged(), TypeReference.JavaLangException, this.scope, "init_exc" ); final CallSiteReference site = CallSiteReference.make(pc, mRef, IInvokeInstruction.Dispatch.VIRTUAL); final List<SSAValue> params = new ArrayList<SSAValue>(7); params.add(packageContext); params.add(nullApk); // TODO: This would contain a Context too? params.add(nullIBinder); // OK: is null in Android-Sources too params.add(mainThread); params.add(nullResources); // TODO params.add(packageName); params.add(uid); final SSAInstruction call = instructionFactory.InvokeInstruction(pc, params, exception, site); body.addStatement(call); } // */ { // XXX: ALTERNATIVE FROM THE ABOVE, THAT IS IN STUBS!! // init(Landroid/app/LoadedApk;Landroid/os/IBinder;Landroid/app/ActivityThread;)V final SSAValue nullApk = this.pm.getUnmanaged(AndroidTypes.LoadedApk, "nullApk"); // TODO this.body.addConstant(nullApk.getNumber(), new ConstantValue(null)); nullApk.setAssigned(); final SSAValue nullIBinder = this.pm.getUnmanaged(AndroidTypes.IBinder, "nullBinder"); this.body.addConstant(nullIBinder.getNumber(), new ConstantValue(null)); nullIBinder.setAssigned(); final int pc = this.body.getNextProgramCounter(); final Descriptor desc = Descriptor.findOrCreate( new TypeName[] { AndroidTypes.LoadedApkName, AndroidTypes.IBinderName, AndroidTypes.ActivityThreadName, }, TypeReference.VoidName); final Selector mSel = new Selector( Atom.findOrCreateAsciiAtom("init"), desc); // the name of the function is actually init final MethodReference mRef = MethodReference.findOrCreate(AndroidTypes.ContextImpl, mSel); final SSAValue exception = this.pm.getException(); final CallSiteReference site = CallSiteReference.make(pc, mRef, IInvokeInstruction.Dispatch.VIRTUAL); final List<SSAValue> params = new ArrayList<>(7); params.add(packageContext); params.add(nullApk); // TODO: This would contain a Context too? params.add(nullIBinder); // OK: is null in Android-Sources too params.add(mainThread); final SSAInstruction call = instructionFactory.InvokeInstruction(pc, params, exception, site); body.addStatement(call); } return packageContext; } // private SSAValue createApplicationContext(final SSAValue mainThread, final SSAValue // systemContext) { // return null; // TODO // } }
17,701
46.714286
137
java
WALA
WALA-master/dalvik/src/main/java/com/ibm/wala/dalvik/ipa/callgraph/androidModel/stubs/AndroidStartComponentTool.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.androidModel.stubs; import com.ibm.wala.classLoader.CallSiteReference; import com.ibm.wala.classLoader.IClass; import com.ibm.wala.core.util.ssa.ParameterAccessor; import com.ibm.wala.core.util.ssa.ParameterAccessor.Parameter; import com.ibm.wala.core.util.ssa.SSAValue; import com.ibm.wala.core.util.ssa.SSAValueManager; import com.ibm.wala.core.util.ssa.TypeSafeInstructionFactory; import com.ibm.wala.core.util.strings.Atom; import com.ibm.wala.dalvik.ipa.callgraph.androidModel.AndroidModelClass; import com.ibm.wala.dalvik.ipa.callgraph.propagation.cfa.IntentStarters.StartInfo; import com.ibm.wala.dalvik.ipa.callgraph.propagation.cfa.IntentStarters.StarterFlags; import com.ibm.wala.dalvik.util.AndroidTypes; import com.ibm.wala.ipa.cha.IClassHierarchy; import com.ibm.wala.ipa.summaries.VolatileMethodSummary; import com.ibm.wala.shrike.shrikeBT.IInvokeInstruction; import com.ibm.wala.ssa.ConstantValue; import com.ibm.wala.ssa.SSAInstruction; import com.ibm.wala.types.Descriptor; import com.ibm.wala.types.FieldReference; import com.ibm.wala.types.MethodReference; import com.ibm.wala.types.Selector; import com.ibm.wala.types.TypeName; import com.ibm.wala.types.TypeReference; import java.util.ArrayList; import java.util.List; import java.util.Set; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Grab and set data of AndroidClasses. * * <p>This class is only used by AndroidModel.getMethodAs() as it got a bit lengthy. * * @author Tobias Blaschke &lt;code@tobiasblaschke.de&gt; * @since 2013-10-22 */ public class AndroidStartComponentTool { private static final Logger logger = LoggerFactory.getLogger(AndroidStartComponentTool.class); private final IClassHierarchy cha; // private final MethodReference asMethod; private final Set<StarterFlags> flags; private final TypeReference caller; private final TypeSafeInstructionFactory instructionFactory; private final ParameterAccessor acc; private final SSAValueManager pm; private final VolatileMethodSummary redirect; private final Parameter self; // private final StartInfo info; // private final CGNode callerNd; private AndroidTypes.AndroidContextType callerContext; public AndroidStartComponentTool( final IClassHierarchy cha, final MethodReference asMethod, final Set<StarterFlags> flags, final TypeReference caller, final TypeSafeInstructionFactory instructionFactory, final ParameterAccessor acc, final SSAValueManager pm, final VolatileMethodSummary redirect, final Parameter self, final StartInfo info) { if (cha == null) { throw new IllegalArgumentException("cha may not be null"); } if (asMethod == null) { throw new IllegalArgumentException("asMethod may not be null"); } if (flags == null) { throw new IllegalArgumentException("Flags may not be null"); } if ((caller == null) && !flags.contains(StarterFlags.CONTEXT_FREE)) { throw new IllegalArgumentException( "Caller may not be null if StarterFlags.CONTEXT_FREE is not set. Flags: " + flags); } if (instructionFactory == null) { throw new IllegalArgumentException("The instructionFactory may not be null"); } if (acc == null) { throw new IllegalArgumentException("acc may not be null"); } if (pm == null) { throw new IllegalArgumentException("pm may not be null"); } if (redirect == null) { throw new IllegalArgumentException("self may not be null"); } if (info == null) { throw new IllegalArgumentException("info may not be null"); } // if ((callerNd == null) && (! flags.contains(StarterFlags.CONTEXT_FREE))) { // throw new IllegalArgumentException("CallerNd may not be null if StarterFlags.CONTEXT_FREE // is not set. Flags: " + flags); // } this.cha = cha; // this.asMethod = asMethod; this.flags = flags; this.caller = caller; this.instructionFactory = instructionFactory; this.acc = acc; this.pm = pm; this.redirect = redirect; this.self = self; // this.info = info; // this.callerNd = callerNd; } public void attachActivities( Set<? extends SSAValue> activities, SSAValue application, SSAValue thread, SSAValue context, SSAValue iBinderToken, SSAValue intent) { // call: final void Activity.attach(Context context, ActivityThread aThread, Instrumentation // instr, IBinder token, // Application application, Intent intent, ActivityInfo info, CharSequence title, // Activity parent, String id, Object lastNonConfigurationInstance, // Configuration config) final SSAValue nullInstrumentation; { nullInstrumentation = pm.getUnmanaged(AndroidTypes.Instrumentation, "nullInstrumentation"); this.redirect.addConstant(nullInstrumentation.getNumber(), new ConstantValue(null)); nullInstrumentation.setAssigned(); } final SSAValue nullInfo; { nullInfo = pm.getUnmanaged(AndroidTypes.ActivityInfo, "nullInfo"); this.redirect.addConstant(nullInfo.getNumber(), new ConstantValue(null)); nullInfo.setAssigned(); } final SSAValue title; { title = pm.getUnmanaged(TypeReference.JavaLangString, "title"); // XXX CharSequence this.redirect.addConstant(title.getNumber(), new ConstantValue("title")); title.setAssigned(); } final SSAValue nullParent; { nullParent = pm.getUnmanaged(AndroidTypes.Activity, "nullParent"); this.redirect.addConstant(nullParent.getNumber(), new ConstantValue(null)); nullParent.setAssigned(); } final SSAValue nullConfigInstance; { final TypeName cName = TypeName.string2TypeName("Landroid/app/Activity$NonConfigurationInstances"); final TypeReference type = TypeReference.findOrCreate(com.ibm.wala.types.ClassLoaderReference.Primordial, cName); nullConfigInstance = pm.getUnmanaged(type, "noState"); this.redirect.addConstant(nullConfigInstance.getNumber(), new ConstantValue(null)); nullConfigInstance.setAssigned(); } final SSAValue nullConfiguration; { nullConfiguration = pm.getUnmanaged(AndroidTypes.Configuration, "nullConfig"); this.redirect.addConstant(nullConfiguration.getNumber(), new ConstantValue(null)); nullConfiguration.setAssigned(); } final Descriptor desc = Descriptor.findOrCreate( new TypeName[] { AndroidTypes.ContextName, AndroidTypes.ActivityThreadName, AndroidTypes.InstrumentationName, AndroidTypes.IBinderName, AndroidTypes.ApplicationName, AndroidTypes.IntentName, AndroidTypes.ActivityInfoName, TypeName.string2TypeName("Ljava/lang/CharSequence"), AndroidTypes.ActivityName, TypeReference.JavaLangString.getName(), TypeName.string2TypeName("Landroid/app/Activity$NonConfigurationInstances"), AndroidTypes.ConfigurationName }, TypeReference.VoidName); final Selector mSel = new Selector(Atom.findOrCreateAsciiAtom("attach"), desc); final MethodReference mRef = MethodReference.findOrCreate(AndroidTypes.Activity, mSel); final List<SSAValue> params = new ArrayList<>(13); params.add(null); // activity params.add(context); params.add(thread); params.add(nullInstrumentation); params.add(iBinderToken); params.add(application); params.add(intent); params.add(nullInfo); params.add(title); params.add(nullParent); params.add(title); params.add(nullConfigInstance); params.add(nullConfiguration); for (final SSAValue activity : activities) { final int callPC = redirect.getNextProgramCounter(); final CallSiteReference site = CallSiteReference.make(callPC, mRef, IInvokeInstruction.Dispatch.VIRTUAL); final SSAValue exception = pm.getException(); params.set(0, activity); final SSAInstruction invokation = instructionFactory.InvokeInstruction(callPC, params, exception, site); redirect.addStatement(invokation); } } public AndroidTypes.AndroidContextType typeOfCallerContext() { return this.callerContext; } /** * Fetches the context of the caller. * * @return A new SSAValue representing the androidContext (may be null!). // XXX */ public SSAValue fetchCallerContext() { /*if (flags.contains(StarterFlags.CONTEXT_FREE)) { return null; // XXX: Return a synthetic null? }*/ if (caller == null) { return null; } final IClass iCaller = cha.lookupClass(caller); final IClass iActivity = cha.lookupClass(AndroidTypes.Activity); final IClass iApp = cha.lookupClass(AndroidTypes.Application); final IClass iService = cha.lookupClass(AndroidTypes.Service); final SSAValue androidContext; if (caller.getName().equals(AndroidTypes.ContextWrapperName)) { this.callerContext = AndroidTypes.AndroidContextType.USELESS; return null; /*{ // Fetch ContextWrapperName.mBase => androidContext androidContext = pm.getUnmanaged(AndroidTypes.Context, "callerContext"); final FieldReference mBaseRef = FieldReference.findOrCreate(AndroidTypes.ContextWrapper, Atom.findOrCreateAsciiAtom("mBase"), AndroidTypes.Context); final int instPC = redirect.getNextProgramCounter(); final SSAInstruction getInst = instructionFactory.GetInstruction(instPC, androidContext, self, mBaseRef); redirect.addStatement(getInst); // TODO: somehow dispatch on type of mBase? this.callerContext = AndroidTypes.AndroidContextType.CONTEXT_IMPL; logger.info("Caller has android-context type: ContextWrapper(ContextImpl)"); return androidContext; } */ } else if (caller.getName().equals(AndroidTypes.ContextImplName)) { { // self is already the right context androidContext = self; this.callerContext = AndroidTypes.AndroidContextType.CONTEXT_IMPL; return androidContext; } } else if (cha.isAssignableFrom(iActivity, iCaller)) { // We don't need it for now - TODO grab anyway androidContext = null; this.callerContext = AndroidTypes.AndroidContextType.ACTIVITY; return androidContext; } else if (caller.equals(AndroidModelClass.ANDROID_MODEL_CLASS)) { // TODO: Return something useful this.callerContext = AndroidTypes.AndroidContextType.USELESS; return null; } else if (caller.getName().equals(AndroidTypes.BridgeContextName)) { // XXX ??? androidContext = self; this.callerContext = AndroidTypes.AndroidContextType.CONTEXT_BRIDGE; return androidContext; } else if (cha.isAssignableFrom(iApp, iCaller)) { androidContext = self; this.callerContext = AndroidTypes.AndroidContextType.APPLICATION; return androidContext; } else if (cha.isAssignableFrom(iService, iCaller)) { androidContext = self; this.callerContext = AndroidTypes.AndroidContextType.SERVICE; return androidContext; } else { logger.debug("Can not handle the callers android-context of " + caller); return null; } } /** * Fetch the permissions to start the component with. * * <p>Fetching depends on StarterFlags.QUENCH_PERMISSIONS, XXX * * @return an iBinder * @throws UnsupportedOperationException when fetching is not supported with the current settings */ public SSAValue fetchIBinder(SSAValue androidContext) { final SSAValue iBinder = pm.getUnmanaged(AndroidTypes.IBinder, "foreignIBinder"); if (flags.contains(StarterFlags.CONTEXT_FREE)) { // TODO: Can we do somethig? return null; } else if (flags.contains(StarterFlags.QUENCH_PERMISSIONS)) { // If this flag is set the given asMethod has a IntentSender-Parameter final Parameter intentSender = acc.firstOf(AndroidTypes.IntentSenderName); assert (intentSender != null) : "Unable to look up the IntentSender-Object"; assert (intentSender.getNumber() == 2) : "The IntentSender-Object was not located at SSA-Number 2. This may be entirely " + "ok! I left this assertion to ashure the ParameterAccessor does its job right."; // retreive the IBinder: IIntentSender.asBinder() final SSAValue iIntentSender = pm.getUnmanaged(AndroidTypes.IIntentSender, "iIntentSender"); { // call IIntentSender IntentSender.getTarget() final int callPC = redirect.getNextProgramCounter(); final Selector mSel = Selector.make("getTarget()Landroid/content/IIntentSender;"); final MethodReference mRef = MethodReference.findOrCreate(AndroidTypes.IntentSender, mSel); final CallSiteReference site = CallSiteReference.make(callPC, mRef, IInvokeInstruction.Dispatch.VIRTUAL); final SSAValue exception = pm.getException(); final List<SSAValue> params = new ArrayList<>(1); params.add(intentSender); final SSAInstruction invokation = instructionFactory.InvokeInstruction(callPC, iIntentSender, params, exception, site); redirect.addStatement(invokation); } { // call IBinder IIntentSender.asBinder() final int callPC = redirect.getNextProgramCounter(); final Selector mSel = Selector.make("asBinder()Landroid/os/IBinder;"); final MethodReference mRef = MethodReference.findOrCreate(AndroidTypes.IntentSender, mSel); final CallSiteReference site = CallSiteReference.make(callPC, mRef, IInvokeInstruction.Dispatch.VIRTUAL); final SSAValue exception = pm.getException(); final List<SSAValue> params = new ArrayList<>(1); params.add(iIntentSender); final SSAInstruction invokation = instructionFactory.InvokeInstruction(callPC, iBinder, params, exception, site); redirect.addStatement(invokation); } return iBinder; // } else if (caller.getName().equals(AndroidTypes.ActivityName)) { } else if (this.callerContext == AndroidTypes.AndroidContextType.ACTIVITY) { // The IBinder is Activity.mMainThread.getApplicationThread() // TODO: Verify final SSAValue mMainThread = pm.getUnmanaged(AndroidTypes.ActivityThread, "callersMainThred"); { // Fetch mMainthred final int instPC = redirect.getNextProgramCounter(); final FieldReference mMainThreadRef = FieldReference.findOrCreate( AndroidTypes.Activity, Atom.findOrCreateAsciiAtom("mMainThread"), AndroidTypes.ActivityThread); final SSAInstruction getInst = instructionFactory.GetInstruction(instPC, mMainThread, self, mMainThreadRef); redirect.addStatement(getInst); } /*{ // DEBUG final com.ibm.wala.classLoader.IClass activityThread = cha.lookupClass(AndroidTypes.ActivityThread); assert (activityThread != null); for (com.ibm.wala.classLoader.IMethod m : activityThread.getDeclaredMethods()) { System.out.println(m); } } // */ { // Call getApplicationThread() on it final int callPC = redirect.getNextProgramCounter(); final Selector mSel = Selector.make("getApplicationThread()Landroid/app/ActivityThread$ApplicationThread;"); final MethodReference mRef = MethodReference.findOrCreate(AndroidTypes.ActivityThread, mSel); final CallSiteReference site = CallSiteReference.make(callPC, mRef, IInvokeInstruction.Dispatch.VIRTUAL); final SSAValue exception = pm.getException(); final List<SSAValue> params = new ArrayList<>(1); params.add(mMainThread); final SSAInstruction invokation = instructionFactory.InvokeInstruction(callPC, iBinder, params, exception, site); redirect.addStatement(invokation); } // */ return iBinder; } else if (this.callerContext == AndroidTypes.AndroidContextType.CONTEXT_IMPL) { // For bindService its mActivityToken - TODO: For the rest? // startActivity uses mMainThread.getApplicationThread() { // read mActivityToken -> iBinder final FieldReference mActivityTokenRef = FieldReference.findOrCreate( AndroidTypes.ContextImpl, Atom.findOrCreateAsciiAtom("mActivityToken"), AndroidTypes.IBinder); final int instPC = redirect.getNextProgramCounter(); final SSAInstruction getInst = instructionFactory.GetInstruction(instPC, iBinder, androidContext, mActivityTokenRef); redirect.addStatement(getInst); } return iBinder; } else if (this.callerContext == AndroidTypes.AndroidContextType.CONTEXT_BRIDGE) { // TODO: Return something useful return null; } else if (caller.equals(AndroidModelClass.ANDROID_MODEL_CLASS)) { // TODO: Return something useful return null; } else { throw new UnsupportedOperationException( "No implementation on how to extract an iBinder from a " + caller); } } /** Set the iBinder in the callee. */ public void assignIBinder(SSAValue iBinder, List<? extends SSAValue> allActivities) { if (iBinder == null) { // TODO: Some day we may throe here... return; } // TODO: Use Phi? for (SSAValue activity : allActivities) { // final int callPC = redirect.getNextProgramCounter(); final FieldReference mTokenRef = FieldReference.findOrCreate( AndroidTypes.Activity, Atom.findOrCreateAsciiAtom("mToken"), AndroidTypes.IBinder); final int instPC = redirect.getNextProgramCounter(); final SSAInstruction putInst = instructionFactory.PutInstruction(instPC, activity, iBinder, mTokenRef); redirect.addStatement(putInst); } } /** Call Activity.setIntent. */ public void setIntent(SSAValue intent, List<? extends SSAValue> allActivities) { if (intent == null) { throw new IllegalArgumentException("Null-Intent"); } // TODO: Use Phi? for (SSAValue activity : allActivities) { final int callPC = redirect.getNextProgramCounter(); final Selector mSel = Selector.make("setIntent(Landroid/content/Intent;)V"); final MethodReference mRef = MethodReference.findOrCreate(AndroidTypes.Activity, mSel); final CallSiteReference site = CallSiteReference.make(callPC, mRef, IInvokeInstruction.Dispatch.VIRTUAL); final SSAValue exception = pm.getException(); final List<SSAValue> params = new ArrayList<>(1); params.add(activity); params.add(intent); final SSAInstruction invokation = instructionFactory.InvokeInstruction(callPC, params, exception, site); redirect.addStatement(invokation); } } /** * Grab mResultCode and mResultData. * * <p>This data is used to call onActivityResult of the caller. */ public void fetchResults( List<? super SSAValue> resultCodes, List<? super SSAValue> resultData, List<? extends SSAValue> allActivities) { for (SSAValue activity : allActivities) { final SSAValue tmpResultCode = pm.getUnmanaged(TypeReference.Int, "mResultCode"); { // Fetch mResultCode // redirect.setLocalName(tmpResultCode, "gotResultCode"); final FieldReference mResultCodeRef = FieldReference.findOrCreate( AndroidTypes.Activity, Atom.findOrCreateAsciiAtom("mResultCode"), TypeReference.Int); final int instPC = redirect.getNextProgramCounter(); final SSAInstruction getInst = instructionFactory.GetInstruction(instPC, tmpResultCode, activity, mResultCodeRef); redirect.addStatement(getInst); } final SSAValue tmpResultData = pm.getUnmanaged(AndroidTypes.Intent, "mResultData"); { // Fetch mResultData // redirect.setLocalName(tmpResultData, "gotResultData"); final FieldReference mResultDataRef = FieldReference.findOrCreate( AndroidTypes.Activity, Atom.findOrCreateAsciiAtom("mResultData"), AndroidTypes.Intent); final int instPC = redirect.getNextProgramCounter(); final SSAInstruction getInst = instructionFactory.GetInstruction(instPC, tmpResultData, activity, mResultDataRef); redirect.addStatement(getInst); } // */ resultCodes.add(tmpResultCode); resultData.add(tmpResultData); } // End: for all activities */ assert (resultCodes.size() == resultData.size()); } /** Add Phi (if necessary) - not if only one from. */ public SSAValue addPhi(List<? extends SSAValue> from) { if (from.size() == 1) { return from.get(0); } else { final SSAValue retVal = this.pm.getUnmanaged(from.get(0).getType(), "forPhi"); final int phiPC = redirect.getNextProgramCounter(); final SSAInstruction phi = instructionFactory.PhiInstruction(phiPC, retVal, from); this.redirect.addStatement(phi); return retVal; } } }
23,285
39.924429
135
java
WALA
WALA-master/dalvik/src/main/java/com/ibm/wala/dalvik/ipa/callgraph/androidModel/stubs/ExternalModel.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.androidModel.stubs; import com.ibm.wala.classLoader.CallSiteReference; import com.ibm.wala.classLoader.IClass; import com.ibm.wala.core.util.ssa.ParameterAccessor; import com.ibm.wala.core.util.ssa.SSAValue; import com.ibm.wala.core.util.ssa.TypeSafeInstructionFactory; import com.ibm.wala.core.util.strings.Atom; import com.ibm.wala.dalvik.ipa.callgraph.androidModel.AndroidModel; import com.ibm.wala.dalvik.ipa.callgraph.androidModel.AndroidModelClass; import com.ibm.wala.dalvik.ipa.callgraph.impl.AndroidEntryPoint; import com.ibm.wala.dalvik.util.AndroidComponent; import com.ibm.wala.dalvik.util.AndroidTypes; import com.ibm.wala.ipa.callgraph.AnalysisOptions; import com.ibm.wala.ipa.callgraph.IAnalysisCacheView; import com.ibm.wala.ipa.cha.IClassHierarchy; import com.ibm.wala.ipa.summaries.MethodSummary; import com.ibm.wala.ipa.summaries.SummarizedMethod; import com.ibm.wala.ipa.summaries.VolatileMethodSummary; import com.ibm.wala.shrike.shrikeBT.IInvokeInstruction; import com.ibm.wala.ssa.ConstantValue; import com.ibm.wala.ssa.SSAInstruction; import com.ibm.wala.types.Descriptor; import com.ibm.wala.types.MethodReference; import com.ibm.wala.types.Selector; import com.ibm.wala.types.TypeName; import com.ibm.wala.types.TypeReference; import com.ibm.wala.util.CancelException; import java.util.ArrayList; import java.util.Collection; import java.util.List; /** * This is generates a dummy for the call to an external Activity. * * <p>Is used by the IntentContextInterpreter if an Intent is marked as beeing external. * * @see com.ibm.wala.dalvik.ipa.callgraph.propagation.cfa.IntentContextInterpreter * @author Tobias Blaschke &lt;code@tobiasblaschke.de&gt; * @since 2013-10-15 */ public class ExternalModel extends AndroidModel { public final Atom name; private SummarizedMethod activityModel; // private final AndroidComponent target; // uses AndroidModel.cha; /** * Do not call any EntryPoint. * * <p>{@inheritDoc} */ @Override protected boolean selectEntryPoint(AndroidEntryPoint ep) { return false; } public ExternalModel( final IClassHierarchy cha, final AnalysisOptions options, final IAnalysisCacheView cache, AndroidComponent target) { super(cha, options, cache); if (target == null) { throw new IllegalArgumentException( "The component type requested to create an ExternalModel for was null"); } this.name = Atom.findOrCreateAsciiAtom("startExternal" + target); // this.target = target; } // @Override private void register(SummarizedMethod model) { AndroidModelClass mClass = AndroidModelClass.getInstance(cha); if (!mClass.containsMethod(model.getSelector())) { mClass.addMethod(model); } } @Override public SummarizedMethod getMethod() throws CancelException { if (!built) { super.build(this.name); this.register(super.model); this.activityModel = super.model; } return this.activityModel; } @Override protected void build(Atom name, Collection<? extends AndroidEntryPoint> entrypoints) { assert ((entrypoints == null) || !entrypoints.iterator().hasNext()); final TypeName intentName = AndroidTypes.IntentName; final TypeName bundleName = AndroidTypes.BundleName; final Descriptor descr = Descriptor.findOrCreate( new TypeName[] {intentName, TypeReference.IntName, bundleName}, intentName); this.mRef = MethodReference.findOrCreate(AndroidModelClass.ANDROID_MODEL_CLASS, name, descr); final Selector selector = new Selector(name, descr); // Assert not registered yet final AndroidModelClass mClass = AndroidModelClass.getInstance(this.cha); if (mClass.containsMethod(selector)) { this.model = (SummarizedMethod) mClass.getMethod(selector); return; } this.body = new VolatileMethodSummary(new MethodSummary(this.mRef)); this.body.setStatic(true); populate(null); this.klass = AndroidModelClass.getInstance(this.cha); this.model = new SummarizedMethod(this.mRef, this.body.getMethodSummary(), this.klass) { @Override public TypeReference getParameterType(int i) { IClassHierarchy cha = getClassHierarchy(); TypeReference tRef = super.getParameterType(i); if (tRef.isClassType()) { if (cha.lookupClass(tRef) != null) { return tRef; } else { for (IClass c : cha) { if (c.getName().toString().equals(tRef.getName().toString())) { return c.getReference(); } } } throw new IllegalStateException("Error looking up " + tRef); } else { return tRef; } } }; this.built = true; } /** * Fill the model with instructions. * * <p>Read the extra-data associated with the Intent. Read the optional bundle argument Write data * to the Intent to return. */ // @Override private void populate(Iterable<? extends AndroidEntryPoint> entrypoints) { assert ((entrypoints == null) || !entrypoints.iterator().hasNext()); assert !built : "You can only build once"; final TypeSafeInstructionFactory instructionFactory = new TypeSafeInstructionFactory(getClassHierarchy()); // mRef is: startExternal...(Intent, int, Bundle) --> Intent final ParameterAccessor pAcc = new ParameterAccessor(this.mRef, /* hasImplicitThis */ false); // final AndroidModelParameterManager pm = new AndroidModelParameterManager(pAcc); // See this.build() for parameter mapping final SSAValue inIntent = pAcc.firstOf(AndroidTypes.IntentName); assert (inIntent.getNumber() == 1); final SSAValue inBundle = pAcc.firstOf(AndroidTypes.BundleName); assert (inBundle.getNumber() == 3) : "Wrong bundle " + inBundle + " of " + this.mRef; // TODO: Verify was 2 int nextLocal = pAcc.getFirstAfter(); // assert (nextLocal == 4); // was 3 SSAValue outBundle; SSAValue outIntent; { // Read out Intent extras final int callPC = this.body.getNextProgramCounter(); // Bundle Intent.getExtras() final Selector mSel = Selector.make("getExtras()Landroid/os/Bundle;"); final MethodReference mRef = MethodReference.findOrCreate(AndroidTypes.Intent, mSel); final CallSiteReference site = CallSiteReference.make(callPC, mRef, IInvokeInstruction.Dispatch.VIRTUAL); final SSAValue exception = new SSAValue(nextLocal++, TypeReference.JavaLangException, this.mRef, "exception"); outBundle = new SSAValue(nextLocal++, inBundle); final List<SSAValue> params = new ArrayList<>(1); params.add(inIntent); final SSAInstruction invokation = instructionFactory.InvokeInstruction(callPC, outBundle, params, exception, site); this.body.addStatement(invokation); } /*{ // Read from the bundle returned by the Intent extras // TODO Defunct // TODO: If I clone it - does it access all? final int callPC = this.body.getNextProgramCounter(); // Bundle Intent.getExtras() final Selector mSel = Selector.make("clone()Landroid/os/Bundle;"); final MethodReference mRef = MethodReference.findOrCreate(AndroidTypes.Bundle, mSel); final CallSiteReference site = CallSiteReference.make(callPC, mRef, IInvokeInstruction.Dispatch.VIRTUAL); final SSAValue exception = new SSAValue(nextLocal++, TypeReference.JavaLangException, this.mRef, "exception"); final SSAValue myBundle = outBundle; outBundle = new SSAValue(nextLocal++, outBundle); final List<SSAValue> params = new ArrayList<SSAValue>(1); params.add(myBundle); final SSAInstruction invokation = instructionFactory.InvokeInstruction(callPC, outBundle, params, exception, site); this.body.addStatement(invokation); } { // Read from the bundle given as argument // TODO: If I clone it - does it access all? final int callPC = this.body.getNextProgramCounter(); // Bundle Intent.getExtras() final Selector mSel = Selector.make("clone()Landroid/os/Bundle;"); final MethodReference mRef = MethodReference.findOrCreate(AndroidTypes.Bundle, mSel); final CallSiteReference site = CallSiteReference.make(callPC, mRef, IInvokeInstruction.Dispatch.VIRTUAL); final SSAValue exception = new SSAValue(nextLocal++, TypeReference.JavaLangException, this.mRef, "exception"); outBundle = new SSAValue(nextLocal++, outBundle); final List<SSAValue> params = new ArrayList<SSAValue>(1); params.add(inBundle); final SSAInstruction invokation = instructionFactory.InvokeInstruction(callPC, outBundle, params, exception, site); this.body.addStatement(invokation); }*/ { // Call Intent.putExtra(String name, int value) do add some new info final SSAValue outName = new SSAValue(nextLocal++, TypeReference.JavaLangString, this.mRef, "outName"); this.body.addConstant(outName.getNumber(), new ConstantValue("my.extra.object")); final SSAValue outValue = new SSAValue(nextLocal++, TypeReference.Int, this.mRef, "outValue"); // Assign value? final int callPC = this.body.getNextProgramCounter(); // void onActivityResult (int requestCode, int resultCode, Intent data) final Selector mSel = Selector.make("putExtra(Ljava/lang/String;I)Landroid/content/Intent;"); final MethodReference mRef = MethodReference.findOrCreate(AndroidTypes.Intent, mSel); final CallSiteReference site = CallSiteReference.make(callPC, mRef, IInvokeInstruction.Dispatch.VIRTUAL); final SSAValue exception = new SSAValue(nextLocal++, TypeReference.JavaLangException, this.mRef, "exception"); outIntent = new SSAValue(nextLocal++, inIntent); final List<SSAValue> params = new ArrayList<>(3); params.add(inIntent); params.add(outName); params.add(outValue); final SSAInstruction invokation = instructionFactory.InvokeInstruction(callPC, outIntent, params, exception, site); this.body.addStatement(invokation); } { // Add return statement on intent final int returnPC = this.body.getNextProgramCounter(); final SSAInstruction returnInstruction = instructionFactory.ReturnInstruction(returnPC, outIntent); this.body.addStatement(returnInstruction); } } }
12,554
40.435644
118
java
WALA
WALA-master/dalvik/src/main/java/com/ibm/wala/dalvik/ipa/callgraph/androidModel/stubs/Overrides.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.androidModel.stubs; import com.ibm.wala.classLoader.CallSiteReference; import com.ibm.wala.classLoader.IClass; import com.ibm.wala.classLoader.IMethod; import com.ibm.wala.dalvik.ipa.callgraph.androidModel.AndroidModel; import com.ibm.wala.dalvik.ipa.callgraph.propagation.cfa.IntentStarters; 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.IAnalysisCacheView; import com.ibm.wala.ipa.callgraph.MethodTargetSelector; import com.ibm.wala.ipa.cha.IClassHierarchy; import com.ibm.wala.ipa.summaries.SummarizedMethod; import com.ibm.wala.types.MethodReference; import com.ibm.wala.types.Selector; import com.ibm.wala.types.TypeReference; import com.ibm.wala.util.CancelException; import com.ibm.wala.util.MonitorUtil.IProgressMonitor; import com.ibm.wala.util.collections.HashMapFactory; import java.util.EnumMap; import java.util.HashMap; import java.util.Map; import java.util.Set; /** * Context Free overrides for the startComponent-Methods. * * <p>The context-sensitive Overrides may be found in the cfa-package mentioned below. * * @see com.ibm.wala.dalvik.ipa.callgraph.propagation.cfa * @see com.ibm.wala.dalvik.ipa.callgraph.propagation.cfa.IntentStarters * @author Tobias Blaschke &lt;code@tobiasblaschke.de&gt; * @since 2013-10-28 */ public class Overrides { // private static Logger logger = LoggerFactory.getLogger(Overrides.class); private final AndroidModel caller; private final IClassHierarchy cha; private final AnalysisOptions options; private final IAnalysisCacheView cache; public Overrides( AndroidModel caller, IClassHierarchy cha, AnalysisOptions options, IAnalysisCacheView cache) { this.caller = caller; this.cha = cha; this.options = options; this.cache = cache; } protected static class StartComponentMethodTargetSelector implements MethodTargetSelector { protected MethodTargetSelector parent; protected MethodTargetSelector child; protected final HashMap<MethodReference, SummarizedMethod> syntheticMethods; /** * @param syntheticMethods The Methods to override * @param child Ask child if unable to resolve. May be null */ public StartComponentMethodTargetSelector( HashMap<MethodReference, SummarizedMethod> syntheticMethods, MethodTargetSelector child) { // for (MethodReference mRef : syntheticMethods.keySet()) { // // } this.syntheticMethods = syntheticMethods; this.parent = null; this.child = child; } /** * The MethodTarget selector to ask before trying to resolve the Method with this one. * * @throws IllegalStateException if tried to set parent twice */ public void setParent(MethodTargetSelector parent) { if (this.parent != null) { throw new IllegalStateException("Parent may only be set once"); } this.parent = parent; } /** * The MethodTarget selector to ask when the Method could not be resolved by this one. * * <p>In order to be able to use this function you have to set null as child in the Constructor. * * @throws IllegalStateException if tried to set parent twice */ public void setChild(MethodTargetSelector child) { if (this.child != null) { throw new IllegalStateException("Child may only be set once"); } this.child = child; } @Override public IMethod getCalleeTarget(CGNode caller, CallSiteReference site, IClass receiver) { /*if (caller == null) { throw new IllegalArgumentException("caller is null"); }*/ if (site == null) { throw new IllegalArgumentException("site is null"); } if (this.parent != null) { IMethod resolved = this.parent.getCalleeTarget(caller, site, receiver); if (resolved != null) { return resolved; } } final MethodReference mRef = site.getDeclaredTarget(); if (syntheticMethods.containsKey(mRef)) { if (caller != null) { // XXX: Debug remove // Context ctx = caller.getContext(); } if (receiver == null) { // return null; // throw new IllegalArgumentException("site is null"); } return syntheticMethods.get(mRef); } if (this.child != null) { IMethod resolved = this.child.getCalleeTarget(caller, site, receiver); if (resolved != null) { return resolved; } } return null; } } /** * Generates methods in a MethodTargetSelector. * * <p>for all methods found in IntentStarters a synthetic method is generated and added to the * MethodTargetSelector returned. * * @return a MethodTargetSelector that overrides all startComponent-calls. TODO: Use delayed * computation? */ public MethodTargetSelector overrideAll() throws CancelException { final HashMap<MethodReference, SummarizedMethod> overrides = HashMapFactory.make(); final Map<AndroidComponent, AndroidModel> callTo = new EnumMap<>(AndroidComponent.class); final IProgressMonitor monitor = AndroidEntryPointManager.MANAGER.getProgressMonitor(); int monitorCounter = 0; { // Make Mini-Models to override to for (final AndroidComponent target : AndroidComponent.values()) { if (AndroidEntryPointManager.EPContainAny(target)) { final AndroidModel targetModel = new UnknownTargetModel(this.cha, this.options, this.cache, target); callTo.put(target, targetModel); } else { final AndroidModel targetModel = new ExternalModel(this.cha, this.options, this.cache, target); callTo.put(target, targetModel); } } } { // Fill overrides final IntentStarters starters = new IntentStarters(this.cha); final Set<Selector> methodsToOverride = starters.getKnownMethods(); monitor.beginTask("Context-Free overrides", methodsToOverride.size()); for (final Selector mSel : methodsToOverride) { monitor.subTask(mSel.getName().toString()); final IntentStarters.StartInfo info = starters.getInfo(mSel); info.setContextFree(); final TypeReference inClass = info.getDeclaringClass(); if (inClass == null) { System.err.println("Class does not exist for " + info + " in " + mSel); continue; } final MethodReference overrideMe = MethodReference.findOrCreate(inClass, mSel); final Set<AndroidComponent> possibleTargets = info.getComponentsPossible(); assert (possibleTargets.size() == 1); for (final AndroidComponent target : possibleTargets) { final AndroidModel targetModel = callTo.get(target); final SummarizedMethod override = targetModel.getMethodAs( overrideMe, this.caller.getMethod().getReference().getDeclaringClass(), info, /* callerNd = */ null); overrides.put(overrideMe, override); } monitor.worked(++monitorCounter); } } { // Generate the MethodTargetSelector to return // XXX: Are these necessary ?: // final BypassSyntheticClassLoader syntheticLoader = (BypassSyntheticClassLoader) // cha.getLoader( // new ClassLoaderReference (Atom.findOrCreateUnicodeAtom("Synthetic"), // ClassLoaderReference.Java, null)); // syntheticLoader.registerClass(override.getDeclaringClass().getName(), // override.getDeclaringClass()); // cha.addClass(override.getDeclaringClass()); final StartComponentMethodTargetSelector MTSel = new StartComponentMethodTargetSelector(overrides, options.getMethodTargetSelector()); monitor.done(); return MTSel; } } }
9,918
36.430189
100
java
WALA
WALA-master/dalvik/src/main/java/com/ibm/wala/dalvik/ipa/callgraph/androidModel/stubs/SystemServiceModel.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.androidModel.stubs; import com.ibm.wala.classLoader.IClass; import com.ibm.wala.core.util.ssa.ParameterAccessor; import com.ibm.wala.core.util.ssa.SSAValue; import com.ibm.wala.core.util.ssa.SSAValueManager; import com.ibm.wala.core.util.ssa.TypeSafeInstructionFactory; import com.ibm.wala.core.util.strings.Atom; import com.ibm.wala.dalvik.ipa.callgraph.androidModel.AndroidModel; import com.ibm.wala.dalvik.ipa.callgraph.androidModel.AndroidModelClass; import com.ibm.wala.dalvik.ipa.callgraph.androidModel.parameters.Instantiator; import com.ibm.wala.dalvik.ipa.callgraph.impl.AndroidEntryPoint; import com.ibm.wala.dalvik.util.AndroidTypes; import com.ibm.wala.ipa.callgraph.AnalysisOptions; import com.ibm.wala.ipa.callgraph.IAnalysisCacheView; import com.ibm.wala.ipa.cha.IClassHierarchy; import com.ibm.wala.ipa.summaries.MethodSummary; import com.ibm.wala.ipa.summaries.SummarizedMethod; import com.ibm.wala.ipa.summaries.VolatileMethodSummary; import com.ibm.wala.ssa.ConstantValue; import com.ibm.wala.ssa.SSAInstruction; import com.ibm.wala.types.ClassLoaderReference; import com.ibm.wala.types.Descriptor; import com.ibm.wala.types.MethodReference; import com.ibm.wala.types.Selector; import com.ibm.wala.types.TypeName; import com.ibm.wala.types.TypeReference; import com.ibm.wala.util.CancelException; import java.util.Collection; import java.util.HashSet; /** * This is generates a dummy for the call to an external Activity. * * <p>Is used by the IntentContextInterpreter if an Intent is marked as beeing external. * * @see com.ibm.wala.dalvik.ipa.callgraph.propagation.cfa.IntentContextInterpreter * @author Tobias Blaschke &lt;code@tobiasblaschke.de&gt; * @since 2013-10-15 */ public class SystemServiceModel extends AndroidModel { public final Atom name; private SummarizedMethod activityModel; private final String target; // uses AndroidModel.cha; /** * Do not call any EntryPoint. * * <p>{@inheritDoc} */ @Override protected boolean selectEntryPoint(AndroidEntryPoint ep) { return false; } public SystemServiceModel( final IClassHierarchy cha, final AnalysisOptions options, final IAnalysisCacheView cache, Atom target) { super(cha, options, cache); if (target == null) { throw new IllegalArgumentException( "The target requested to create an SystemServiceModel for was null"); } String sName = target.toString(); String cName = Character.toUpperCase(sName.charAt(0)) + sName.substring(1); this.name = Atom.findOrCreateAsciiAtom("startSystemService" + cName); this.target = target.toString(); } // @Override private void register(SummarizedMethod model) { AndroidModelClass mClass = AndroidModelClass.getInstance(cha); if (!mClass.containsMethod(model.getSelector())) { mClass.addMethod(model); } } @Override public SummarizedMethod getMethod() throws CancelException { if (!built) { super.build(this.name); this.register(super.model); this.activityModel = super.model; } return this.activityModel; } @Override protected void build(Atom name, Collection<? extends AndroidEntryPoint> entrypoints) { assert ((entrypoints == null) || !entrypoints.iterator().hasNext()); final Descriptor descr = Descriptor.findOrCreate( new TypeName[] {AndroidTypes.ContextName}, TypeName.string2TypeName("Ljava/lang/Object")); this.mRef = MethodReference.findOrCreate(AndroidModelClass.ANDROID_MODEL_CLASS, name, descr); final Selector selector = new Selector(name, descr); // Assert not registered yet final AndroidModelClass mClass = AndroidModelClass.getInstance(this.cha); if (mClass.containsMethod(selector)) { this.model = (SummarizedMethod) mClass.getMethod(selector); return; } this.body = new VolatileMethodSummary(new MethodSummary(this.mRef)); this.body.setStatic(true); populate(null); this.klass = AndroidModelClass.getInstance(this.cha); this.model = new SummarizedMethod(this.mRef, this.body.getMethodSummary(), this.klass) { @Override public TypeReference getParameterType(int i) { IClassHierarchy cha = getClassHierarchy(); TypeReference tRef = super.getParameterType(i); if (tRef.isClassType()) { if (cha.lookupClass(tRef) != null) { return tRef; } else { for (IClass c : cha) { if (c.getName().toString().equals(tRef.getName().toString())) { return c.getReference(); } } } throw new IllegalStateException("Error looking up " + tRef); } else { return tRef; } } }; this.built = true; } /** * Fill the model with instructions. * * <p>TODO: use "global" instances */ // @Override private void populate(Iterable<? extends AndroidEntryPoint> entrypoints) { assert ((entrypoints == null) || !entrypoints.iterator().hasNext()); assert !built : "You can only build once"; final TypeSafeInstructionFactory instructionFactory = new TypeSafeInstructionFactory(getClassHierarchy()); final VolatileMethodSummary body = this.body; final ParameterAccessor pAcc = new ParameterAccessor(this.mRef, /* hasImplicitThis */ false); final SSAValueManager pm = new SSAValueManager(pAcc); final Instantiator instantiator = new Instantiator(body, instructionFactory, pm, cha, mRef, scope); // final SSAValue context = pAcc.firstOf(AndroidTypes.ContextName); final SSAValue retVal; switch (this.target) { case "phone": retVal = instantiator.createInstance( AndroidTypes.TelephonyManager, false, new SSAValue.UniqueKey(), new HashSet<>(pAcc.all())); // } else if (this.target.equals("Lwindow")) { // TODO: Is an interface // // final TypeName wmN = TypeName.findOrCreate("Landroid/view/WindowManager"); // final TypeReference wmT = TypeReference.findOrCreate(ClassLoaderReference.Primordial, // wmN); // retVal = instantiator.createInstance(wmT, false, new SSAValue.UniqueKey(), new // HashSet<Parameter>(pAcc.all())); // } else if (this.target.equals("Llayout_inflater")) { // } else if (this.target.equals("Lactivity")) { // } else if (this.target.equals("Lpower")) { // } else if (this.target.equals("Lalarm")) { // } else if (this.target.equals("Lnotification")) { break; case "keyguard": { final TypeName n = TypeName.findOrCreate("Landroid/app/KeyguardManager"); final TypeReference T = TypeReference.findOrCreate(ClassLoaderReference.Primordial, n); retVal = instantiator.createInstance( T, false, new SSAValue.UniqueKey(), new HashSet<>(pAcc.all())); break; } case "location": { final TypeName n = TypeName.findOrCreate("Landroid/location/LocationManager"); final TypeReference T = TypeReference.findOrCreate(ClassLoaderReference.Primordial, n); retVal = instantiator.createInstance( T, false, new SSAValue.UniqueKey(), new HashSet<>(pAcc.all())); break; } case "search": { // TODO: Param: Handler final TypeName n = TypeName.findOrCreate("Landroid/app/SearchManager"); final TypeReference T = TypeReference.findOrCreate(ClassLoaderReference.Primordial, n); retVal = instantiator.createInstance( T, false, new SSAValue.UniqueKey(), new HashSet<>(pAcc.all())); // } else if (this.target.equals("Lvibrator")) { // TODO: Is abstract break; } case "connection": { // TODO: use ConnectivityManager.from final TypeName n = TypeName.findOrCreate("Landroid/net/ConnectivityManager"); final TypeReference T = TypeReference.findOrCreate(ClassLoaderReference.Primordial, n); retVal = instantiator.createInstance( T, false, new SSAValue.UniqueKey(), new HashSet<>(pAcc.all())); break; } case "wifi": { // Handle Params: Context context, IWifiManager service final TypeName n = TypeName.findOrCreate("Landroid/net/wifi/WifiManager"); final TypeReference T = TypeReference.findOrCreate(ClassLoaderReference.Primordial, n); retVal = instantiator.createInstance( T, false, new SSAValue.UniqueKey(), new HashSet<>(pAcc.all())); break; } case "input_method": { // TODO: Use InputMethodManager.getInstance? final TypeName n = TypeName.findOrCreate("Landroid/view/inputmethod/InputMethodManager"); final TypeReference T = TypeReference.findOrCreate(ClassLoaderReference.Primordial, n); retVal = instantiator.createInstance( T, false, new SSAValue.UniqueKey(), new HashSet<>(pAcc.all())); break; } case "uimode": { final TypeName n = TypeName.findOrCreate("Landroid/app/UiModeManager"); final TypeReference T = TypeReference.findOrCreate(ClassLoaderReference.Primordial, n); retVal = instantiator.createInstance( T, false, new SSAValue.UniqueKey(), new HashSet<>(pAcc.all())); break; } case "download": { // TODO: Params ContentResolver resolver, String packageName final TypeName n = TypeName.findOrCreate("Landroid/app/DownloadManager"); final TypeReference T = TypeReference.findOrCreate(ClassLoaderReference.Primordial, n); retVal = instantiator.createInstance( T, false, new SSAValue.UniqueKey(), new HashSet<>(pAcc.all())); break; } default: retVal = pm.getUnmanaged(TypeReference.JavaLangObject, "notFound"); this.body.addConstant(retVal.getNumber(), new ConstantValue(null)); retVal.setAssigned(); break; } { // Add return statement on intent final int returnPC = this.body.getNextProgramCounter(); final SSAInstruction returnInstruction = instructionFactory.ReturnInstruction(returnPC, retVal); this.body.addStatement(returnInstruction); } } }
12,611
38.28972
99
java
WALA
WALA-master/dalvik/src/main/java/com/ibm/wala/dalvik/ipa/callgraph/androidModel/stubs/UnknownTargetModel.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.androidModel.stubs; import com.ibm.wala.classLoader.CallSiteReference; import com.ibm.wala.classLoader.IClass; import com.ibm.wala.classLoader.IMethod; import com.ibm.wala.core.util.ssa.ParameterAccessor; import com.ibm.wala.core.util.ssa.SSAValue; import com.ibm.wala.core.util.ssa.SSAValueManager; import com.ibm.wala.core.util.ssa.TypeSafeInstructionFactory; import com.ibm.wala.core.util.strings.Atom; import com.ibm.wala.dalvik.ipa.callgraph.androidModel.AndroidModel; import com.ibm.wala.dalvik.ipa.callgraph.androidModel.AndroidModelClass; import com.ibm.wala.dalvik.ipa.callgraph.androidModel.MiniModel; import com.ibm.wala.dalvik.ipa.callgraph.androidModel.parameters.Instantiator; import com.ibm.wala.dalvik.ipa.callgraph.impl.AndroidEntryPoint; 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.IAnalysisCacheView; import com.ibm.wala.ipa.cha.IClassHierarchy; import com.ibm.wala.ipa.summaries.MethodSummary; import com.ibm.wala.ipa.summaries.SummarizedMethod; import com.ibm.wala.ipa.summaries.VolatileMethodSummary; import com.ibm.wala.shrike.shrikeBT.IInvokeInstruction; import com.ibm.wala.ssa.SSAInstruction; import com.ibm.wala.types.Descriptor; import com.ibm.wala.types.MethodReference; import com.ibm.wala.types.TypeName; import com.ibm.wala.types.TypeReference; import com.ibm.wala.util.CancelException; import java.util.Arrays; import java.util.Collection; import java.util.HashSet; import java.util.List; import java.util.Set; /** * This Model is used to start an Android-Component of unknown Target. * * <p>All internal Components of a Type (if given) then an ExternalModel is called. Used by the * IntentContextInterpreter. * * @see com.ibm.wala.dalvik.ipa.callgraph.propagation.cfa.IntentContextInterpreter * @author Tobias Blaschke &lt;code@tobiasblaschke.de&gt; * @since 2013-10-18 */ public class UnknownTargetModel extends AndroidModel { public final Atom name; private boolean doMini = true; private MiniModel miniModel = null; private ExternalModel externalModel = null; private final AndroidComponent target; // uses AndroidModel.cha; /** * The UnknownTargetModel does not call any entrypoints on it's own. * * <p>Instead it first creates a restricted AndroidModel and an ExternalModel. These are actually * called. */ @Override protected boolean selectEntryPoint(AndroidEntryPoint ep) { return false; } /** @param target Component Type, may be null: No restrictions are imposed on AndroidModel then */ public UnknownTargetModel( final IClassHierarchy cha, final AnalysisOptions options, final IAnalysisCacheView cache, AndroidComponent target) { super(cha, options, cache); if (target == null) { // TODO: Enable throw new IllegalArgumentException( "The component type requested to create an UnknownTargetModel for was null"); } String sName = target.toString(); String cName = Character.toUpperCase(sName.charAt(0)) + sName.substring(1).toLowerCase(); this.name = Atom.findOrCreateAsciiAtom("startUnknown" + cName); this.target = target; // this.allInternal = new MiniModel(cha, options, cache, target); // this.external = new ExternalModel(cha, options, cache, target); } // @Override private void register(SummarizedMethod model) { AndroidModelClass mClass = AndroidModelClass.getInstance(cha); if (!mClass.containsMethod(model.getSelector())) { mClass.addMethod(model); } } @Override public SummarizedMethod getMethod() throws CancelException { if (!built) { super.build(this.name); this.register(super.model); } return super.model; } @Override protected void build(Atom name, Collection<? extends AndroidEntryPoint> entrypoints) throws CancelException { assert ((entrypoints == null) || !entrypoints.iterator().hasNext()); { // Check if this Application has components, that implement target. If not we don't // have to build a MiniModel. doMini = false; for (final AndroidEntryPoint ep : AndroidEntryPointManager.ENTRIES) { if (ep.belongsTo(this.target)) { doMini = true; break; } } } if (doMini) { miniModel = new MiniModel(this.cha, this.options, this.cache, this.target); } externalModel = new ExternalModel(this.cha, this.options, this.cache, this.target); final Descriptor descr; // final Selector selector; { if (doMini) { final TypeName[] othersA = miniModel.getDescriptor().getParameters(); final Set<TypeName> others; if (othersA != null) { others = new HashSet<>(Arrays.asList(othersA)); } else { others = new HashSet<>(); } doMini = others.size() > 0; others.addAll(Arrays.asList(externalModel.getDescriptor().getParameters())); descr = Descriptor.findOrCreate( others.toArray(new TypeName[] {}), TypeReference.VoidName); // Return the intent of external? TODO } else { descr = Descriptor.findOrCreate( externalModel.getDescriptor().getParameters(), TypeReference.VoidName); } // selector = new Selector(name, descr); } /*{ // Skip construction if there already exists a model wit this name. This should // not happen. final AndroidModelClass mClass = AndroidModelClass.getInstance(this.cha); if (mClass.containsMethod(selector)) { this.built = true; this.model = (SummarizedMethod) mClass.getMethod(selector); return; } } // */ { // Set some properties of the later method this.klass = AndroidModelClass.getInstance(this.cha); this.mRef = MethodReference.findOrCreate(AndroidModelClass.ANDROID_MODEL_CLASS, name, descr); this.body = new VolatileMethodSummary(new MethodSummary(this.mRef)); this.body.setStatic(true); } { // Start building populate(null); this.model = new SummarizedMethod(this.mRef, this.body.getMethodSummary(), this.klass) { @Override public TypeReference getParameterType(int i) { IClassHierarchy cha = getClassHierarchy(); TypeReference tRef = super.getParameterType(i); if (tRef.isClassType()) { if (cha.lookupClass(tRef) != null) { return tRef; } else { for (IClass c : cha) { if (c.getName().toString().equals(tRef.getName().toString())) { return c.getReference(); } } } throw new IllegalStateException("Error looking up " + tRef); } else { return tRef; } } }; // of this.model } this.built = true; } /** * Fill the model with instructions. * * <p>Call both models: ExternalModel, MiniModel */ // @Override private void populate(Iterable<? extends AndroidEntryPoint> entrypoints) throws CancelException { assert ((entrypoints == null) || !entrypoints.iterator().hasNext()); assert !built : "You can only build once"; final TypeSafeInstructionFactory instructionFactory = new TypeSafeInstructionFactory(this.cha); final ParameterAccessor pAcc = new ParameterAccessor(this.mRef, /* hasImplicitThis */ false); final SSAValueManager pm = new SSAValueManager(pAcc); final Instantiator instantiator = new Instantiator(this.body, instructionFactory, pm, this.cha, this.mRef, this.scope); if (doMini) { // Call a MiniModel // final MiniModel miniModel = new MiniModel(this.cha, this.options, this.cache, this.target); final IMethod mini = miniModel.getMethod(); final ParameterAccessor miniAcc = new ParameterAccessor(mini); final List<SSAValue> params = pAcc.connectThrough(miniAcc, null, null, this.cha, instantiator, false, null, null); final SSAValue excpetion = pm.getException(); final int pc = this.body.getNextProgramCounter(); final CallSiteReference site = CallSiteReference.make(pc, mini.getReference(), IInvokeInstruction.Dispatch.STATIC); final SSAInstruction invokation = instructionFactory.InvokeInstruction(pc, params, excpetion, site); this.body.addStatement(invokation); } final SSAValue extRet; { // Call the externalTarget Model // final ExternalModel externalModel = new ExternalModel(this.cha, this.options, this.cache, // this.target); final IMethod external = externalModel.getMethod(); final ParameterAccessor externalAcc = new ParameterAccessor(external); final List<SSAValue> params = pAcc.connectThrough(externalAcc, null, null, this.cha, instantiator, false, null, null); final SSAValue excpetion = pm.getException(); extRet = pm.getUnmanaged(external.getReturnType(), "extRet"); final int pc = this.body.getNextProgramCounter(); final CallSiteReference site = CallSiteReference.make(pc, external.getReference(), IInvokeInstruction.Dispatch.STATIC); final SSAInstruction invokation = instructionFactory.InvokeInstruction(pc, extRet, params, excpetion, site); this.body.addStatement(invokation); } // TODO: Do somethig with extRet? this.body.setLocalNames(pm.makeLocalNames()); } /* final ParameterAccessor internalAcc = new ParameterAccessor(this.allInternal.getMethod()); final ParameterAccessor externalAcc = new ParameterAccessor(this.external.getMethod()); final ParameterAccessor thisAcc = new ParameterAccessor(this.mRef, false); final SSAValueManager pm = new SSAValueManager(thisAcc); final JavaInstructionFactory instructionFactory = new JavaInstructionFactory(); // TODO: Use a typesafe factory? final Instantiator instantiator = new Instantiator(this.body, new TypeSafeInstructionFactory(getClassHierarchy()), pm, getClassHierarchy(), this.mRef, this.scope); int nextLocal = thisAcc.getFirstAfter(); // TODO: Use manager? final List<SSAValue> internalArgs; { // Call the MiniModel // Map through the parameters of this.mRef to this.allInternal final List<SSAValue> args = thisAcc.connectThrough(internalAcc, null, null, getClassHierarchy(), instantiator, false, null, null); internalArgs = args; final IMethod allInternalMethod = this.allInternal.getMethod(); { logger.debug("Calling {} using {}", this.allInternal.getMethod(), args); final int callPC = this.body.getNextProgramCounter(); final CallSiteReference site = CallSiteReference.make(callPC, allInternalMethod.getReference(), IInvokeInstruction.Dispatch.STATIC); final int exception = nextLocal++; assert (exception > 0); final SSAInstruction invokation = instructionFactory.InvokeInstruction(callPC, internalAcc.forInvokeStatic(args), exception, site); this.body.addStatement(invokation); } } final int externalReturnIntent = nextLocal++; { // Call the external model final List<SSAValue> args = thisAcc.connectThrough(externalAcc, null, null , getClassHierarchy(), instantiator, false, null, null); final IMethod externalMethod = this.external.getMethod(); { final int callPC = this.body.getNextProgramCounter(); final CallSiteReference site = CallSiteReference.make(callPC, externalMethod.getReference(), IInvokeInstruction.Dispatch.STATIC); final int exception = nextLocal++; final SSAInstruction invokation = instructionFactory.InvokeInstruction(callPC, externalReturnIntent, externalAcc.forInvokeStatic(args), exception, site); this.body.addStatement(invokation); } } // TODO: Phi-Together returnIntents and return it. Or at least handle external }*/ }
14,344
40.340058
127
java
WALA
WALA-master/dalvik/src/main/java/com/ibm/wala/dalvik/ipa/callgraph/androidModel/stubs/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. */ /** * Contains functions inserted into the AndroidModel. * * <p>Various function calls, getters and setters are moved from the AndroidModel here to keep the * model-code itself more clear. This stubs should not be of that grat use besides in the * AndroidModel itself. * * <p>Context-Free Overrides of startCompontent-functions are handled here. Context-Sensitive * overrides may be found in the cfa-package mentioned below. * * @see com.ibm.wala.dalvik.ipa.callgraph.propagation.cfa * @since 2013-10-25 * @author Tobias Blaschke &lt;code@tobiasblaschke.de&gt; */ package com.ibm.wala.dalvik.ipa.callgraph.androidModel.stubs;
2,524
44.089286
98
java
WALA
WALA-master/dalvik/src/main/java/com/ibm/wala/dalvik/ipa/callgraph/impl/AndroidEntryPoint.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.impl; import com.ibm.wala.classLoader.IMethod; import com.ibm.wala.core.util.strings.Atom; import com.ibm.wala.dalvik.util.AndroidComponent; import com.ibm.wala.dalvik.util.AndroidEntryPointLocator.AndroidPossibleEntryPoint; import com.ibm.wala.dalvik.util.AndroidTypes; import com.ibm.wala.ipa.cha.IClassHierarchy; import com.ibm.wala.types.TypeReference; import java.util.Comparator; /** * An AdnroidEntryPoint is basically the same as a DexEntryPoint. The Difference is, that further * actions are taken to give a list of EntryPoints a specific order an to add information on how the * entrypoints are to be called in a model which represents the usage of an android application. * * <p>You might want to use AndroidEntryPointLocator to generate a list of all EntryPoints in an * android application * * @see com.ibm.wala.dalvik.util.AndroidEntryPointLocator * @author Tobias Blaschke &lt;code@toiasblaschke.de&gt; * @since 2013-09-01 */ public class AndroidEntryPoint extends DexEntryPoint { // implements AndroidEntryPoint.IExecutionOrder { public ExecutionOrder order; // XXX protect? protected AndroidComponent superType; public AndroidEntryPoint( AndroidPossibleEntryPoint p, IMethod method, IClassHierarchy cha, AndroidComponent inComponent) { super(method, cha); this.order = p.order; this.superType = inComponent; } public AndroidEntryPoint(AndroidPossibleEntryPoint p, IMethod method, IClassHierarchy cha) { super(method, cha); this.order = p.order; this.superType = AndroidComponent.from(method, cha); } public AndroidEntryPoint( ExecutionOrder o, IMethod method, IClassHierarchy cha, AndroidComponent inComponent) { this(o, method, cha); this.superType = inComponent; } public AndroidEntryPoint(ExecutionOrder o, IMethod method, IClassHierarchy cha) { super(method, cha); if (o == null) { throw new IllegalArgumentException("The execution order may not be null."); } this.order = o; this.superType = AndroidComponent.from(method, cha); } public AndroidComponent getComponent() { return this.superType; } /** If the function is defined in a class that extends an Activity. */ public boolean isActivity() { IClassHierarchy cha = getClassHierarchy(); final TypeReference activity = AndroidTypes.Activity; return cha.isSubclassOf(method.getDeclaringClass(), cha.lookupClass(activity)); } public boolean belongsTo(AndroidComponent compo) { if ((compo == AndroidComponent.SERVICE) && this.superType.equals(AndroidComponent.INTENT_SERVICE)) { return true; } return this.superType.equals(compo); } public boolean isMemberOf(Atom klass) { return method.getDeclaringClass().getName().toString().startsWith(klass.toString()); // IClassHierarchy cha = getClassHierarchy(); // final TypeReference type = TypeReference.find(ClassLoaderReference.Primordial, // klass.toString()); // if (type == null) { // throw new IllegalArgumentException("Unable to look up " + klass.toString()); // } // return cha.isSubclassOf(method.getDeclaringClass(), cha.lookupClass(type)); } /** * Implement this interface to put entitys into the AndroidModel. * * <p>Currently only AndroidEntryPoints are supportet directly. If you want to add other stuff you * might want to subclass AbstractAndroidModel. */ public interface IExecutionOrder extends Comparable<IExecutionOrder> { /** Returns an integer-representation of the ExecutionOrder. */ int getOrderValue(); /** * AbstractAndroidModel inserts code at section switches. * * <p>There are eight hardcoded sections. Sections are derived by rounding the * integer-representation. * * @return the section of this entity */ ExecutionOrder getSection(); } /** AndroidEntryPoints have to be sorted before building the model. */ public static class ExecutionOrderComperator implements Comparator<AndroidEntryPoint> { @Override public int compare(AndroidEntryPoint a, AndroidEntryPoint b) { return a.order.compareTo(b.order); } } /** * The section is used to build classes of EntryPoints on how they are to be called. * * <p>The section is represented by the last label passed before the entity is reached. * * @return the section of this entrypoint */ public ExecutionOrder getSection() { if (this.order.compareTo(ExecutionOrder.BEFORE_LOOP) < 0) return ExecutionOrder.AT_FIRST; if (this.order.compareTo(ExecutionOrder.START_OF_LOOP) < 0) return ExecutionOrder.BEFORE_LOOP; if (this.order.compareTo(ExecutionOrder.MIDDLE_OF_LOOP) < 0) return ExecutionOrder.START_OF_LOOP; if (this.order.compareTo(ExecutionOrder.MULTIPLE_TIMES_IN_LOOP) < 0) return ExecutionOrder.MIDDLE_OF_LOOP; if (this.order.compareTo(ExecutionOrder.END_OF_LOOP) < 0) return ExecutionOrder.MULTIPLE_TIMES_IN_LOOP; if (this.order.compareTo(ExecutionOrder.AFTER_LOOP) < 0) return ExecutionOrder.END_OF_LOOP; if (this.order.compareTo(ExecutionOrder.AT_LAST) < 0) return ExecutionOrder.AFTER_LOOP; return ExecutionOrder.AT_LAST; } public int getOrderValue() { return order.getOrderValue(); } public int compareTo(AndroidEntryPoint.IExecutionOrder o) { return this.order.compareTo(o); } /** * The ExecutionOrder is used to partially order EntryPoints. * * <p>The order has to be understood inclusive! E.g. "after(END_OF_LOOP)" means that the position * is __BEFORE__ the loop is actually closed! * * <p>Before building the model a list of AdroidEntryPoints is to be sorted by that criterion. You * can use AndroidEntryPoint.ExecutionOrderComperator for that task. */ public static class ExecutionOrder implements IExecutionOrder { // This is an Enum-Style class /** Visit the EntryPoint once at the beginning of the model use that for initialization stuff */ public static final ExecutionOrder AT_FIRST = new ExecutionOrder(0); /** Basicly the same as AT_FIRST but visited after AT_FIRST */ public static final ExecutionOrder BEFORE_LOOP = new ExecutionOrder(Integer.MAX_VALUE / 8); /** Visit multiple times (endless) in the loop */ public static final ExecutionOrder START_OF_LOOP = new ExecutionOrder(Integer.MAX_VALUE / 8 * 2); /** Basicly the same as START_OF_LOOP */ public static final ExecutionOrder MIDDLE_OF_LOOP = new ExecutionOrder(Integer.MAX_VALUE / 8 * 3); /** Do multiple calls in the loop. Visited after MIDDLE_OF_LOOP, before EEN_OF_LOOP */ public static final ExecutionOrder MULTIPLE_TIMES_IN_LOOP = new ExecutionOrder(Integer.MAX_VALUE / 8 * 4); /** * Things in END_OF_LOOP are acutually part of the loop. Use AFTER_LOOP if you want them * executed only once */ public static final ExecutionOrder END_OF_LOOP = new ExecutionOrder(Integer.MAX_VALUE / 8 * 5); /** Basicly the same as AT_LAST but visited before */ public static final ExecutionOrder AFTER_LOOP = new ExecutionOrder(Integer.MAX_VALUE / 8 * 6); /** Last calls in the model */ public static final ExecutionOrder AT_LAST = new ExecutionOrder(Integer.MAX_VALUE / 8 * 7); /** This value getts used by the detection heuristic - It is not recommended for manual use. */ public static final ExecutionOrder DEFAULT = MIDDLE_OF_LOOP; private final int value; /** * Unrecommended way to generate the Order based on an Integer. * * <p>This method is handy when reading back files. In your code you should prefer the methods * {@link #after(com.ibm.wala.dalvik.ipa.callgraph.impl.AndroidEntryPoint.IExecutionOrder)} and * {@link #between(com.ibm.wala.dalvik.ipa.callgraph.impl.AndroidEntryPoint.IExecutionOrder, * com.ibm.wala.dalvik.ipa.callgraph.impl.AndroidEntryPoint.IExecutionOrder)}. */ public ExecutionOrder(int val) { this.value = val; } /** * Unrecommended way to generate the Order based on a Label-String. * * <p>This method is handy when reading back files. If you want to refer to a label you should * prefer the static members. */ public ExecutionOrder(String label) { if (label.equals("AT_FIRST")) { this.value = ExecutionOrder.AT_FIRST.getOrderValue(); return; } if (label.equals("BEFORE_LOOP")) { this.value = ExecutionOrder.BEFORE_LOOP.getOrderValue(); return; } if (label.equals("START_OF_LOOP")) { this.value = ExecutionOrder.START_OF_LOOP.getOrderValue(); return; } if (label.equals("MIDDLE_OF_LOOP")) { this.value = ExecutionOrder.MIDDLE_OF_LOOP.getOrderValue(); return; } if (label.equals("MULTIPLE_TIMES_IN_LOOP")) { this.value = ExecutionOrder.MULTIPLE_TIMES_IN_LOOP.getOrderValue(); return; } if (label.equals("END_OF_LOOP")) { this.value = ExecutionOrder.END_OF_LOOP.getOrderValue(); return; } if (label.equals("AFTER_LOOP")) { this.value = ExecutionOrder.AFTER_LOOP.getOrderValue(); return; } if (label.equals("AT_LAST")) { this.value = ExecutionOrder.AT_LAST.getOrderValue(); return; } throw new IllegalArgumentException( "ExecutionOrder was constructed from an illegal label: " + label); } @Override public int getOrderValue() { return this.value; } /** * Use {@link #between(IExecutionOrder, IExecutionOrder)} instead. * * <p>Does the internal calculations for the placement. */ private static ExecutionOrder between(int after, int before) { if ((before - after) == 1) { // It could be ok to warn here instead of throwing: Functions would be located at the same // 'slot' in this case. // An alternative solution could be to choose other values for before or after. throw new ArithmeticException( "Precision to low when cascading the ExecutionOrder. You can prevent this error by " + "assigning the ExecutionOrders (e.g. using before() and after()) in a different order."); } if (after > before) { throw new IllegalArgumentException( "The requested ordering could not be established due to the after-parameter " + "being greater than the before parameter! after=" + after + " before=" + before); } return new ExecutionOrder(after + (before - after) / 2); } /** * Use this to place a call to an EntryPoint between two other EntryPoint calls or * ExecutionOrder "labels". between() does not care about section-boundaries by itself! * * <p>Use {@link * #between(com.ibm.wala.dalvik.ipa.callgraph.impl.AndroidEntryPoint.IExecutionOrder[], * com.ibm.wala.dalvik.ipa.callgraph.impl.AndroidEntryPoint.IExecutionOrder[])} and use labels * as additional placement-information to prevent unexpected misplacement. * * @param after the call or "label" to be executed before this one * @param before the call or "label" to be executed after this one (inclusive) * @return A sortable object to represent the execution order * @throws ArithmeticException when the precision is no more suitable for further cascading * @throws IllegalArgumentException if parameter after is larger than before. * @throws NullPointerException if either parameter is null */ public static ExecutionOrder between(IExecutionOrder after, IExecutionOrder before) { if (after == null) { throw new NullPointerException("after may not be null"); } if (before == null) { throw new NullPointerException("after may not be null"); } return between(after.getOrderValue(), before.getOrderValue()); } /** Helper for internal use. */ private static ExecutionOrder between(IExecutionOrder after, int before) { return between(after.getOrderValue(), before); } /** * Use this variant to refer to multiple locations. * * <p>The minimum / maximum is computed before the placement of the ExecutionOrder. * * <p>This method is intended to be more robust when changing the position-information of * referred-to ExecutionOrders. * * <p>In any other means it behaves exactly like {@link * #between(com.ibm.wala.dalvik.ipa.callgraph.impl.AndroidEntryPoint.IExecutionOrder, * com.ibm.wala.dalvik.ipa.callgraph.impl.AndroidEntryPoint.IExecutionOrder)}. * * @param after the calls or "labels" to be executed before this one * @param before the calls or "labels" to be executed after this one (inclusive) * @return A sortable object to represent the execution order * @throws ArithmeticException when the precision is no more suitable for further cascading * @throws IllegalArgumentException if parameter after is larger than before. * @throws NullPointerException if either parameter is null */ public static ExecutionOrder between(IExecutionOrder[] after, IExecutionOrder[] before) { if ((after == null) || (after.length == 0)) { throw new NullPointerException("after may not be null or empty array"); } if ((before == null) || (before.length == 0)) { throw new NullPointerException("before may not be null or empty array"); } int max = Integer.MIN_VALUE; int min = Integer.MAX_VALUE; for (IExecutionOrder i : after) if (max < i.getOrderValue()) max = i.getOrderValue(); for (IExecutionOrder i : before) if (min > i.getOrderValue()) min = i.getOrderValue(); return between(max, min); } public static ExecutionOrder between(IExecutionOrder after, IExecutionOrder[] before) { if ((before == null) || (before.length == 0)) { throw new NullPointerException("after may not be null or empty array"); } int min = Integer.MAX_VALUE; for (IExecutionOrder i : before) if (min > i.getOrderValue()) min = i.getOrderValue(); return between(after, min); } public static ExecutionOrder between(IExecutionOrder[] after, IExecutionOrder before) { if ((after == null) || (after.length == 0)) { throw new NullPointerException("after may not be null or empty array"); } if (before == null) { throw new NullPointerException("before may not be null"); } int max = Integer.MIN_VALUE; for (IExecutionOrder i : after) if (max < i.getOrderValue()) max = i.getOrderValue(); return between(max, before.getOrderValue()); } /** * Place the call in the same section after the given call or "label". * * @param after the call to be executed before this one or label the call belongs to * @return A sortable object to represent the execution order * @throws ArithmeticException when the precision is no more suitable for further cascading * @throws NullPointerException if the parameter is null */ public static ExecutionOrder after(IExecutionOrder after) { if (after == null) { throw new NullPointerException("after may not be null"); } return after(after.getOrderValue()); } /** * Prefer {@link * #after(com.ibm.wala.dalvik.ipa.callgraph.impl.AndroidEntryPoint.IExecutionOrder)} whenever * possible. */ public static ExecutionOrder after(int after) { return between(after, ((after / (Integer.MAX_VALUE / 8)) + 1) * (Integer.MAX_VALUE / 8)); } /** * Use this variant to refer to multiple locations. * * <p>The maximum is computed before the placement of the ExecutionOrder. * * @param after the call to be executed before this one or label the call belongs to * @return A sortable object to represent the execution order * @throws ArithmeticException when the precision is no more suitable for further cascading * @throws NullPointerException if the parameter is null */ public static ExecutionOrder after(IExecutionOrder[] after) { if (after == null) { throw new NullPointerException("after may not be null"); } int max = Integer.MIN_VALUE; for (IExecutionOrder i : after) if (max < i.getOrderValue()) max = i.getOrderValue(); return after(max); } public static ExecutionOrder directlyBefore(IExecutionOrder before) { return new ExecutionOrder(before.getOrderValue() - 1); } public static ExecutionOrder directlyAfter(IExecutionOrder before) { return new ExecutionOrder(before.getOrderValue() + 1); } @Override public ExecutionOrder getSection() { if (this.compareTo(ExecutionOrder.BEFORE_LOOP) < 0) return ExecutionOrder.AT_FIRST; if (this.compareTo(ExecutionOrder.START_OF_LOOP) < 0) return ExecutionOrder.BEFORE_LOOP; if (this.compareTo(ExecutionOrder.MIDDLE_OF_LOOP) < 0) return ExecutionOrder.START_OF_LOOP; if (this.compareTo(ExecutionOrder.MULTIPLE_TIMES_IN_LOOP) < 0) return ExecutionOrder.MIDDLE_OF_LOOP; if (this.compareTo(ExecutionOrder.END_OF_LOOP) < 0) return ExecutionOrder.MULTIPLE_TIMES_IN_LOOP; if (this.compareTo(ExecutionOrder.AFTER_LOOP) < 0) return ExecutionOrder.END_OF_LOOP; if (this.compareTo(ExecutionOrder.AT_LAST) < 0) return ExecutionOrder.AFTER_LOOP; return ExecutionOrder.AT_LAST; } @Override public int compareTo(IExecutionOrder o) { return this.value - o.getOrderValue(); } @Override public String toString() { if (this.compareTo(ExecutionOrder.AT_FIRST) == 0) return "ExecutionOrder.AT_FIRST"; if (this.compareTo(ExecutionOrder.BEFORE_LOOP) == 0) return "ExecutionOrder.BEFORE_LOOP"; if (this.compareTo(ExecutionOrder.START_OF_LOOP) == 0) return "ExecutionOrder.START_OF_LOOP"; if (this.compareTo(ExecutionOrder.MIDDLE_OF_LOOP) == 0) return "ExecutionOrder.MIDDLE_OF_LOOP"; if (this.compareTo(ExecutionOrder.MULTIPLE_TIMES_IN_LOOP) == 0) return "ExecutionOrder.MULTIPLE_TIMES_IN_LOOP"; if (this.compareTo(ExecutionOrder.END_OF_LOOP) == 0) return "ExecutionOrder.END_OF_LOOP"; if (this.compareTo(ExecutionOrder.AFTER_LOOP) == 0) return "ExecutionOrder.AFTER_LOOP"; if (this.compareTo(ExecutionOrder.AT_LAST) == 0) return "ExecutionOrder.AT_LAST"; if (this.compareTo(ExecutionOrder.BEFORE_LOOP) < 0) return "in section ExecutionOrder.AT_FIRST"; if (this.compareTo(ExecutionOrder.START_OF_LOOP) < 0) return "in section ExecutionOrder.BEFORE_LOOP"; if (this.compareTo(ExecutionOrder.MIDDLE_OF_LOOP) < 0) return "in section ExecutionOrder.START_OF_LOOP"; if (this.compareTo(ExecutionOrder.MULTIPLE_TIMES_IN_LOOP) < 0) return "in section ExecutionOrder.MIDDLE_OF_LOOP"; if (this.compareTo(ExecutionOrder.END_OF_LOOP) < 0) return "in section ExecutionOrder.MULTIPLE_TIMES_IN_LOOP"; if (this.compareTo(ExecutionOrder.AFTER_LOOP) < 0) return "in section ExecutionOrder.END_OF_LOOP"; if (this.compareTo(ExecutionOrder.AT_LAST) < 0) return "in section ExecutionOrder.AFTER_LOOP"; return "in section ExecutionOrder.AT_LAST"; } } @Override public boolean equals(Object o) { if (o instanceof AndroidEntryPoint) { AndroidEntryPoint other = (AndroidEntryPoint) o; return this.getMethod().equals(other.getMethod()); } else { return false; } } @Override public int hashCode() { return 3 * this.getMethod().hashCode(); } }
21,682
41.515686
107
java
WALA
WALA-master/dalvik/src/main/java/com/ibm/wala/dalvik/ipa/callgraph/impl/DexEntryPoint.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, * * <p>Galois, Inc. (Aaron Tomb <atomb@galois.com>, Rogan Creswick <creswick@galois.com>) Steve Suh * <suhsteve@gmail.com> * * <p>All rights reserved. * * <p>Redistribution and use in source and binary forms, with or without modification, are permitted * provided that the following conditions are met: * * <p>1. Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. * * <p>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. * * <p>3. The names of the contributors may not be used to endorse or promote products derived from * this software without specific prior written permission. * * <p>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.impl; import com.ibm.wala.classLoader.IMethod; import com.ibm.wala.ipa.callgraph.impl.DefaultEntrypoint; import com.ibm.wala.ipa.cha.IClassHierarchy; import com.ibm.wala.ipa.cha.IClassHierarchyDweller; import com.ibm.wala.types.MethodReference; import com.ibm.wala.types.TypeReference; public class DexEntryPoint extends DefaultEntrypoint implements IClassHierarchyDweller { /* BEGIN Custom change */ private final IClassHierarchy cha; /* END Custom change */ public DexEntryPoint(IMethod method, IClassHierarchy cha) { super(method, cha); /* BEGIN Custom change */ this.cha = cha; /* END Custom change */ // TODO Auto-generated constructor stub } public DexEntryPoint(MethodReference method, IClassHierarchy cha) { super(method, cha); /* BEGIN Custom change */ this.cha = cha; /* END Custom change */ // TODO Auto-generated constructor stub } /* BEGIN Custom change */ @Override public IClassHierarchy getClassHierarchy() { return cha; } /* END Custom change */ @Override protected TypeReference[] makeParameterTypes(IMethod method, int i) { TypeReference[] trA = new TypeReference[] {method.getParameterType(i)}; return trA; } }
3,228
38.864198
100
java