1/* 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 19import android.content.Context; 20import android.content.SharedPreferences; 21import android.content.pm.ApplicationInfo; 22import android.os.Build; 23import android.util.Log; 24 25import java.io.BufferedOutputStream; 26import java.io.Closeable; 27import java.io.File; 28import java.io.FileFilter; 29import java.io.FileNotFoundException; 30import java.io.FileOutputStream; 31import java.io.IOException; 32import java.io.InputStream; 33import java.lang.reflect.InvocationTargetException; 34import java.lang.reflect.Method; 35import java.util.ArrayList; 36import java.util.List; 37import java.util.zip.ZipEntry; 38import java.util.zip.ZipException; 39import java.util.zip.ZipFile; 40import java.util.zip.ZipOutputStream; 41 42/** 43 * Exposes application secondary dex files as files in the application data 44 * directory. 45 */ 46final class MultiDexExtractor { 47 48 private static final String TAG = MultiDex.TAG; 49 50 /** 51 * We look for additional dex files named {@code classes2.dex}, 52 * {@code classes3.dex}, etc. 53 */ 54 private static final String DEX_PREFIX = "classes"; 55 private static final String DEX_SUFFIX = ".dex"; 56 57 private static final String EXTRACTED_NAME_EXT = ".classes"; 58 private static final String EXTRACTED_SUFFIX = ".zip"; 59 private static final int MAX_EXTRACT_ATTEMPTS = 3; 60 61 private static final String PREFS_FILE = "multidex.version"; 62 private static final String KEY_TIME_STAMP = "timestamp"; 63 private static final String KEY_CRC = "crc"; 64 private static final String KEY_DEX_NUMBER = "dex.number"; 65 66 /** 67 * Size of reading buffers. 68 */ 69 private static final int BUFFER_SIZE = 0x4000; 70 /* Keep value away from 0 because it is a too probable time stamp value */ 71 private static final long NO_VALUE = -1L; 72 73 /** 74 * Extracts application secondary dexes into files in the application data 75 * directory. 76 * 77 * @return a list of files that were created. The list may be empty if there 78 * are no secondary dex files. 79 * @throws IOException if encounters a problem while reading or writing 80 * secondary dex files 81 */ 82 static List<File> load(Context context, ApplicationInfo applicationInfo, File dexDir, 83 boolean forceReload) throws IOException { 84 Log.i(TAG, "MultiDexExtractor.load(" + applicationInfo.sourceDir + ", " + forceReload + ")"); 85 final File sourceApk = new File(applicationInfo.sourceDir); 86 87 long currentCrc = getZipCrc(sourceApk); 88 89 List<File> files; 90 if (!forceReload && !isModified(context, sourceApk, currentCrc)) { 91 try { 92 files = loadExistingExtractions(context, sourceApk, dexDir); 93 } catch (IOException ioe) { 94 Log.w(TAG, "Failed to reload existing extracted secondary dex files," 95 + " falling back to fresh extraction", ioe); 96 files = performExtractions(sourceApk, dexDir); 97 putStoredApkInfo(context, getTimeStamp(sourceApk), currentCrc, files.size() + 1); 98 99 } 100 } else { 101 Log.i(TAG, "Detected that extraction must be performed."); 102 files = performExtractions(sourceApk, dexDir); 103 putStoredApkInfo(context, getTimeStamp(sourceApk), currentCrc, files.size() + 1); 104 } 105 106 Log.i(TAG, "load found " + files.size() + " secondary dex files"); 107 return files; 108 } 109 110 private static List<File> loadExistingExtractions(Context context, File sourceApk, File dexDir) 111 throws IOException { 112 Log.i(TAG, "loading existing secondary dex files"); 113 114 final String extractedFilePrefix = sourceApk.getName() + EXTRACTED_NAME_EXT; 115 int totalDexNumber = getMultiDexPreferences(context).getInt(KEY_DEX_NUMBER, 1); 116 final List<File> files = new ArrayList<File>(totalDexNumber); 117 118 for (int secondaryNumber = 2; secondaryNumber <= totalDexNumber; secondaryNumber++) { 119 String fileName = extractedFilePrefix + secondaryNumber + EXTRACTED_SUFFIX; 120 File extractedFile = new File(dexDir, fileName); 121 if (extractedFile.isFile()) { 122 files.add(extractedFile); 123 if (!verifyZipFile(extractedFile)) { 124 Log.i(TAG, "Invalid zip file: " + extractedFile); 125 throw new IOException("Invalid ZIP file."); 126 } 127 } else { 128 throw new IOException("Missing extracted secondary dex file '" + 129 extractedFile.getPath() + "'"); 130 } 131 } 132 133 return files; 134 } 135 136 private static boolean isModified(Context context, File archive, long currentCrc) { 137 SharedPreferences prefs = getMultiDexPreferences(context); 138 return (prefs.getLong(KEY_TIME_STAMP, NO_VALUE) != getTimeStamp(archive)) 139 || (prefs.getLong(KEY_CRC, NO_VALUE) != currentCrc); 140 } 141 142 private static long getTimeStamp(File archive) { 143 long timeStamp = archive.lastModified(); 144 if (timeStamp == NO_VALUE) { 145 // never return NO_VALUE 146 timeStamp--; 147 } 148 return timeStamp; 149 } 150 151 152 private static long getZipCrc(File archive) throws IOException { 153 long computedValue = ZipUtil.getZipCrc(archive); 154 if (computedValue == NO_VALUE) { 155 // never return NO_VALUE 156 computedValue--; 157 } 158 return computedValue; 159 } 160 161 private static List<File> performExtractions(File sourceApk, File dexDir) 162 throws IOException { 163 164 final String extractedFilePrefix = sourceApk.getName() + EXTRACTED_NAME_EXT; 165 166 // Ensure that whatever deletions happen in prepareDexDir only happen if the zip that 167 // contains a secondary dex file in there is not consistent with the latest apk. Otherwise, 168 // multi-process race conditions can cause a crash loop where one process deletes the zip 169 // while another had created it. 170 prepareDexDir(dexDir, extractedFilePrefix); 171 172 List<File> files = new ArrayList<File>(); 173 174 final ZipFile apk = new ZipFile(sourceApk); 175 try { 176 177 int secondaryNumber = 2; 178 179 ZipEntry dexFile = apk.getEntry(DEX_PREFIX + secondaryNumber + DEX_SUFFIX); 180 while (dexFile != null) { 181 String fileName = extractedFilePrefix + secondaryNumber + EXTRACTED_SUFFIX; 182 File extractedFile = new File(dexDir, fileName); 183 files.add(extractedFile); 184 185 Log.i(TAG, "Extraction is needed for file " + extractedFile); 186 int numAttempts = 0; 187 boolean isExtractionSuccessful = false; 188 while (numAttempts < MAX_EXTRACT_ATTEMPTS && !isExtractionSuccessful) { 189 numAttempts++; 190 191 // Create a zip file (extractedFile) containing only the secondary dex file 192 // (dexFile) from the apk. 193 extract(apk, dexFile, extractedFile, extractedFilePrefix); 194 195 // Verify that the extracted file is indeed a zip file. 196 isExtractionSuccessful = verifyZipFile(extractedFile); 197 198 // Log the sha1 of the extracted zip file 199 Log.i(TAG, "Extraction " + (isExtractionSuccessful ? "success" : "failed") + 200 " - length " + extractedFile.getAbsolutePath() + ": " + 201 extractedFile.length()); 202 if (!isExtractionSuccessful) { 203 // Delete the extracted file 204 extractedFile.delete(); 205 if (extractedFile.exists()) { 206 Log.w(TAG, "Failed to delete corrupted secondary dex '" + 207 extractedFile.getPath() + "'"); 208 } 209 } 210 } 211 if (!isExtractionSuccessful) { 212 throw new IOException("Could not create zip file " + 213 extractedFile.getAbsolutePath() + " for secondary dex (" + 214 secondaryNumber + ")"); 215 } 216 secondaryNumber++; 217 dexFile = apk.getEntry(DEX_PREFIX + secondaryNumber + DEX_SUFFIX); 218 } 219 } finally { 220 try { 221 apk.close(); 222 } catch (IOException e) { 223 Log.w(TAG, "Failed to close resource", e); 224 } 225 } 226 227 return files; 228 } 229 230 private static void putStoredApkInfo(Context context, long timeStamp, long crc, 231 int totalDexNumber) { 232 SharedPreferences prefs = getMultiDexPreferences(context); 233 SharedPreferences.Editor edit = prefs.edit(); 234 edit.putLong(KEY_TIME_STAMP, timeStamp); 235 edit.putLong(KEY_CRC, crc); 236 /* SharedPreferences.Editor doc says that apply() and commit() "atomically performs the 237 * requested modifications" it should be OK to rely on saving the dex files number (getting 238 * old number value would go along with old crc and time stamp). 239 */ 240 edit.putInt(KEY_DEX_NUMBER, totalDexNumber); 241 apply(edit); 242 } 243 244 private static SharedPreferences getMultiDexPreferences(Context context) { 245 return context.getSharedPreferences(PREFS_FILE, 246 Build.VERSION.SDK_INT < 11 /* Build.VERSION_CODES.HONEYCOMB */ 247 ? Context.MODE_PRIVATE 248 : Context.MODE_PRIVATE | 0x0004 /* Context.MODE_MULTI_PROCESS */); 249 } 250 251 /** 252 * This removes any files that do not have the correct prefix. 253 */ 254 private static void prepareDexDir(File dexDir, final String extractedFilePrefix) { 255 // Clean possible old files 256 FileFilter filter = new FileFilter() { 257 258 @Override 259 public boolean accept(File pathname) { 260 return !pathname.getName().startsWith(extractedFilePrefix); 261 } 262 }; 263 File[] files = dexDir.listFiles(filter); 264 if (files == null) { 265 Log.w(TAG, "Failed to list secondary dex dir content (" + dexDir.getPath() + ")."); 266 return; 267 } 268 for (File oldFile : files) { 269 Log.i(TAG, "Trying to delete old file " + oldFile.getPath() + " of size " + 270 oldFile.length()); 271 if (!oldFile.delete()) { 272 Log.w(TAG, "Failed to delete old file " + oldFile.getPath()); 273 } else { 274 Log.i(TAG, "Deleted old file " + oldFile.getPath()); 275 } 276 } 277 } 278 279 private static void extract(ZipFile apk, ZipEntry dexFile, File extractTo, 280 String extractedFilePrefix) throws IOException, FileNotFoundException { 281 282 InputStream in = apk.getInputStream(dexFile); 283 ZipOutputStream out = null; 284 File tmp = File.createTempFile(extractedFilePrefix, EXTRACTED_SUFFIX, 285 extractTo.getParentFile()); 286 Log.i(TAG, "Extracting " + tmp.getPath()); 287 try { 288 out = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(tmp))); 289 try { 290 ZipEntry classesDex = new ZipEntry("classes.dex"); 291 // keep zip entry time since it is the criteria used by Dalvik 292 classesDex.setTime(dexFile.getTime()); 293 out.putNextEntry(classesDex); 294 295 byte[] buffer = new byte[BUFFER_SIZE]; 296 int length = in.read(buffer); 297 while (length != -1) { 298 out.write(buffer, 0, length); 299 length = in.read(buffer); 300 } 301 out.closeEntry(); 302 } finally { 303 out.close(); 304 } 305 Log.i(TAG, "Renaming to " + extractTo.getPath()); 306 if (!tmp.renameTo(extractTo)) { 307 throw new IOException("Failed to rename \"" + tmp.getAbsolutePath() + 308 "\" to \"" + extractTo.getAbsolutePath() + "\""); 309 } 310 } finally { 311 closeQuietly(in); 312 tmp.delete(); // return status ignored 313 } 314 } 315 316 /** 317 * Returns whether the file is a valid zip file. 318 */ 319 static boolean verifyZipFile(File file) { 320 try { 321 ZipFile zipFile = new ZipFile(file); 322 try { 323 zipFile.close(); 324 return true; 325 } catch (IOException e) { 326 Log.w(TAG, "Failed to close zip file: " + file.getAbsolutePath()); 327 } 328 } catch (ZipException ex) { 329 Log.w(TAG, "File " + file.getAbsolutePath() + " is not a valid zip file.", ex); 330 } catch (IOException ex) { 331 Log.w(TAG, "Got an IOException trying to open zip file: " + file.getAbsolutePath(), ex); 332 } 333 return false; 334 } 335 336 /** 337 * Closes the given {@code Closeable}. Suppresses any IO exceptions. 338 */ 339 private static void closeQuietly(Closeable closeable) { 340 try { 341 closeable.close(); 342 } catch (IOException e) { 343 Log.w(TAG, "Failed to close resource", e); 344 } 345 } 346 347 // The following is taken from SharedPreferencesCompat to avoid having a dependency of the 348 // multidex support library on another support library. 349 private static Method sApplyMethod; // final 350 static { 351 try { 352 Class<?> cls = SharedPreferences.Editor.class; 353 sApplyMethod = cls.getMethod("apply"); 354 } catch (NoSuchMethodException unused) { 355 sApplyMethod = null; 356 } 357 } 358 359 private static void apply(SharedPreferences.Editor editor) { 360 if (sApplyMethod != null) { 361 try { 362 sApplyMethod.invoke(editor); 363 return; 364 } catch (InvocationTargetException unused) { 365 // fall through 366 } catch (IllegalAccessException unused) { 367 // fall through 368 } 369 } 370 editor.commit(); 371 } 372} 373