DexMaker.java revision 5624228626d7cdf206de25a6981ba8107be61057
1/*
2 * Copyright (C) 2011 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.google.dexmaker;
18
19import com.android.dx.dex.DexFormat;
20import com.android.dx.dex.DexOptions;
21import com.android.dx.dex.code.DalvCode;
22import com.android.dx.dex.code.PositionList;
23import com.android.dx.dex.code.RopTranslator;
24import com.android.dx.dex.file.ClassDefItem;
25import com.android.dx.dex.file.DexFile;
26import com.android.dx.dex.file.EncodedField;
27import com.android.dx.dex.file.EncodedMethod;
28import com.android.dx.rop.code.AccessFlags;
29import static com.android.dx.rop.code.AccessFlags.ACC_CONSTRUCTOR;
30import com.android.dx.rop.code.LocalVariableInfo;
31import com.android.dx.rop.code.RopMethod;
32import com.android.dx.rop.cst.CstString;
33import com.android.dx.rop.cst.CstType;
34import com.android.dx.rop.type.StdTypeList;
35import java.io.File;
36import java.io.FileOutputStream;
37import java.io.IOException;
38import java.lang.reflect.InvocationTargetException;
39import java.lang.reflect.Modifier;
40import static java.lang.reflect.Modifier.PRIVATE;
41import static java.lang.reflect.Modifier.STATIC;
42import java.util.LinkedHashMap;
43import java.util.Map;
44import java.util.jar.JarEntry;
45import java.util.jar.JarOutputStream;
46
47/**
48 * Generates a </i><strong>D</strong>alvik <strong>EX</strong>ecutable (dex)
49 * file for execution on Android. Dex files define classes and interfaces,
50 * including their member methods and fields, executable code, and debugging
51 * information. They also define annotations, though this API currently has no
52 * facility to create a dex file that contains annotations.
53 *
54 * <p>This library is intended to satisfy two use cases:
55 * <ul>
56 *   <li><strong>For runtime code generation.</strong> By embedding this library
57 *       in your Android application, you can dynamically generate and load
58 *       executable code. This approach takes advantage of the fact that the
59 *       host environment and target environment are both Android.
60 *   <li><strong>For compile time code generation.</strong> You may use this
61 *       library as a part of a compiler that targets Android. In this scenario
62 *       the generated dex file must be installed on an Android device before it
63 *       can be executed.
64 * </ul>
65 *
66 * <h3>Example: Fibonacci</h3>
67 * To illustrate how this API is used, we'll use DexMaker to generate a class
68 * equivalent to the following Java source: <pre> {@code
69 *
70 * package com.publicobject.fib;
71 *
72 * public class Fibonacci {
73 *   public static int fib(int i) {
74 *     if (i < 2) {
75 *       return i;
76 *     }
77 *     return fib(i - 1) + fib(i - 2);
78 *   }
79 * }}</pre>
80 *
81 * <p>We start by creating a {@link TypeId} to identify the generated {@code
82 * Fibonacci} class. DexMaker identifies types by their internal names like
83 * {@code Ljava/lang/Object;} rather than their Java identifiers like {@code
84 * java.lang.Object}. <pre>   {@code
85 *
86 *   TypeId<?> fibonacci = TypeId.get("Lcom/google/dexmaker/examples/Fibonacci;");
87 * }</pre>
88 *
89 * <p>Next we declare the class. It allows us to specify the type's source file
90 * for stack traces, its modifiers, its superclass, and the interfaces it
91 * implements. In this case, {@code Fibonacci} is a public class that extends
92 * from {@code Object}: <pre>   {@code
93 *
94 *   String fileName = "Fibonacci.generated";
95 *   DexMaker dexMaker = new DexMaker();
96 *   dexMaker.declare(fibonacci, fileName, Modifier.PUBLIC, TypeId.OBJECT);
97 * }</pre>
98 * It is illegal to declare members of a class without also declaring the class
99 * itself.
100 *
101 * <p>To make it easier to go from our Java method to dex instructions, we'll
102 * manually translate it to pseudocode fit for an assembler. We need to replace
103 * control flow like {@code if()} blocks and {@code for()} loops with labels and
104 * branches. We'll also avoid performing multiple operations in one statement,
105 * using local variables to hold intermediate values as necessary:
106 * <pre>   {@code
107 *
108 *   int constant1 = 1;
109 *   int constant2 = 2;
110 *   if (i < constant2) goto baseCase;
111 *   int a = i - constant1;
112 *   int b = i - constant2;
113 *   int c = fib(a);
114 *   int d = fib(b);
115 *   int result = c + d;
116 *   return result;
117 * baseCase:
118 *   return i;
119 * }</pre>
120 *
121 * <p>We look up the {@code MethodId} for the method on the declaring type. This
122 * takes the method's return type (possibly {@link TypeId#VOID}), its name and
123 * its parameters types. Next we declare the method, specifying its modifiers by
124 * bitwise ORing constants from {@link java.lang.reflect.Modifier}. The declare
125 * call returns a {@link Code} object, which we'll use to define the method's
126 * instructions. <pre>   {@code
127 *
128 *   MethodId<?, Integer> fib = fibonacci.getMethod(TypeId.INT, "fib", TypeId.INT);
129 *   Code code = dexMaker.declare(fib, Modifier.PUBLIC | Modifier.STATIC);
130 * }</pre>
131 *
132 * <p>One limitation of {@code DexMaker}'s API is that it requires all local
133 * variables to be created before any instructions are emitted. Use {@link
134 * Code#newLocal newLocal()} to create a new local variable. The method's
135 * parameters are exposed as locals using {@link Code#getParameter
136 * getParameter()}. For non-static methods the {@code this} pointer is exposed
137 * using {@link Code#getThis getThis()}. Here we declare all of the local
138 * variables that we'll need for our {@code fib()} method: <pre>   {@code
139 *
140 *   Local<Integer> i = code.getParameter(0, TypeId.INT);
141 *   Local<Integer> constant1 = code.newLocal(TypeId.INT);
142 *   Local<Integer> constant2 = code.newLocal(TypeId.INT);
143 *   Local<Integer> a = code.newLocal(TypeId.INT);
144 *   Local<Integer> b = code.newLocal(TypeId.INT);
145 *   Local<Integer> c = code.newLocal(TypeId.INT);
146 *   Local<Integer> d = code.newLocal(TypeId.INT);
147 *   Local<Integer> result = code.newLocal(TypeId.INT);
148 * }</pre>
149 *
150 * <p>Notice that {@link Local} has a type parameter of {@code Integer}. This is
151 * useful for generating code that works with existing types like {@code String}
152 * and {@code Integer}, but it can be a hindrance when generating code that
153 * involves new types. For this reason you may prefer to use raw types only and
154 * add {@code @SuppressWarnings("unsafe")} on your calling code. This will yield
155 * the same result but you won't get IDE support if you make a type error.
156 *
157 * <p>We're ready to start defining our method's instructions. The {@link Code}
158 * class catalogs the available instructions and their use. <pre>   {@code
159 *
160 *   code.loadConstant(constant1, 1);
161 *   code.loadConstant(constant2, 2);
162 *   Label baseCase = new Label();
163 *   code.compare(Comparison.LT, baseCase, i, constant2);
164 *   code.op(BinaryOp.SUBTRACT, a, i, constant1);
165 *   code.op(BinaryOp.SUBTRACT, b, i, constant2);
166 *   code.invokeStatic(fib, c, a);
167 *   code.invokeStatic(fib, d, b);
168 *   code.op(BinaryOp.ADD, result, c, d);
169 *   code.returnValue(result);
170 *   code.mark(baseCase);
171 *   code.returnValue(i);
172 * }</pre>
173 *
174 * <p>We're done defining the dex file. We just need to write it to the
175 * filesystem or load it into the current process. For this example we'll load
176 * the generated code into the current process. This only works when the current
177 * process is running on Android. We use {@link #generateAndLoad} which takes
178 * the class loader that will be used as our generated code's parent class
179 * loader. It also requires a directory where temporary files can be written.
180 * <pre>   {@code
181 *
182 *   ClassLoader loader = dexMaker.generateAndLoad(
183 *       Fibonacci.class.getClassLoader(), getDataDirectory());
184 * }</pre>
185 * Finally we'll use reflection to lookup our generated class on its class
186 * loader and invoke its {@code fib()} method: <pre>   {@code
187 *
188 *   Class<?> fibonacciClass = loader.loadClass("com.google.dexmaker.examples.Fibonacci");
189 *   Method fibMethod = fibonacciClass.getMethod("fib", int.class);
190 *   System.out.println(fibMethod.invoke(null, 8));
191 * }</pre>
192 */
193public final class DexMaker {
194    private final Map<TypeId<?>, TypeDeclaration> types
195            = new LinkedHashMap<TypeId<?>, TypeDeclaration>();
196
197    private TypeDeclaration getTypeDeclaration(TypeId<?> type) {
198        TypeDeclaration result = types.get(type);
199        if (result == null) {
200            result = new TypeDeclaration(type);
201            types.put(type, result);
202        }
203        return result;
204    }
205
206    /**
207     * Declares {@code type}.
208     *
209     * @param flags a bitwise combination of {@link Modifier#PUBLIC}, {@link
210     *     Modifier#FINAL} and {@link Modifier#ABSTRACT}.
211     */
212    public void declare(TypeId<?> type, String sourceFile, int flags,
213            TypeId<?> supertype, TypeId<?>... interfaces) {
214        TypeDeclaration declaration = getTypeDeclaration(type);
215        if (declaration.declared) {
216            throw new IllegalStateException("already declared: " + type);
217        }
218        declaration.declared = true;
219        declaration.flags = flags;
220        declaration.supertype = supertype;
221        declaration.sourceFile = sourceFile;
222        declaration.interfaces = new TypeList(interfaces);
223    }
224
225    /**
226     * Declares a constructor. The name of {@code method} must be "<init>",
227     * as it is on all instances returned by {@link TypeId#getConstructor}.
228     *
229     * @param flags a bitwise combination of {@link Modifier#PUBLIC}, {@link
230     *     Modifier#PRIVATE}, {@link Modifier#PROTECTED}, {@link Modifier#STATIC},
231     *     {@link Modifier#FINAL}, {@link Modifier#SYNCHRONIZED} and {@link
232     *     Modifier#VARARGS}.
233     *     <p><strong>Warning:</strong> the {@link Modifier#SYNCHRONIZED} flag
234     *     is insufficient to generate a synchronized method. You must also use
235     *     {@link Code#monitorEnter} and {@link Code#monitorExit} to acquire
236     *     a monitor.
237     */
238    public Code declareConstructor(MethodId<?, ?> method, int flags) {
239        return declare(method, flags | ACC_CONSTRUCTOR);
240    }
241
242    /**
243     * Declares a method. The name of {@code method} must not be "<init>".
244     *
245     * @param flags a bitwise combination of {@link Modifier#PUBLIC}, {@link
246     *     Modifier#PRIVATE}, {@link Modifier#PROTECTED}, {@link Modifier#STATIC},
247     *     {@link Modifier#FINAL}, {@link Modifier#SYNCHRONIZED} and {@link
248     *     Modifier#VARARGS}.
249     *     <p><strong>Warning:</strong> the {@link Modifier#SYNCHRONIZED} flag
250     *     is insufficient to generate a synchronized method. You must also use
251     *     {@link Code#monitorEnter} and {@link Code#monitorExit} to acquire
252     *     a monitor.
253     */
254    public Code declare(MethodId<?, ?> method, int flags) {
255        TypeDeclaration typeDeclaration = getTypeDeclaration(method.declaringType);
256        if (typeDeclaration.methods.containsKey(method)) {
257            throw new IllegalStateException("already declared: " + method);
258        }
259        // replace the SYNCHRONIZED flag with the DECLARED_SYNCHRONIZED flag
260        if ((flags & Modifier.SYNCHRONIZED) != 0) {
261            flags = (flags & ~Modifier.SYNCHRONIZED) | AccessFlags.ACC_DECLARED_SYNCHRONIZED;
262        }
263        MethodDeclaration methodDeclaration = new MethodDeclaration(method, flags);
264        typeDeclaration.methods.put(method, methodDeclaration);
265        return methodDeclaration.code;
266    }
267
268    /**
269     * Declares a field.
270     *
271     * @param flags a bitwise combination of {@link Modifier#PUBLIC}, {@link
272     *     Modifier#PRIVATE}, {@link Modifier#PROTECTED}, {@link Modifier#STATIC},
273     *     {@link Modifier#FINAL}, {@link Modifier#VOLATILE}, and {@link
274     *     Modifier#TRANSIENT}.
275     */
276    public void declare(FieldId<?, ?> fieldId, int flags, Object staticValue) {
277        TypeDeclaration typeDeclaration = getTypeDeclaration(fieldId.declaringType);
278        if (typeDeclaration.fields.containsKey(fieldId)) {
279            throw new IllegalStateException("already declared: " + fieldId);
280        }
281        FieldDeclaration fieldDeclaration = new FieldDeclaration(fieldId, flags, staticValue);
282        typeDeclaration.fields.put(fieldId, fieldDeclaration);
283    }
284
285    /**
286     * Generates a dex file and returns its bytes.
287     */
288    public byte[] generate() {
289        DexOptions options = new DexOptions();
290        options.targetApiLevel = DexFormat.API_NO_EXTENDED_OPCODES;
291        DexFile outputDex = new DexFile(options);
292
293        for (TypeDeclaration typeDeclaration : types.values()) {
294            outputDex.add(typeDeclaration.toClassDefItem());
295        }
296
297        try {
298            return outputDex.toDex(null, false);
299        } catch (IOException e) {
300            throw new RuntimeException(e);
301        }
302    }
303
304    /**
305     * Generates a dex file and loads its types into the current process.
306     *
307     * <p>All parameters are optional; you may pass {@code null} and suitable
308     * defaults will be used.
309     *
310     * <p>If you opt to provide your own {@code dexDir}, take care to ensure
311     * that it is not world-writable, otherwise a malicious app may be able
312     * to inject code into your process.  A suitable parameter is:
313     * {@code getApplicationContext().getDir("dx", Context.MODE_PRIVATE); }
314     *
315     * @param parent the parent ClassLoader to be used when loading
316     *     our generated types
317     * @param dexDir the destination directory where generated and
318     *     optimized dex files will be written.
319     */
320    public ClassLoader generateAndLoad(ClassLoader parent, File dexDir) throws IOException {
321        byte[] dex = generate();
322
323        /*
324         * This implementation currently dumps the dex to the filesystem. It
325         * jars the emitted .dex for the benefit of Gingerbread and earlier
326         * devices, which can't load .dex files directly.
327         *
328         * TODO: load the dex from memory where supported.
329         */
330        File result = File.createTempFile("Generated", ".jar", dexDir);
331        result.deleteOnExit();
332        JarOutputStream jarOut = new JarOutputStream(new FileOutputStream(result));
333        jarOut.putNextEntry(new JarEntry(DexFormat.DEX_IN_JAR_NAME));
334        jarOut.write(dex);
335        jarOut.closeEntry();
336        jarOut.close();
337        try {
338            return (ClassLoader) Class.forName("dalvik.system.DexClassLoader")
339                    .getConstructor(String.class, String.class, String.class, ClassLoader.class)
340                    .newInstance(result.getPath(), dexDir.getAbsolutePath(), null, parent);
341        } catch (ClassNotFoundException e) {
342            throw new UnsupportedOperationException("load() requires a Dalvik VM", e);
343        } catch (InvocationTargetException e) {
344            throw new RuntimeException(e.getCause());
345        } catch (InstantiationException e) {
346            throw new AssertionError();
347        } catch (NoSuchMethodException e) {
348            throw new AssertionError();
349        } catch (IllegalAccessException e) {
350            throw new AssertionError();
351        }
352    }
353
354    private static class TypeDeclaration {
355        private final TypeId<?> type;
356
357        /** declared state */
358        private boolean declared;
359        private int flags;
360        private TypeId<?> supertype;
361        private String sourceFile;
362        private TypeList interfaces;
363
364        private final Map<FieldId, FieldDeclaration> fields
365                = new LinkedHashMap<FieldId, FieldDeclaration>();
366        private final Map<MethodId, MethodDeclaration> methods
367                = new LinkedHashMap<MethodId, MethodDeclaration>();
368
369        TypeDeclaration(TypeId<?> type) {
370            this.type = type;
371        }
372
373        ClassDefItem toClassDefItem() {
374            if (!declared) {
375                throw new IllegalStateException("Undeclared type " + type + " declares members: "
376                        + fields.keySet() + " " + methods.keySet());
377            }
378
379            DexOptions dexOptions = new DexOptions();
380            dexOptions.targetApiLevel = DexFormat.API_NO_EXTENDED_OPCODES;
381
382            CstType thisType = type.constant;
383
384            ClassDefItem out = new ClassDefItem(thisType, flags, supertype.constant,
385                    interfaces.ropTypes, new CstString(sourceFile));
386
387            for (MethodDeclaration method : methods.values()) {
388                EncodedMethod encoded = method.toEncodedMethod(dexOptions);
389                if (method.isDirect()) {
390                    out.addDirectMethod(encoded);
391                } else {
392                    out.addVirtualMethod(encoded);
393                }
394            }
395            for (FieldDeclaration field : fields.values()) {
396                EncodedField encoded = field.toEncodedField();
397                if (field.isStatic()) {
398                    out.addStaticField(encoded, Constants.getConstant(field.staticValue));
399                } else {
400                    out.addInstanceField(encoded);
401                }
402            }
403
404            return out;
405        }
406    }
407
408    static class FieldDeclaration {
409        final FieldId<?, ?> fieldId;
410        private final int accessFlags;
411        private final Object staticValue;
412
413        FieldDeclaration(FieldId<?, ?> fieldId, int accessFlags, Object staticValue) {
414            if ((accessFlags & STATIC) == 0 && staticValue != null) {
415                throw new IllegalArgumentException("instance fields may not have a value");
416            }
417            this.fieldId = fieldId;
418            this.accessFlags = accessFlags;
419            this.staticValue = staticValue;
420        }
421
422        EncodedField toEncodedField() {
423            return new EncodedField(fieldId.constant, accessFlags);
424        }
425
426        public boolean isStatic() {
427            return (accessFlags & STATIC) != 0;
428        }
429    }
430
431    static class MethodDeclaration {
432        final MethodId<?, ?> method;
433        private final int flags;
434        private final Code code;
435
436        public MethodDeclaration(MethodId<?, ?> method, int flags) {
437            this.method = method;
438            this.flags = flags;
439            this.code = new Code(this);
440        }
441
442        boolean isStatic() {
443            return (flags & STATIC) != 0;
444        }
445
446        boolean isDirect() {
447            return (flags & (STATIC | PRIVATE | ACC_CONSTRUCTOR)) != 0;
448        }
449
450        EncodedMethod toEncodedMethod(DexOptions dexOptions) {
451            RopMethod ropMethod = new RopMethod(code.toBasicBlocks(), 0);
452            LocalVariableInfo locals = null;
453            DalvCode dalvCode = RopTranslator.translate(
454                    ropMethod, PositionList.NONE, locals, code.paramSize(), dexOptions);
455            return new EncodedMethod(method.constant, flags, dalvCode, StdTypeList.EMPTY);
456        }
457    }
458}
459