blob: 7a99142ab530b4afa4ecb543353bf3c5e52bcc68 [file] [log] [blame]
Maurice Chu667f9a82013-10-16 13:12:22 -07001/*
2 * Copyright (C) 2013 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 android.support.multidex;
18
Maurice Chu66f379f2013-11-14 19:08:32 -080019import dalvik.system.DexFile;
20
Maurice Chu667f9a82013-10-16 13:12:22 -070021import android.content.Context;
22import android.content.pm.ApplicationInfo;
23import android.content.pm.PackageManager;
24import android.os.Build;
25import android.util.Log;
26
Maurice Chu667f9a82013-10-16 13:12:22 -070027import java.io.File;
28import java.io.IOException;
29import java.lang.reflect.Array;
30import java.lang.reflect.Field;
31import java.lang.reflect.InvocationTargetException;
32import java.lang.reflect.Method;
33import java.util.ArrayList;
34import java.util.Arrays;
35import java.util.HashSet;
36import java.util.List;
37import java.util.ListIterator;
38import java.util.Set;
Maurice Chu66f379f2013-11-14 19:08:32 -080039import java.util.zip.ZipFile;
Maurice Chu667f9a82013-10-16 13:12:22 -070040
41/**
42 * Monkey patches {@link Context#getClassLoader() the application context class
43 * loader} in order to load classes from more than one dex file. The primary
44 * {@code classes.dex} file necessary for calling this class methods. secondary
45 * dex files named classes2.dex, classes".dex... found in the application apk
46 * will be added to the classloader after first call to
47 * {@link #install(Context)}.
48 *
49 * <p/>
50 * <strong>IMPORTANT:</strong>This library provides compatibility for platforms
51 * with API level 4 through 19. This library does nothing on newer versions of
52 * the platform which provide built-in support for secondary dex files.
53 */
54public final class MultiDex {
55
56 static final String TAG = "MultiDex";
57
58 private static final String SECONDARY_FOLDER_NAME = "secondary-dexes";
59
60 private static final int SUPPORTED_MULTIDEX_SDK_VERSION = 20;
61
62 private static final int MIN_SDK_VERSION = 4;
63
64 private static final Set<String> installedApk = new HashSet<String>();
65
66 private MultiDex() {}
67
68 /**
69 * Patches the application context class loader by appending extra dex files
70 * loaded from the application apk. Call this method first thing in your
71 * {@code Application#OnCreate}, {@code Instrumentation#OnCreate},
72 * {@code BackupAgent#OnCreate}, {@code Service#OnCreate},
73 * {@code BroadcastReceiver#onReceive}, {@code Activity#OnCreate} and
74 * {@code ContentProvider#OnCreate} .
75 *
76 * @param context application context.
77 * @throws RuntimeException if an error occurred preventing the classloader
78 * extension.
79 */
80 public static void install(Context context) {
81
82 if (Build.VERSION.SDK_INT < MIN_SDK_VERSION) {
83 throw new RuntimeException("Multi dex installation failed. SDK " + Build.VERSION.SDK_INT
84 + " is unsupported. Min SDK version is " + MIN_SDK_VERSION + ".");
85 }
86
87
88 try {
89 PackageManager pm;
90 String packageName;
91 try {
92 pm = context.getPackageManager();
93 packageName = context.getPackageName();
94 } catch (RuntimeException e) {
95 /* Ignore those exceptions so that we don't break tests relying on Context like
96 * a android.test.mock.MockContext or a android.content.ContextWrapper with a null
97 * base Context.
98 */
99 Log.w(TAG, "Failure while trying to obtain ApplicationInfo from Context. " +
100 "Must be running in test mode. Skip patching.", e);
101 return;
102 }
103 if (pm == null || packageName == null) {
104 // This is most likely a mock context, so just return without patching.
105 return;
106 }
107 ApplicationInfo applicationInfo =
108 pm.getApplicationInfo(packageName, PackageManager.GET_META_DATA);
109 if (applicationInfo == null) {
110 // This is from a mock context, so just return without patching.
111 return;
112 }
113
114 synchronized (installedApk) {
115 String apkPath = applicationInfo.sourceDir;
116 if (installedApk.contains(apkPath)) {
117 return;
118 }
119 installedApk.add(apkPath);
120
121 if (Build.VERSION.SDK_INT >= SUPPORTED_MULTIDEX_SDK_VERSION) {
122 // STOPSHIP: Any app that uses this class needs approval before being released
123 // as well as figuring out what the right behavior should be here.
124 throw new RuntimeException("Platform support of multidex for SDK " +
125 Build.VERSION.SDK_INT + " has not been confirmed yet.");
126 }
127
128 /* The patched class loader is expected to be a descendant of
129 * dalvik.system.BaseDexClassLoader. We modify its
130 * dalvik.system.DexPathList pathList field to append additional DEX
131 * file entries.
132 */
133 ClassLoader loader;
134 try {
135 loader = context.getClassLoader();
136 } catch (RuntimeException e) {
137 /* Ignore those exceptions so that we don't break tests relying on Context like
138 * a android.test.mock.MockContext or a android.content.ContextWrapper with a
139 * null base Context.
140 */
141 Log.w(TAG, "Failure while trying to obtain Context class loader. " +
142 "Must be running in test mode. Skip patching.", e);
143 return;
144 }
145 if (loader == null) {
146 // Note, the context class loader is null when running Robolectric tests.
147 Log.e(TAG,
148 "Context class loader is null. Must be running in test mode. "
149 + "Skip patching.");
150 return;
151 }
152
153 File dexDir = new File(context.getFilesDir(), SECONDARY_FOLDER_NAME);
Maurice Chucc63eda2013-12-02 15:39:59 -0800154 List<File> files = MultiDexExtractor.load(applicationInfo, dexDir, false);
155 if (checkValidZipFiles(files)) {
156 installSecondaryDexes(loader, dexDir, files);
157 } else {
158 Log.w(TAG, "Files were not valid zip files. Forcing a reload.");
159 // Try again, but this time force a reload of the zip file.
160 files = MultiDexExtractor.load(applicationInfo, dexDir, true);
161 if (checkValidZipFiles(files)) {
162 installSecondaryDexes(loader, dexDir, files);
Maurice Chu667f9a82013-10-16 13:12:22 -0700163 } else {
Maurice Chucc63eda2013-12-02 15:39:59 -0800164 // Second time didn't work, give up
165 throw new RuntimeException("Zip files were not valid.");
Maurice Chu667f9a82013-10-16 13:12:22 -0700166 }
167 }
168 }
169
170 } catch (Exception e) {
171 Log.e(TAG, "Multidex installation failure", e);
172 throw new RuntimeException("Multi dex installation failed (" + e.getMessage() + ").");
173 }
174 }
175
Maurice Chucc63eda2013-12-02 15:39:59 -0800176 private static void installSecondaryDexes(ClassLoader loader, File dexDir, List<File> files)
177 throws IllegalArgumentException, IllegalAccessException, NoSuchFieldException,
178 InvocationTargetException, NoSuchMethodException, IOException {
179 if (!files.isEmpty()) {
180 if (Build.VERSION.SDK_INT >= 19) {
181 V19.install(loader, files, dexDir);
182 } else if (Build.VERSION.SDK_INT >= 14) {
183 V14.install(loader, files, dexDir);
184 } else {
185 V4.install(loader, files);
186 }
187 }
188 }
189
190 /**
191 * Returns whether all files in the list are valid zip files. If {@code files} is empty, then
192 * returns true.
193 */
194 private static boolean checkValidZipFiles(List<File> files) {
195 for (File file : files) {
196 if (!MultiDexExtractor.verifyZipFile(file)) {
197 return false;
198 }
199 }
200 return true;
201 }
202
Maurice Chu667f9a82013-10-16 13:12:22 -0700203 /**
204 * Locates a given field anywhere in the class inheritance hierarchy.
205 *
206 * @param instance an object to search the field into.
207 * @param name field name
208 * @return a field object
209 * @throws NoSuchFieldException if the field cannot be located
210 */
211 private static Field findField(Object instance, String name) throws NoSuchFieldException {
212 for (Class<?> clazz = instance.getClass(); clazz != null; clazz = clazz.getSuperclass()) {
213 try {
214 Field field = clazz.getDeclaredField(name);
215
216
217 if (!field.isAccessible()) {
218 field.setAccessible(true);
219 }
220
221 return field;
222 } catch (NoSuchFieldException e) {
223 // ignore and search next
224 }
225 }
226
227 throw new NoSuchFieldException("Field " + name + " not found in " + instance.getClass());
228 }
229
230 /**
231 * Locates a given method anywhere in the class inheritance hierarchy.
232 *
233 * @param instance an object to search the method into.
234 * @param name method name
235 * @param parameterTypes method parameter types
236 * @return a method object
237 * @throws NoSuchMethodException if the method cannot be located
238 */
239 private static Method findMethod(Object instance, String name, Class<?>... parameterTypes)
240 throws NoSuchMethodException {
241 for (Class<?> clazz = instance.getClass(); clazz != null; clazz = clazz.getSuperclass()) {
242 try {
243 Method method = clazz.getDeclaredMethod(name, parameterTypes);
244
245
246 if (!method.isAccessible()) {
247 method.setAccessible(true);
248 }
249
250 return method;
251 } catch (NoSuchMethodException e) {
252 // ignore and search next
253 }
254 }
255
256 throw new NoSuchMethodException("Method " + name + " with parameters " +
257 Arrays.asList(parameterTypes) + " not found in " + instance.getClass());
258 }
259
260 /**
261 * Replace the value of a field containing a non null array, by a new array containing the
262 * elements of the original array plus the elements of extraElements.
263 * @param instance the instance whose field is to be modified.
264 * @param fieldName the field to modify.
265 * @param extraElements elements to append at the end of the array.
266 */
267 private static void expandFieldArray(Object instance, String fieldName,
268 Object[] extraElements) throws NoSuchFieldException, IllegalArgumentException,
269 IllegalAccessException {
270 Field jlrField = findField(instance, fieldName);
271 Object[] original = (Object[]) jlrField.get(instance);
272 Object[] combined = (Object[]) Array.newInstance(
273 original.getClass().getComponentType(), original.length + extraElements.length);
274 System.arraycopy(original, 0, combined, 0, original.length);
275 System.arraycopy(extraElements, 0, combined, original.length, extraElements.length);
276 jlrField.set(instance, combined);
277 }
278
279 /**
280 * Installer for platform versions 19.
281 */
282 private static final class V19 {
283
284 private static void install(ClassLoader loader, List<File> additionalClassPathEntries,
285 File optimizedDirectory)
286 throws IllegalArgumentException, IllegalAccessException,
287 NoSuchFieldException, InvocationTargetException, NoSuchMethodException {
288 /* The patched class loader is expected to be a descendant of
289 * dalvik.system.BaseDexClassLoader. We modify its
290 * dalvik.system.DexPathList pathList field to append additional DEX
291 * file entries.
292 */
293 Field pathListField = findField(loader, "pathList");
294 Object dexPathList = pathListField.get(loader);
295 ArrayList<IOException> suppressedExceptions = new ArrayList<IOException>();
296 expandFieldArray(dexPathList, "dexElements", makeDexElements(dexPathList,
297 new ArrayList<File>(additionalClassPathEntries), optimizedDirectory,
298 suppressedExceptions));
299 if (suppressedExceptions.size() > 0) {
Yohann Roussel88117c32013-11-28 23:22:11 +0100300 for (IOException e : suppressedExceptions) {
301 Log.w(TAG, "Exception in makeDexElement", e);
302 }
Maurice Chu667f9a82013-10-16 13:12:22 -0700303 Field suppressedExceptionsField =
304 findField(loader, "dexElementsSuppressedExceptions");
305 IOException[] dexElementsSuppressedExceptions =
306 (IOException[]) suppressedExceptionsField.get(loader);
307
308 if (dexElementsSuppressedExceptions == null) {
309 dexElementsSuppressedExceptions =
310 suppressedExceptions.toArray(
311 new IOException[suppressedExceptions.size()]);
312 } else {
313 IOException[] combined =
314 new IOException[suppressedExceptions.size() +
315 dexElementsSuppressedExceptions.length];
316 suppressedExceptions.toArray(combined);
317 System.arraycopy(dexElementsSuppressedExceptions, 0, combined,
318 suppressedExceptions.size(), dexElementsSuppressedExceptions.length);
319 dexElementsSuppressedExceptions = combined;
320 }
321
322 suppressedExceptionsField.set(loader, dexElementsSuppressedExceptions);
323 }
324 }
325
326 /**
327 * A wrapper around
328 * {@code private static final dalvik.system.DexPathList#makeDexElements}.
329 */
330 private static Object[] makeDexElements(
331 Object dexPathList, ArrayList<File> files, File optimizedDirectory,
332 ArrayList<IOException> suppressedExceptions)
333 throws IllegalAccessException, InvocationTargetException,
334 NoSuchMethodException {
335 Method makeDexElements =
336 findMethod(dexPathList, "makeDexElements", ArrayList.class, File.class,
337 ArrayList.class);
338
339 return (Object[]) makeDexElements.invoke(dexPathList, files, optimizedDirectory,
340 suppressedExceptions);
341 }
342 }
343
344 /**
345 * Installer for platform versions 14, 15, 16, 17 and 18.
346 */
347 private static final class V14 {
348
349 private static void install(ClassLoader loader, List<File> additionalClassPathEntries,
350 File optimizedDirectory)
351 throws IllegalArgumentException, IllegalAccessException,
352 NoSuchFieldException, InvocationTargetException, NoSuchMethodException {
353 /* The patched class loader is expected to be a descendant of
354 * dalvik.system.BaseDexClassLoader. We modify its
355 * dalvik.system.DexPathList pathList field to append additional DEX
356 * file entries.
357 */
358 Field pathListField = findField(loader, "pathList");
359 Object dexPathList = pathListField.get(loader);
360 expandFieldArray(dexPathList, "dexElements", makeDexElements(dexPathList,
361 new ArrayList<File>(additionalClassPathEntries), optimizedDirectory));
362 }
363
364 /**
365 * A wrapper around
366 * {@code private static final dalvik.system.DexPathList#makeDexElements}.
367 */
368 private static Object[] makeDexElements(
369 Object dexPathList, ArrayList<File> files, File optimizedDirectory)
370 throws IllegalAccessException, InvocationTargetException,
371 NoSuchMethodException {
372 Method makeDexElements =
373 findMethod(dexPathList, "makeDexElements", ArrayList.class, File.class);
374
375 return (Object[]) makeDexElements.invoke(dexPathList, files, optimizedDirectory);
376 }
377 }
378
379 /**
380 * Installer for platform versions 4 to 13.
381 */
382 private static final class V4 {
Yohann Roussel52eafa02013-11-21 11:46:53 +0100383 private static void install(ClassLoader loader, List<File> additionalClassPathEntries)
Maurice Chu667f9a82013-10-16 13:12:22 -0700384 throws IllegalArgumentException, IllegalAccessException,
385 NoSuchFieldException, IOException {
386 /* The patched class loader is expected to be a descendant of
387 * dalvik.system.DexClassLoader. We modify its
Yohann Roussel52eafa02013-11-21 11:46:53 +0100388 * fields mPaths, mFiles, mZips and mDexs to append additional DEX
Maurice Chu667f9a82013-10-16 13:12:22 -0700389 * file entries.
390 */
391 int extraSize = additionalClassPathEntries.size();
392
393 Field pathField = findField(loader, "path");
394
395 StringBuilder path = new StringBuilder((String) pathField.get(loader));
396 String[] extraPaths = new String[extraSize];
397 File[] extraFiles = new File[extraSize];
Maurice Chu66f379f2013-11-14 19:08:32 -0800398 ZipFile[] extraZips = new ZipFile[extraSize];
Maurice Chu667f9a82013-10-16 13:12:22 -0700399 DexFile[] extraDexs = new DexFile[extraSize];
400 for (ListIterator<File> iterator = additionalClassPathEntries.listIterator();
401 iterator.hasNext();) {
402 File additionalEntry = iterator.next();
403 String entryPath = additionalEntry.getAbsolutePath();
404 path.append(':').append(entryPath);
405 int index = iterator.previousIndex();
406 extraPaths[index] = entryPath;
407 extraFiles[index] = additionalEntry;
Maurice Chu66f379f2013-11-14 19:08:32 -0800408 extraZips[index] = new ZipFile(additionalEntry);
Maurice Chu667f9a82013-10-16 13:12:22 -0700409 extraDexs[index] = DexFile.loadDex(entryPath, entryPath + ".dex", 0);
410 }
411
412 pathField.set(loader, path.toString());
413 expandFieldArray(loader, "mPaths", extraPaths);
414 expandFieldArray(loader, "mFiles", extraFiles);
Maurice Chu66f379f2013-11-14 19:08:32 -0800415 expandFieldArray(loader, "mZips", extraZips);
Maurice Chu667f9a82013-10-16 13:12:22 -0700416 expandFieldArray(loader, "mDexs", extraDexs);
417 }
418 }
419
420}