1579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson/*
2579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson * Copyright (C) 2011 The Android Open Source Project
3579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson *
4579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson * Licensed under the Apache License, Version 2.0 (the "License");
5579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson * you may not use this file except in compliance with the License.
6579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson * You may obtain a copy of the License at
7579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson *
8579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson *      http://www.apache.org/licenses/LICENSE-2.0
9579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson *
10579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson * Unless required by applicable law or agreed to in writing, software
11579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson * distributed under the License is distributed on an "AS IS" BASIS,
12579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson * See the License for the specific language governing permissions and
14579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson * limitations under the License.
15579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson */
16579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson
17579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilsonpackage com.google.dexmaker;
18579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson
19579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilsonimport com.android.dx.dex.DexFormat;
20579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilsonimport com.android.dx.dex.DexOptions;
21579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilsonimport com.android.dx.dex.code.DalvCode;
22579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilsonimport com.android.dx.dex.code.PositionList;
23579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilsonimport com.android.dx.dex.code.RopTranslator;
24579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilsonimport com.android.dx.dex.file.ClassDefItem;
25579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilsonimport com.android.dx.dex.file.DexFile;
26579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilsonimport com.android.dx.dex.file.EncodedField;
27579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilsonimport com.android.dx.dex.file.EncodedMethod;
285624228626d7cdf206de25a6981ba8107be61057Jesse Wilsonimport com.android.dx.rop.code.AccessFlags;
2990699b97998f1582a921202fb909f17f9718d177Jesse Wilsonimport static com.android.dx.rop.code.AccessFlags.ACC_CONSTRUCTOR;
30579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilsonimport com.android.dx.rop.code.LocalVariableInfo;
31579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilsonimport com.android.dx.rop.code.RopMethod;
32579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilsonimport com.android.dx.rop.cst.CstString;
33579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilsonimport com.android.dx.rop.cst.CstType;
34579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilsonimport com.android.dx.rop.type.StdTypeList;
35579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilsonimport java.io.File;
36579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilsonimport java.io.FileOutputStream;
37579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilsonimport java.io.IOException;
38579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilsonimport java.lang.reflect.InvocationTargetException;
3923abc2fe89ec3713645d64bdb74415a9090084f4Jesse Wilsonimport java.lang.reflect.Modifier;
4090699b97998f1582a921202fb909f17f9718d177Jesse Wilsonimport static java.lang.reflect.Modifier.PRIVATE;
4190699b97998f1582a921202fb909f17f9718d177Jesse Wilsonimport static java.lang.reflect.Modifier.STATIC;
42579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilsonimport java.util.LinkedHashMap;
43579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilsonimport java.util.Map;
44579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilsonimport java.util.jar.JarEntry;
45579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilsonimport java.util.jar.JarOutputStream;
46579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson
47579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson/**
480e49fb9243b7463835ab80ef7cc62435f55846ceJesse Wilson * Generates a </i><strong>D</strong>alvik <strong>EX</strong>ecutable (dex)
49b0f6ea8cec29bd1b2453e8fd15d9c6f65ca3ea2cJesse Wilson * file for execution on Android. Dex files define classes and interfaces,
500e49fb9243b7463835ab80ef7cc62435f55846ceJesse Wilson * including their member methods and fields, executable code, and debugging
510e49fb9243b7463835ab80ef7cc62435f55846ceJesse Wilson * information. They also define annotations, though this API currently has no
520e49fb9243b7463835ab80ef7cc62435f55846ceJesse Wilson * facility to create a dex file that contains annotations.
530e49fb9243b7463835ab80ef7cc62435f55846ceJesse Wilson *
540e49fb9243b7463835ab80ef7cc62435f55846ceJesse Wilson * <p>This library is intended to satisfy two use cases:
550e49fb9243b7463835ab80ef7cc62435f55846ceJesse Wilson * <ul>
560e49fb9243b7463835ab80ef7cc62435f55846ceJesse Wilson *   <li><strong>For runtime code generation.</strong> By embedding this library
570e49fb9243b7463835ab80ef7cc62435f55846ceJesse Wilson *       in your Android application, you can dynamically generate and load
580e49fb9243b7463835ab80ef7cc62435f55846ceJesse Wilson *       executable code. This approach takes advantage of the fact that the
590e49fb9243b7463835ab80ef7cc62435f55846ceJesse Wilson *       host environment and target environment are both Android.
600e49fb9243b7463835ab80ef7cc62435f55846ceJesse Wilson *   <li><strong>For compile time code generation.</strong> You may use this
610e49fb9243b7463835ab80ef7cc62435f55846ceJesse Wilson *       library as a part of a compiler that targets Android. In this scenario
620e49fb9243b7463835ab80ef7cc62435f55846ceJesse Wilson *       the generated dex file must be installed on an Android device before it
630e49fb9243b7463835ab80ef7cc62435f55846ceJesse Wilson *       can be executed.
640e49fb9243b7463835ab80ef7cc62435f55846ceJesse Wilson * </ul>
650e49fb9243b7463835ab80ef7cc62435f55846ceJesse Wilson *
660e49fb9243b7463835ab80ef7cc62435f55846ceJesse Wilson * <h3>Example: Fibonacci</h3>
670e49fb9243b7463835ab80ef7cc62435f55846ceJesse Wilson * To illustrate how this API is used, we'll use DexMaker to generate a class
68008290ab55ac24ef656d254e41a03ad2b1fba7d2Jesse Wilson * equivalent to the following Java source: <pre> {@code
690e49fb9243b7463835ab80ef7cc62435f55846ceJesse Wilson *
700e49fb9243b7463835ab80ef7cc62435f55846ceJesse Wilson * package com.publicobject.fib;
710e49fb9243b7463835ab80ef7cc62435f55846ceJesse Wilson *
720e49fb9243b7463835ab80ef7cc62435f55846ceJesse Wilson * public class Fibonacci {
730e49fb9243b7463835ab80ef7cc62435f55846ceJesse Wilson *   public static int fib(int i) {
740e49fb9243b7463835ab80ef7cc62435f55846ceJesse Wilson *     if (i < 2) {
750e49fb9243b7463835ab80ef7cc62435f55846ceJesse Wilson *       return i;
760e49fb9243b7463835ab80ef7cc62435f55846ceJesse Wilson *     }
770e49fb9243b7463835ab80ef7cc62435f55846ceJesse Wilson *     return fib(i - 1) + fib(i - 2);
780e49fb9243b7463835ab80ef7cc62435f55846ceJesse Wilson *   }
790e49fb9243b7463835ab80ef7cc62435f55846ceJesse Wilson * }}</pre>
800e49fb9243b7463835ab80ef7cc62435f55846ceJesse Wilson *
810e49fb9243b7463835ab80ef7cc62435f55846ceJesse Wilson * <p>We start by creating a {@link TypeId} to identify the generated {@code
820e49fb9243b7463835ab80ef7cc62435f55846ceJesse Wilson * Fibonacci} class. DexMaker identifies types by their internal names like
830e49fb9243b7463835ab80ef7cc62435f55846ceJesse Wilson * {@code Ljava/lang/Object;} rather than their Java identifiers like {@code
840e49fb9243b7463835ab80ef7cc62435f55846ceJesse Wilson * java.lang.Object}. <pre>   {@code
850e49fb9243b7463835ab80ef7cc62435f55846ceJesse Wilson *
860e49fb9243b7463835ab80ef7cc62435f55846ceJesse Wilson *   TypeId<?> fibonacci = TypeId.get("Lcom/google/dexmaker/examples/Fibonacci;");
870e49fb9243b7463835ab80ef7cc62435f55846ceJesse Wilson * }</pre>
880e49fb9243b7463835ab80ef7cc62435f55846ceJesse Wilson *
890e49fb9243b7463835ab80ef7cc62435f55846ceJesse Wilson * <p>Next we declare the class. It allows us to specify the type's source file
900e49fb9243b7463835ab80ef7cc62435f55846ceJesse Wilson * for stack traces, its modifiers, its superclass, and the interfaces it
910e49fb9243b7463835ab80ef7cc62435f55846ceJesse Wilson * implements. In this case, {@code Fibonacci} is a public class that extends
920e49fb9243b7463835ab80ef7cc62435f55846ceJesse Wilson * from {@code Object}: <pre>   {@code
930e49fb9243b7463835ab80ef7cc62435f55846ceJesse Wilson *
940e49fb9243b7463835ab80ef7cc62435f55846ceJesse Wilson *   String fileName = "Fibonacci.generated";
950e49fb9243b7463835ab80ef7cc62435f55846ceJesse Wilson *   DexMaker dexMaker = new DexMaker();
960e49fb9243b7463835ab80ef7cc62435f55846ceJesse Wilson *   dexMaker.declare(fibonacci, fileName, Modifier.PUBLIC, TypeId.OBJECT);
970e49fb9243b7463835ab80ef7cc62435f55846ceJesse Wilson * }</pre>
980e49fb9243b7463835ab80ef7cc62435f55846ceJesse Wilson * It is illegal to declare members of a class without also declaring the class
990e49fb9243b7463835ab80ef7cc62435f55846ceJesse Wilson * itself.
1000e49fb9243b7463835ab80ef7cc62435f55846ceJesse Wilson *
1010e49fb9243b7463835ab80ef7cc62435f55846ceJesse Wilson * <p>To make it easier to go from our Java method to dex instructions, we'll
1020e49fb9243b7463835ab80ef7cc62435f55846ceJesse Wilson * manually translate it to pseudocode fit for an assembler. We need to replace
1030e49fb9243b7463835ab80ef7cc62435f55846ceJesse Wilson * control flow like {@code if()} blocks and {@code for()} loops with labels and
1040e49fb9243b7463835ab80ef7cc62435f55846ceJesse Wilson * branches. We'll also avoid performing multiple operations in one statement,
1050e49fb9243b7463835ab80ef7cc62435f55846ceJesse Wilson * using local variables to hold intermediate values as necessary:
1060e49fb9243b7463835ab80ef7cc62435f55846ceJesse Wilson * <pre>   {@code
1070e49fb9243b7463835ab80ef7cc62435f55846ceJesse Wilson *
1080e49fb9243b7463835ab80ef7cc62435f55846ceJesse Wilson *   int constant1 = 1;
1090e49fb9243b7463835ab80ef7cc62435f55846ceJesse Wilson *   int constant2 = 2;
1100e49fb9243b7463835ab80ef7cc62435f55846ceJesse Wilson *   if (i < constant2) goto baseCase;
1110e49fb9243b7463835ab80ef7cc62435f55846ceJesse Wilson *   int a = i - constant1;
1120e49fb9243b7463835ab80ef7cc62435f55846ceJesse Wilson *   int b = i - constant2;
1130e49fb9243b7463835ab80ef7cc62435f55846ceJesse Wilson *   int c = fib(a);
1140e49fb9243b7463835ab80ef7cc62435f55846ceJesse Wilson *   int d = fib(b);
1150e49fb9243b7463835ab80ef7cc62435f55846ceJesse Wilson *   int result = c + d;
1160e49fb9243b7463835ab80ef7cc62435f55846ceJesse Wilson *   return result;
1170e49fb9243b7463835ab80ef7cc62435f55846ceJesse Wilson * baseCase:
1180e49fb9243b7463835ab80ef7cc62435f55846ceJesse Wilson *   return i;
1190e49fb9243b7463835ab80ef7cc62435f55846ceJesse Wilson * }</pre>
1200e49fb9243b7463835ab80ef7cc62435f55846ceJesse Wilson *
121008290ab55ac24ef656d254e41a03ad2b1fba7d2Jesse Wilson * <p>We look up the {@code MethodId} for the method on the declaring type. This
122008290ab55ac24ef656d254e41a03ad2b1fba7d2Jesse Wilson * takes the method's return type (possibly {@link TypeId#VOID}), its name and
123008290ab55ac24ef656d254e41a03ad2b1fba7d2Jesse Wilson * its parameters types. Next we declare the method, specifying its modifiers by
124008290ab55ac24ef656d254e41a03ad2b1fba7d2Jesse Wilson * bitwise ORing constants from {@link java.lang.reflect.Modifier}. The declare
125008290ab55ac24ef656d254e41a03ad2b1fba7d2Jesse Wilson * call returns a {@link Code} object, which we'll use to define the method's
126008290ab55ac24ef656d254e41a03ad2b1fba7d2Jesse Wilson * instructions. <pre>   {@code
1270e49fb9243b7463835ab80ef7cc62435f55846ceJesse Wilson *
1280e49fb9243b7463835ab80ef7cc62435f55846ceJesse Wilson *   MethodId<?, Integer> fib = fibonacci.getMethod(TypeId.INT, "fib", TypeId.INT);
1290e49fb9243b7463835ab80ef7cc62435f55846ceJesse Wilson *   Code code = dexMaker.declare(fib, Modifier.PUBLIC | Modifier.STATIC);
1300e49fb9243b7463835ab80ef7cc62435f55846ceJesse Wilson * }</pre>
1310e49fb9243b7463835ab80ef7cc62435f55846ceJesse Wilson *
1320e49fb9243b7463835ab80ef7cc62435f55846ceJesse Wilson * <p>One limitation of {@code DexMaker}'s API is that it requires all local
1330e49fb9243b7463835ab80ef7cc62435f55846ceJesse Wilson * variables to be created before any instructions are emitted. Use {@link
134008290ab55ac24ef656d254e41a03ad2b1fba7d2Jesse Wilson * Code#newLocal newLocal()} to create a new local variable. The method's
135008290ab55ac24ef656d254e41a03ad2b1fba7d2Jesse Wilson * parameters are exposed as locals using {@link Code#getParameter
136008290ab55ac24ef656d254e41a03ad2b1fba7d2Jesse Wilson * getParameter()}. For non-static methods the {@code this} pointer is exposed
137008290ab55ac24ef656d254e41a03ad2b1fba7d2Jesse Wilson * using {@link Code#getThis getThis()}. Here we declare all of the local
138008290ab55ac24ef656d254e41a03ad2b1fba7d2Jesse Wilson * variables that we'll need for our {@code fib()} method: <pre>   {@code
1390e49fb9243b7463835ab80ef7cc62435f55846ceJesse Wilson *
1400e49fb9243b7463835ab80ef7cc62435f55846ceJesse Wilson *   Local<Integer> i = code.getParameter(0, TypeId.INT);
1410e49fb9243b7463835ab80ef7cc62435f55846ceJesse Wilson *   Local<Integer> constant1 = code.newLocal(TypeId.INT);
1420e49fb9243b7463835ab80ef7cc62435f55846ceJesse Wilson *   Local<Integer> constant2 = code.newLocal(TypeId.INT);
1430e49fb9243b7463835ab80ef7cc62435f55846ceJesse Wilson *   Local<Integer> a = code.newLocal(TypeId.INT);
1440e49fb9243b7463835ab80ef7cc62435f55846ceJesse Wilson *   Local<Integer> b = code.newLocal(TypeId.INT);
1450e49fb9243b7463835ab80ef7cc62435f55846ceJesse Wilson *   Local<Integer> c = code.newLocal(TypeId.INT);
1460e49fb9243b7463835ab80ef7cc62435f55846ceJesse Wilson *   Local<Integer> d = code.newLocal(TypeId.INT);
1470e49fb9243b7463835ab80ef7cc62435f55846ceJesse Wilson *   Local<Integer> result = code.newLocal(TypeId.INT);
1480e49fb9243b7463835ab80ef7cc62435f55846ceJesse Wilson * }</pre>
1490e49fb9243b7463835ab80ef7cc62435f55846ceJesse Wilson *
150008290ab55ac24ef656d254e41a03ad2b1fba7d2Jesse Wilson * <p>Notice that {@link Local} has a type parameter of {@code Integer}. This is
151008290ab55ac24ef656d254e41a03ad2b1fba7d2Jesse Wilson * useful for generating code that works with existing types like {@code String}
152008290ab55ac24ef656d254e41a03ad2b1fba7d2Jesse Wilson * and {@code Integer}, but it can be a hindrance when generating code that
153008290ab55ac24ef656d254e41a03ad2b1fba7d2Jesse Wilson * involves new types. For this reason you may prefer to use raw types only and
154008290ab55ac24ef656d254e41a03ad2b1fba7d2Jesse Wilson * add {@code @SuppressWarnings("unsafe")} on your calling code. This will yield
155008290ab55ac24ef656d254e41a03ad2b1fba7d2Jesse Wilson * the same result but you won't get IDE support if you make a type error.
1560e49fb9243b7463835ab80ef7cc62435f55846ceJesse Wilson *
157b0f6ea8cec29bd1b2453e8fd15d9c6f65ca3ea2cJesse Wilson * <p>We're ready to start defining our method's instructions. The {@link Code}
158b0f6ea8cec29bd1b2453e8fd15d9c6f65ca3ea2cJesse Wilson * class catalogs the available instructions and their use. <pre>   {@code
1590e49fb9243b7463835ab80ef7cc62435f55846ceJesse Wilson *
1600e49fb9243b7463835ab80ef7cc62435f55846ceJesse Wilson *   code.loadConstant(constant1, 1);
1610e49fb9243b7463835ab80ef7cc62435f55846ceJesse Wilson *   code.loadConstant(constant2, 2);
16223abc2fe89ec3713645d64bdb74415a9090084f4Jesse Wilson *   Label baseCase = new Label();
1630e49fb9243b7463835ab80ef7cc62435f55846ceJesse Wilson *   code.compare(Comparison.LT, baseCase, i, constant2);
1640e49fb9243b7463835ab80ef7cc62435f55846ceJesse Wilson *   code.op(BinaryOp.SUBTRACT, a, i, constant1);
1650e49fb9243b7463835ab80ef7cc62435f55846ceJesse Wilson *   code.op(BinaryOp.SUBTRACT, b, i, constant2);
1660e49fb9243b7463835ab80ef7cc62435f55846ceJesse Wilson *   code.invokeStatic(fib, c, a);
1670e49fb9243b7463835ab80ef7cc62435f55846ceJesse Wilson *   code.invokeStatic(fib, d, b);
1680e49fb9243b7463835ab80ef7cc62435f55846ceJesse Wilson *   code.op(BinaryOp.ADD, result, c, d);
1690e49fb9243b7463835ab80ef7cc62435f55846ceJesse Wilson *   code.returnValue(result);
1700e49fb9243b7463835ab80ef7cc62435f55846ceJesse Wilson *   code.mark(baseCase);
1710e49fb9243b7463835ab80ef7cc62435f55846ceJesse Wilson *   code.returnValue(i);
1720e49fb9243b7463835ab80ef7cc62435f55846ceJesse Wilson * }</pre>
1730e49fb9243b7463835ab80ef7cc62435f55846ceJesse Wilson *
174008290ab55ac24ef656d254e41a03ad2b1fba7d2Jesse Wilson * <p>We're done defining the dex file. We just need to write it to the
175008290ab55ac24ef656d254e41a03ad2b1fba7d2Jesse Wilson * filesystem or load it into the current process. For this example we'll load
1760e49fb9243b7463835ab80ef7cc62435f55846ceJesse Wilson * the generated code into the current process. This only works when the current
1773e7a2230ec75b59ae9b4aad292f51df2542ced7dJesse Wilson * process is running on Android. We use {@link #generateAndLoad
1783e7a2230ec75b59ae9b4aad292f51df2542ced7dJesse Wilson * generateAndLoad()} which takes the class loader that will be used as our
1793e7a2230ec75b59ae9b4aad292f51df2542ced7dJesse Wilson * generated code's parent class loader. It also requires a directory where
1803e7a2230ec75b59ae9b4aad292f51df2542ced7dJesse Wilson * temporary files can be written. <pre>   {@code
1810e49fb9243b7463835ab80ef7cc62435f55846ceJesse Wilson *
1820e49fb9243b7463835ab80ef7cc62435f55846ceJesse Wilson *   ClassLoader loader = dexMaker.generateAndLoad(
1835692b3b0303c55524ff206dc7840ffdb1fa47628Jesse Wilson *       FibonacciMaker.class.getClassLoader(), getDataDirectory());
1840e49fb9243b7463835ab80ef7cc62435f55846ceJesse Wilson * }</pre>
1850e49fb9243b7463835ab80ef7cc62435f55846ceJesse Wilson * Finally we'll use reflection to lookup our generated class on its class
1860e49fb9243b7463835ab80ef7cc62435f55846ceJesse Wilson * loader and invoke its {@code fib()} method: <pre>   {@code
1870e49fb9243b7463835ab80ef7cc62435f55846ceJesse Wilson *
1880e49fb9243b7463835ab80ef7cc62435f55846ceJesse Wilson *   Class<?> fibonacciClass = loader.loadClass("com.google.dexmaker.examples.Fibonacci");
1890e49fb9243b7463835ab80ef7cc62435f55846ceJesse Wilson *   Method fibMethod = fibonacciClass.getMethod("fib", int.class);
1900e49fb9243b7463835ab80ef7cc62435f55846ceJesse Wilson *   System.out.println(fibMethod.invoke(null, 8));
1910e49fb9243b7463835ab80ef7cc62435f55846ceJesse Wilson * }</pre>
192579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson */
193ab220f004db90fa94ef9349ca1adde5f89012e8dJesse Wilsonpublic final class DexMaker {
1940e49fb9243b7463835ab80ef7cc62435f55846ceJesse Wilson    private final Map<TypeId<?>, TypeDeclaration> types
1950e49fb9243b7463835ab80ef7cc62435f55846ceJesse Wilson            = new LinkedHashMap<TypeId<?>, TypeDeclaration>();
196579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson
1973e7a2230ec75b59ae9b4aad292f51df2542ced7dJesse Wilson    /**
1983e7a2230ec75b59ae9b4aad292f51df2542ced7dJesse Wilson     * Creates a new {@code DexMaker} instance, which can be used to create a
1993e7a2230ec75b59ae9b4aad292f51df2542ced7dJesse Wilson     * single dex file.
2003e7a2230ec75b59ae9b4aad292f51df2542ced7dJesse Wilson     */
2013e7a2230ec75b59ae9b4aad292f51df2542ced7dJesse Wilson    public DexMaker() {
2023e7a2230ec75b59ae9b4aad292f51df2542ced7dJesse Wilson    }
2033e7a2230ec75b59ae9b4aad292f51df2542ced7dJesse Wilson
2040e49fb9243b7463835ab80ef7cc62435f55846ceJesse Wilson    private TypeDeclaration getTypeDeclaration(TypeId<?> type) {
205579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson        TypeDeclaration result = types.get(type);
206579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson        if (result == null) {
207579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson            result = new TypeDeclaration(type);
208579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson            types.put(type, result);
209579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson        }
210579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson        return result;
211579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson    }
212579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson
213579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson    /**
21423abc2fe89ec3713645d64bdb74415a9090084f4Jesse Wilson     * Declares {@code type}.
21523abc2fe89ec3713645d64bdb74415a9090084f4Jesse Wilson     *
21623abc2fe89ec3713645d64bdb74415a9090084f4Jesse Wilson     * @param flags a bitwise combination of {@link Modifier#PUBLIC}, {@link
21723abc2fe89ec3713645d64bdb74415a9090084f4Jesse Wilson     *     Modifier#FINAL} and {@link Modifier#ABSTRACT}.
218579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson     */
2190e49fb9243b7463835ab80ef7cc62435f55846ceJesse Wilson    public void declare(TypeId<?> type, String sourceFile, int flags,
2200e49fb9243b7463835ab80ef7cc62435f55846ceJesse Wilson            TypeId<?> supertype, TypeId<?>... interfaces) {
221579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson        TypeDeclaration declaration = getTypeDeclaration(type);
222c0271e9981ddd85a13ed88defd0b5b1a5ccc6f46Jesse Wilson        int supportedFlags = Modifier.PUBLIC | Modifier.FINAL | Modifier.ABSTRACT;
223c0271e9981ddd85a13ed88defd0b5b1a5ccc6f46Jesse Wilson        if ((flags & ~supportedFlags) != 0) {
224c0271e9981ddd85a13ed88defd0b5b1a5ccc6f46Jesse Wilson            throw new IllegalArgumentException("Unexpected flag: "
225c0271e9981ddd85a13ed88defd0b5b1a5ccc6f46Jesse Wilson                    + Integer.toHexString(flags));
226c0271e9981ddd85a13ed88defd0b5b1a5ccc6f46Jesse Wilson        }
227579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson        if (declaration.declared) {
228579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson            throw new IllegalStateException("already declared: " + type);
229579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson        }
230579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson        declaration.declared = true;
231579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson        declaration.flags = flags;
232579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson        declaration.supertype = supertype;
233579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson        declaration.sourceFile = sourceFile;
234579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson        declaration.interfaces = new TypeList(interfaces);
235579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson    }
236579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson
237579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson    /**
238c0271e9981ddd85a13ed88defd0b5b1a5ccc6f46Jesse Wilson     * Declares a method or constructor.
23923abc2fe89ec3713645d64bdb74415a9090084f4Jesse Wilson     *
24023abc2fe89ec3713645d64bdb74415a9090084f4Jesse Wilson     * @param flags a bitwise combination of {@link Modifier#PUBLIC}, {@link
24123abc2fe89ec3713645d64bdb74415a9090084f4Jesse Wilson     *     Modifier#PRIVATE}, {@link Modifier#PROTECTED}, {@link Modifier#STATIC},
242c0271e9981ddd85a13ed88defd0b5b1a5ccc6f46Jesse Wilson     *     {@link Modifier#FINAL} and {@link Modifier#SYNCHRONIZED}.
2435624228626d7cdf206de25a6981ba8107be61057Jesse Wilson     *     <p><strong>Warning:</strong> the {@link Modifier#SYNCHRONIZED} flag
2445624228626d7cdf206de25a6981ba8107be61057Jesse Wilson     *     is insufficient to generate a synchronized method. You must also use
2455624228626d7cdf206de25a6981ba8107be61057Jesse Wilson     *     {@link Code#monitorEnter} and {@link Code#monitorExit} to acquire
2465624228626d7cdf206de25a6981ba8107be61057Jesse Wilson     *     a monitor.
24790699b97998f1582a921202fb909f17f9718d177Jesse Wilson     */
248579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson    public Code declare(MethodId<?, ?> method, int flags) {
249579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson        TypeDeclaration typeDeclaration = getTypeDeclaration(method.declaringType);
250579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson        if (typeDeclaration.methods.containsKey(method)) {
251579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson            throw new IllegalStateException("already declared: " + method);
252579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson        }
253c0271e9981ddd85a13ed88defd0b5b1a5ccc6f46Jesse Wilson
254c0271e9981ddd85a13ed88defd0b5b1a5ccc6f46Jesse Wilson        int supportedFlags = Modifier.PUBLIC | Modifier.PRIVATE | Modifier.PROTECTED
255c0271e9981ddd85a13ed88defd0b5b1a5ccc6f46Jesse Wilson                | Modifier.STATIC | Modifier.FINAL | Modifier.SYNCHRONIZED;
256c0271e9981ddd85a13ed88defd0b5b1a5ccc6f46Jesse Wilson        if ((flags & ~supportedFlags) != 0) {
257c0271e9981ddd85a13ed88defd0b5b1a5ccc6f46Jesse Wilson            throw new IllegalArgumentException("Unexpected flag: "
258c0271e9981ddd85a13ed88defd0b5b1a5ccc6f46Jesse Wilson                    + Integer.toHexString(flags));
259c0271e9981ddd85a13ed88defd0b5b1a5ccc6f46Jesse Wilson        }
260c0271e9981ddd85a13ed88defd0b5b1a5ccc6f46Jesse Wilson
2615624228626d7cdf206de25a6981ba8107be61057Jesse Wilson        // replace the SYNCHRONIZED flag with the DECLARED_SYNCHRONIZED flag
2625624228626d7cdf206de25a6981ba8107be61057Jesse Wilson        if ((flags & Modifier.SYNCHRONIZED) != 0) {
2635624228626d7cdf206de25a6981ba8107be61057Jesse Wilson            flags = (flags & ~Modifier.SYNCHRONIZED) | AccessFlags.ACC_DECLARED_SYNCHRONIZED;
2645624228626d7cdf206de25a6981ba8107be61057Jesse Wilson        }
265c0271e9981ddd85a13ed88defd0b5b1a5ccc6f46Jesse Wilson
266c0271e9981ddd85a13ed88defd0b5b1a5ccc6f46Jesse Wilson        if (method.isConstructor()) {
267c0271e9981ddd85a13ed88defd0b5b1a5ccc6f46Jesse Wilson            flags |= ACC_CONSTRUCTOR;
268c0271e9981ddd85a13ed88defd0b5b1a5ccc6f46Jesse Wilson        }
269c0271e9981ddd85a13ed88defd0b5b1a5ccc6f46Jesse Wilson
270579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson        MethodDeclaration methodDeclaration = new MethodDeclaration(method, flags);
271579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson        typeDeclaration.methods.put(method, methodDeclaration);
272579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson        return methodDeclaration.code;
273579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson    }
274579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson
275579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson    /**
27623abc2fe89ec3713645d64bdb74415a9090084f4Jesse Wilson     * Declares a field.
27723abc2fe89ec3713645d64bdb74415a9090084f4Jesse Wilson     *
27823abc2fe89ec3713645d64bdb74415a9090084f4Jesse Wilson     * @param flags a bitwise combination of {@link Modifier#PUBLIC}, {@link
27923abc2fe89ec3713645d64bdb74415a9090084f4Jesse Wilson     *     Modifier#PRIVATE}, {@link Modifier#PROTECTED}, {@link Modifier#STATIC},
28023abc2fe89ec3713645d64bdb74415a9090084f4Jesse Wilson     *     {@link Modifier#FINAL}, {@link Modifier#VOLATILE}, and {@link
28123abc2fe89ec3713645d64bdb74415a9090084f4Jesse Wilson     *     Modifier#TRANSIENT}.
282c0271e9981ddd85a13ed88defd0b5b1a5ccc6f46Jesse Wilson     * @param staticValue a constant representing the initial value for the
283c0271e9981ddd85a13ed88defd0b5b1a5ccc6f46Jesse Wilson     *     static field, possibly null. This must be null if this field is
284c0271e9981ddd85a13ed88defd0b5b1a5ccc6f46Jesse Wilson     *     non-static.
285579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson     */
286579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson    public void declare(FieldId<?, ?> fieldId, int flags, Object staticValue) {
287579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson        TypeDeclaration typeDeclaration = getTypeDeclaration(fieldId.declaringType);
288579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson        if (typeDeclaration.fields.containsKey(fieldId)) {
289579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson            throw new IllegalStateException("already declared: " + fieldId);
290579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson        }
291c0271e9981ddd85a13ed88defd0b5b1a5ccc6f46Jesse Wilson
292c0271e9981ddd85a13ed88defd0b5b1a5ccc6f46Jesse Wilson        int supportedFlags = Modifier.PUBLIC | Modifier.PRIVATE | Modifier.PROTECTED
293c0271e9981ddd85a13ed88defd0b5b1a5ccc6f46Jesse Wilson                | Modifier.STATIC | Modifier.FINAL | Modifier.VOLATILE | Modifier.TRANSIENT;
294c0271e9981ddd85a13ed88defd0b5b1a5ccc6f46Jesse Wilson        if ((flags & ~supportedFlags) != 0) {
295c0271e9981ddd85a13ed88defd0b5b1a5ccc6f46Jesse Wilson            throw new IllegalArgumentException("Unexpected flag: "
296c0271e9981ddd85a13ed88defd0b5b1a5ccc6f46Jesse Wilson                    + Integer.toHexString(flags));
297c0271e9981ddd85a13ed88defd0b5b1a5ccc6f46Jesse Wilson        }
298c0271e9981ddd85a13ed88defd0b5b1a5ccc6f46Jesse Wilson
299c0271e9981ddd85a13ed88defd0b5b1a5ccc6f46Jesse Wilson        if ((flags & Modifier.STATIC) == 0 && staticValue != null) {
300c0271e9981ddd85a13ed88defd0b5b1a5ccc6f46Jesse Wilson            throw new IllegalArgumentException("staticValue is non-null, but field is not static");
301c0271e9981ddd85a13ed88defd0b5b1a5ccc6f46Jesse Wilson        }
302c0271e9981ddd85a13ed88defd0b5b1a5ccc6f46Jesse Wilson
303579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson        FieldDeclaration fieldDeclaration = new FieldDeclaration(fieldId, flags, staticValue);
304579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson        typeDeclaration.fields.put(fieldId, fieldDeclaration);
305579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson    }
306579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson
307579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson    /**
30823abc2fe89ec3713645d64bdb74415a9090084f4Jesse Wilson     * Generates a dex file and returns its bytes.
309579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson     */
310579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson    public byte[] generate() {
311579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson        DexOptions options = new DexOptions();
312579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson        options.targetApiLevel = DexFormat.API_NO_EXTENDED_OPCODES;
313579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson        DexFile outputDex = new DexFile(options);
314579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson
315579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson        for (TypeDeclaration typeDeclaration : types.values()) {
316579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson            outputDex.add(typeDeclaration.toClassDefItem());
317579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson        }
318579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson
319579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson        try {
320579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson            return outputDex.toDex(null, false);
321579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson        } catch (IOException e) {
322579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson            throw new RuntimeException(e);
323579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson        }
324579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson    }
325579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson
326579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson    /**
32723abc2fe89ec3713645d64bdb74415a9090084f4Jesse Wilson     * Generates a dex file and loads its types into the current process.
328579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson     *
32973cfa4498f640e0915b95fc806db4a0d54172fe8Jesse Wilson     * <h3>Picking a dex cache directory</h3>
33073cfa4498f640e0915b95fc806db4a0d54172fe8Jesse Wilson     * The {@code dexCache} should be an application-private directory. If
33173cfa4498f640e0915b95fc806db4a0d54172fe8Jesse Wilson     * you pass a world-writable directory like {@code /sdcard} a malicious app
33273cfa4498f640e0915b95fc806db4a0d54172fe8Jesse Wilson     * could inject code into your process. Most applications should use this:
33373cfa4498f640e0915b95fc806db4a0d54172fe8Jesse Wilson     * <pre>   {@code
334579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson     *
33573cfa4498f640e0915b95fc806db4a0d54172fe8Jesse Wilson     *     File dexCache = getApplicationContext().getDir("dx", Context.MODE_PRIVATE);
33673cfa4498f640e0915b95fc806db4a0d54172fe8Jesse Wilson     * }</pre>
33773cfa4498f640e0915b95fc806db4a0d54172fe8Jesse Wilson     * If the {@code dexCache} is null, this method will consult the {@code
33873cfa4498f640e0915b95fc806db4a0d54172fe8Jesse Wilson     * dexmaker.dexcache} system property. If that exists, it will be used for
33973cfa4498f640e0915b95fc806db4a0d54172fe8Jesse Wilson     * the dex cache. If it doesn't exist, this method will attempt to guess
34073cfa4498f640e0915b95fc806db4a0d54172fe8Jesse Wilson     * the application's private data directory as a last resort. If that fails,
34173cfa4498f640e0915b95fc806db4a0d54172fe8Jesse Wilson     * this method will fail with an unchecked exception. You can avoid the
34273cfa4498f640e0915b95fc806db4a0d54172fe8Jesse Wilson     * exception by either providing a non-null value or setting the system
34373cfa4498f640e0915b95fc806db4a0d54172fe8Jesse Wilson     * property.
344579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson     *
34573cfa4498f640e0915b95fc806db4a0d54172fe8Jesse Wilson     * @param parent the parent ClassLoader to be used when loading our
34673cfa4498f640e0915b95fc806db4a0d54172fe8Jesse Wilson     *     generated types
34773cfa4498f640e0915b95fc806db4a0d54172fe8Jesse Wilson     * @param dexCache the destination directory where generated and optimized
34873cfa4498f640e0915b95fc806db4a0d54172fe8Jesse Wilson     *     dex files will be written. If null, this class will try to guess the
34973cfa4498f640e0915b95fc806db4a0d54172fe8Jesse Wilson     *     application's private data dir.
350579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson     */
35173cfa4498f640e0915b95fc806db4a0d54172fe8Jesse Wilson    public ClassLoader generateAndLoad(ClassLoader parent, File dexCache) throws IOException {
35273cfa4498f640e0915b95fc806db4a0d54172fe8Jesse Wilson        if (dexCache == null) {
35373cfa4498f640e0915b95fc806db4a0d54172fe8Jesse Wilson            String property = System.getProperty("dexmaker.dexcache");
35473cfa4498f640e0915b95fc806db4a0d54172fe8Jesse Wilson            if (property != null) {
35573cfa4498f640e0915b95fc806db4a0d54172fe8Jesse Wilson                dexCache = new File(property);
35673cfa4498f640e0915b95fc806db4a0d54172fe8Jesse Wilson            } else {
35773cfa4498f640e0915b95fc806db4a0d54172fe8Jesse Wilson                dexCache = new AppDataDirGuesser().guess();
35873cfa4498f640e0915b95fc806db4a0d54172fe8Jesse Wilson                if (dexCache == null) {
35973cfa4498f640e0915b95fc806db4a0d54172fe8Jesse Wilson                    throw new IllegalArgumentException("dexcache == null (and no default could be"
36073cfa4498f640e0915b95fc806db4a0d54172fe8Jesse Wilson                            + " found; consider setting the 'dexmaker.dexcache' system property)");
36173cfa4498f640e0915b95fc806db4a0d54172fe8Jesse Wilson                }
36273cfa4498f640e0915b95fc806db4a0d54172fe8Jesse Wilson            }
36373cfa4498f640e0915b95fc806db4a0d54172fe8Jesse Wilson        }
36473cfa4498f640e0915b95fc806db4a0d54172fe8Jesse Wilson
365579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson        byte[] dex = generate();
366579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson
367579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson        /*
368579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson         * This implementation currently dumps the dex to the filesystem. It
369579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson         * jars the emitted .dex for the benefit of Gingerbread and earlier
370579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson         * devices, which can't load .dex files directly.
371579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson         *
372579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson         * TODO: load the dex from memory where supported.
373579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson         */
37473cfa4498f640e0915b95fc806db4a0d54172fe8Jesse Wilson        File result = File.createTempFile("Generated", ".jar", dexCache);
375579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson        result.deleteOnExit();
376579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson        JarOutputStream jarOut = new JarOutputStream(new FileOutputStream(result));
377579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson        jarOut.putNextEntry(new JarEntry(DexFormat.DEX_IN_JAR_NAME));
378579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson        jarOut.write(dex);
379579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson        jarOut.closeEntry();
380579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson        jarOut.close();
381579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson        try {
382579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson            return (ClassLoader) Class.forName("dalvik.system.DexClassLoader")
383579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson                    .getConstructor(String.class, String.class, String.class, ClassLoader.class)
38473cfa4498f640e0915b95fc806db4a0d54172fe8Jesse Wilson                    .newInstance(result.getPath(), dexCache.getAbsolutePath(), null, parent);
385579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson        } catch (ClassNotFoundException e) {
386579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson            throw new UnsupportedOperationException("load() requires a Dalvik VM", e);
387579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson        } catch (InvocationTargetException e) {
388579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson            throw new RuntimeException(e.getCause());
389579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson        } catch (InstantiationException e) {
390579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson            throw new AssertionError();
391579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson        } catch (NoSuchMethodException e) {
392579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson            throw new AssertionError();
393579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson        } catch (IllegalAccessException e) {
394579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson            throw new AssertionError();
395579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson        }
396579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson    }
397579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson
398579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson    private static class TypeDeclaration {
3990e49fb9243b7463835ab80ef7cc62435f55846ceJesse Wilson        private final TypeId<?> type;
400579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson
401579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson        /** declared state */
402579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson        private boolean declared;
403579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson        private int flags;
4040e49fb9243b7463835ab80ef7cc62435f55846ceJesse Wilson        private TypeId<?> supertype;
405579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson        private String sourceFile;
406579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson        private TypeList interfaces;
407579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson
408579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson        private final Map<FieldId, FieldDeclaration> fields
409579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson                = new LinkedHashMap<FieldId, FieldDeclaration>();
410579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson        private final Map<MethodId, MethodDeclaration> methods
411579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson                = new LinkedHashMap<MethodId, MethodDeclaration>();
412579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson
4130e49fb9243b7463835ab80ef7cc62435f55846ceJesse Wilson        TypeDeclaration(TypeId<?> type) {
414579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson            this.type = type;
415579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson        }
416579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson
417579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson        ClassDefItem toClassDefItem() {
418579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson            if (!declared) {
419579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson                throw new IllegalStateException("Undeclared type " + type + " declares members: "
420579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson                        + fields.keySet() + " " + methods.keySet());
421579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson            }
422579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson
423579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson            DexOptions dexOptions = new DexOptions();
424579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson            dexOptions.targetApiLevel = DexFormat.API_NO_EXTENDED_OPCODES;
425579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson
426579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson            CstType thisType = type.constant;
427579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson
428579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson            ClassDefItem out = new ClassDefItem(thisType, flags, supertype.constant,
429579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson                    interfaces.ropTypes, new CstString(sourceFile));
430579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson
431579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson            for (MethodDeclaration method : methods.values()) {
432579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson                EncodedMethod encoded = method.toEncodedMethod(dexOptions);
433579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson                if (method.isDirect()) {
434579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson                    out.addDirectMethod(encoded);
435579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson                } else {
436579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson                    out.addVirtualMethod(encoded);
437579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson                }
438579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson            }
439579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson            for (FieldDeclaration field : fields.values()) {
440579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson                EncodedField encoded = field.toEncodedField();
441579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson                if (field.isStatic()) {
442579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson                    out.addStaticField(encoded, Constants.getConstant(field.staticValue));
443579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson                } else {
444579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson                    out.addInstanceField(encoded);
445579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson                }
446579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson            }
447579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson
448579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson            return out;
449579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson        }
450579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson    }
451579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson
452579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson    static class FieldDeclaration {
453579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson        final FieldId<?, ?> fieldId;
454579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson        private final int accessFlags;
455579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson        private final Object staticValue;
456579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson
457579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson        FieldDeclaration(FieldId<?, ?> fieldId, int accessFlags, Object staticValue) {
45890699b97998f1582a921202fb909f17f9718d177Jesse Wilson            if ((accessFlags & STATIC) == 0 && staticValue != null) {
459579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson                throw new IllegalArgumentException("instance fields may not have a value");
460579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson            }
461579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson            this.fieldId = fieldId;
462579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson            this.accessFlags = accessFlags;
463579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson            this.staticValue = staticValue;
464579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson        }
465579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson
466579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson        EncodedField toEncodedField() {
467579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson            return new EncodedField(fieldId.constant, accessFlags);
468579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson        }
469579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson
470579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson        public boolean isStatic() {
47190699b97998f1582a921202fb909f17f9718d177Jesse Wilson            return (accessFlags & STATIC) != 0;
472579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson        }
473579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson    }
474579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson
475579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson    static class MethodDeclaration {
476579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson        final MethodId<?, ?> method;
477579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson        private final int flags;
478579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson        private final Code code;
479579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson
480579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson        public MethodDeclaration(MethodId<?, ?> method, int flags) {
481579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson            this.method = method;
482579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson            this.flags = flags;
483579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson            this.code = new Code(this);
484579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson        }
485579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson
486579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson        boolean isStatic() {
48790699b97998f1582a921202fb909f17f9718d177Jesse Wilson            return (flags & STATIC) != 0;
488579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson        }
489579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson
490579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson        boolean isDirect() {
49190699b97998f1582a921202fb909f17f9718d177Jesse Wilson            return (flags & (STATIC | PRIVATE | ACC_CONSTRUCTOR)) != 0;
492579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson        }
493579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson
494579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson        EncodedMethod toEncodedMethod(DexOptions dexOptions) {
495579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson            RopMethod ropMethod = new RopMethod(code.toBasicBlocks(), 0);
496579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson            LocalVariableInfo locals = null;
497579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson            DalvCode dalvCode = RopTranslator.translate(
498579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson                    ropMethod, PositionList.NONE, locals, code.paramSize(), dexOptions);
499579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson            return new EncodedMethod(method.constant, flags, dalvCode, StdTypeList.EMPTY);
500579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson        }
501579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson    }
502579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson}
503