PackageDexOptimizer.java revision c7b9482b0c4bb2d378e63541b96be45c50094e05
1/* 2 * Copyright (C) 2015 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.android.server.pm; 18 19import android.annotation.Nullable; 20import android.content.Context; 21import android.content.pm.ApplicationInfo; 22import android.content.pm.PackageParser; 23import android.os.Environment; 24import android.os.PowerManager; 25import android.os.UserHandle; 26import android.os.WorkSource; 27import android.util.Log; 28import android.util.Slog; 29 30import com.android.internal.os.InstallerConnection.InstallerException; 31 32import java.io.File; 33import java.io.IOException; 34import java.util.List; 35 36import dalvik.system.DexFile; 37 38import static com.android.server.pm.Installer.DEXOPT_BOOTCOMPLETE; 39import static com.android.server.pm.Installer.DEXOPT_DEBUGGABLE; 40import static com.android.server.pm.Installer.DEXOPT_PROFILE_GUIDED; 41import static com.android.server.pm.Installer.DEXOPT_PUBLIC; 42import static com.android.server.pm.Installer.DEXOPT_SAFEMODE; 43import static com.android.server.pm.InstructionSets.getAppDexInstructionSets; 44import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets; 45import static com.android.server.pm.PackageManagerServiceCompilerMapping.getNonProfileGuidedCompilerFilter; 46 47/** 48 * Helper class for running dexopt command on packages. 49 */ 50class PackageDexOptimizer { 51 private static final String TAG = "PackageManager.DexOptimizer"; 52 static final String OAT_DIR_NAME = "oat"; 53 // TODO b/19550105 Remove error codes and use exceptions 54 static final int DEX_OPT_SKIPPED = 0; 55 static final int DEX_OPT_PERFORMED = 1; 56 static final int DEX_OPT_FAILED = -1; 57 58 private final Installer mInstaller; 59 private final Object mInstallLock; 60 61 private final PowerManager.WakeLock mDexoptWakeLock; 62 private volatile boolean mSystemReady; 63 64 PackageDexOptimizer(Installer installer, Object installLock, Context context, 65 String wakeLockTag) { 66 this.mInstaller = installer; 67 this.mInstallLock = installLock; 68 69 PowerManager powerManager = (PowerManager)context.getSystemService(Context.POWER_SERVICE); 70 mDexoptWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, wakeLockTag); 71 } 72 73 protected PackageDexOptimizer(PackageDexOptimizer from) { 74 this.mInstaller = from.mInstaller; 75 this.mInstallLock = from.mInstallLock; 76 this.mDexoptWakeLock = from.mDexoptWakeLock; 77 this.mSystemReady = from.mSystemReady; 78 } 79 80 static boolean canOptimizePackage(PackageParser.Package pkg) { 81 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0; 82 } 83 84 /** 85 * Performs dexopt on all code paths and libraries of the specified package for specified 86 * instruction sets. 87 * 88 * <p>Calls to {@link com.android.server.pm.Installer#dexopt} on {@link #mInstaller} are 89 * synchronized on {@link #mInstallLock}. 90 */ 91 int performDexOpt(PackageParser.Package pkg, String[] sharedLibraries, 92 String[] instructionSets, boolean checkProfiles, String targetCompilationFilter) { 93 synchronized (mInstallLock) { 94 final boolean useLock = mSystemReady; 95 if (useLock) { 96 mDexoptWakeLock.setWorkSource(new WorkSource(pkg.applicationInfo.uid)); 97 mDexoptWakeLock.acquire(); 98 } 99 try { 100 return performDexOptLI(pkg, sharedLibraries, instructionSets, checkProfiles, 101 targetCompilationFilter); 102 } finally { 103 if (useLock) { 104 mDexoptWakeLock.release(); 105 } 106 } 107 } 108 } 109 110 /** 111 * Adjust the given dexopt-needed value. Can be overridden to influence the decision to 112 * optimize or not (and in what way). 113 */ 114 protected int adjustDexoptNeeded(int dexoptNeeded) { 115 return dexoptNeeded; 116 } 117 118 /** 119 * Adjust the given dexopt flags that will be passed to the installer. 120 */ 121 protected int adjustDexoptFlags(int dexoptFlags) { 122 return dexoptFlags; 123 } 124 125 private int performDexOptLI(PackageParser.Package pkg, String[] sharedLibraries, 126 String[] targetInstructionSets, boolean checkProfiles, String targetCompilerFilter) { 127 final String[] instructionSets = targetInstructionSets != null ? 128 targetInstructionSets : getAppDexInstructionSets(pkg.applicationInfo); 129 130 if (!canOptimizePackage(pkg)) { 131 return DEX_OPT_SKIPPED; 132 } 133 134 final List<String> paths = pkg.getAllCodePathsExcludingResourceOnly(); 135 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 136 137 boolean isProfileGuidedFilter = DexFile.isProfileGuidedCompilerFilter(targetCompilerFilter); 138 // If any part of the app is used by other apps, we cannot use profile-guided 139 // compilation. 140 if (isProfileGuidedFilter && isUsedByOtherApps(pkg)) { 141 checkProfiles = false; 142 143 targetCompilerFilter = getNonProfileGuidedCompilerFilter(targetCompilerFilter); 144 if (DexFile.isProfileGuidedCompilerFilter(targetCompilerFilter)) { 145 throw new IllegalStateException(targetCompilerFilter); 146 } 147 isProfileGuidedFilter = false; 148 } 149 150 // If we're asked to take profile updates into account, check now. 151 boolean newProfile = false; 152 if (checkProfiles && isProfileGuidedFilter) { 153 // Merge profiles, see if we need to do anything. 154 try { 155 newProfile = mInstaller.mergeProfiles(sharedGid, pkg.packageName); 156 } catch (InstallerException e) { 157 Slog.w(TAG, "Failed to merge profiles", e); 158 } 159 } 160 161 final boolean vmSafeMode = (pkg.applicationInfo.flags & ApplicationInfo.FLAG_VM_SAFE_MODE) != 0; 162 final boolean debuggable = (pkg.applicationInfo.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0; 163 164 boolean performedDexOpt = false; 165 boolean successfulDexOpt = true; 166 167 final String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 168 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 169 for (String path : paths) { 170 int dexoptNeeded; 171 try { 172 dexoptNeeded = DexFile.getDexOptNeeded(path, 173 dexCodeInstructionSet, targetCompilerFilter, newProfile); 174 } catch (IOException ioe) { 175 Slog.w(TAG, "IOException reading apk: " + path, ioe); 176 return DEX_OPT_FAILED; 177 } 178 dexoptNeeded = adjustDexoptNeeded(dexoptNeeded); 179 if (PackageManagerService.DEBUG_DEXOPT) { 180 Log.i(TAG, "DexoptNeeded for " + path + "@" + targetCompilerFilter + " is " + 181 dexoptNeeded); 182 } 183 184 final String dexoptType; 185 String oatDir = null; 186 switch (dexoptNeeded) { 187 case DexFile.NO_DEXOPT_NEEDED: 188 continue; 189 case DexFile.DEX2OAT_NEEDED: 190 dexoptType = "dex2oat"; 191 oatDir = createOatDirIfSupported(pkg, dexCodeInstructionSet); 192 break; 193 case DexFile.PATCHOAT_NEEDED: 194 dexoptType = "patchoat"; 195 break; 196 case DexFile.SELF_PATCHOAT_NEEDED: 197 dexoptType = "self patchoat"; 198 break; 199 default: 200 throw new IllegalStateException("Invalid dexopt:" + dexoptNeeded); 201 } 202 203 String sharedLibrariesPath = null; 204 if (sharedLibraries != null && sharedLibraries.length != 0) { 205 StringBuilder sb = new StringBuilder(); 206 for (String lib : sharedLibraries) { 207 if (sb.length() != 0) { 208 sb.append(":"); 209 } 210 sb.append(lib); 211 } 212 sharedLibrariesPath = sb.toString(); 213 } 214 Log.i(TAG, "Running dexopt (" + dexoptType + ") on: " + path + " pkg=" 215 + pkg.applicationInfo.packageName + " isa=" + dexCodeInstructionSet 216 + " vmSafeMode=" + vmSafeMode + " debuggable=" + debuggable 217 + " target-filter=" + targetCompilerFilter + " oatDir = " + oatDir 218 + " sharedLibraries=" + sharedLibrariesPath); 219 // Profile guide compiled oat files should not be public. 220 final boolean isPublic = !pkg.isForwardLocked() && !isProfileGuidedFilter; 221 final int profileFlag = isProfileGuidedFilter ? DEXOPT_PROFILE_GUIDED : 0; 222 final int dexFlags = adjustDexoptFlags( 223 ( isPublic ? DEXOPT_PUBLIC : 0) 224 | (vmSafeMode ? DEXOPT_SAFEMODE : 0) 225 | (debuggable ? DEXOPT_DEBUGGABLE : 0) 226 | profileFlag 227 | DEXOPT_BOOTCOMPLETE); 228 229 try { 230 mInstaller.dexopt(path, sharedGid, pkg.packageName, dexCodeInstructionSet, 231 dexoptNeeded, oatDir, dexFlags, targetCompilerFilter, pkg.volumeUuid, 232 sharedLibrariesPath); 233 performedDexOpt = true; 234 } catch (InstallerException e) { 235 Slog.w(TAG, "Failed to dexopt", e); 236 successfulDexOpt = false; 237 } 238 } 239 } 240 241 if (successfulDexOpt) { 242 // If we've gotten here, we're sure that no error occurred. We've either 243 // dex-opted one or more paths or instruction sets or we've skipped 244 // all of them because they are up to date. In both cases this package 245 // doesn't need dexopt any longer. 246 return performedDexOpt ? DEX_OPT_PERFORMED : DEX_OPT_SKIPPED; 247 } else { 248 return DEX_OPT_FAILED; 249 } 250 } 251 252 /** 253 * Creates oat dir for the specified package. In certain cases oat directory 254 * <strong>cannot</strong> be created: 255 * <ul> 256 * <li>{@code pkg} is a system app, which is not updated.</li> 257 * <li>Package location is not a directory, i.e. monolithic install.</li> 258 * </ul> 259 * 260 * @return Absolute path to the oat directory or null, if oat directory 261 * cannot be created. 262 */ 263 @Nullable 264 private String createOatDirIfSupported(PackageParser.Package pkg, String dexInstructionSet) { 265 if (!pkg.canHaveOatDir()) { 266 return null; 267 } 268 File codePath = new File(pkg.codePath); 269 if (codePath.isDirectory()) { 270 File oatDir = getOatDir(codePath); 271 try { 272 mInstaller.createOatDir(oatDir.getAbsolutePath(), dexInstructionSet); 273 } catch (InstallerException e) { 274 Slog.w(TAG, "Failed to create oat dir", e); 275 return null; 276 } 277 return oatDir.getAbsolutePath(); 278 } 279 return null; 280 } 281 282 static File getOatDir(File codePath) { 283 return new File(codePath, OAT_DIR_NAME); 284 } 285 286 void systemReady() { 287 mSystemReady = true; 288 } 289 290 /** 291 * Returns true if the profiling data collected for the given app indicate 292 * that the apps's APK has been loaded by another app. 293 * Note that this returns false for all forward-locked apps and apps without 294 * any collected profiling data. 295 */ 296 public static boolean isUsedByOtherApps(PackageParser.Package pkg) { 297 if (pkg.isForwardLocked()) { 298 // Skip the check for forward locked packages since they don't share their code. 299 return false; 300 } 301 302 for (String apkPath : pkg.getAllCodePathsExcludingResourceOnly()) { 303 try { 304 apkPath = new File(apkPath).getCanonicalPath(); 305 } catch (IOException e) { 306 // Log an error but continue without it. 307 Slog.w(TAG, "Failed to get canonical path", e); 308 } 309 String useMarker = apkPath.replace('/', '@'); 310 final int[] currentUserIds = UserManagerService.getInstance().getUserIds(); 311 for (int i = 0; i < currentUserIds.length; i++) { 312 File profileDir = 313 Environment.getDataProfilesDeForeignDexDirectory(currentUserIds[i]); 314 File foreignUseMark = new File(profileDir, useMarker); 315 if (foreignUseMark.exists()) { 316 return true; 317 } 318 } 319 } 320 return false; 321 } 322 323 /** 324 * A specialized PackageDexOptimizer that overrides already-installed checks, forcing a 325 * dexopt path. 326 */ 327 public static class ForcedUpdatePackageDexOptimizer extends PackageDexOptimizer { 328 329 public ForcedUpdatePackageDexOptimizer(Installer installer, Object installLock, 330 Context context, String wakeLockTag) { 331 super(installer, installLock, context, wakeLockTag); 332 } 333 334 public ForcedUpdatePackageDexOptimizer(PackageDexOptimizer from) { 335 super(from); 336 } 337 338 @Override 339 protected int adjustDexoptNeeded(int dexoptNeeded) { 340 // Ensure compilation, no matter the current state. 341 // TODO: The return value is wrong when patchoat is needed. 342 return DexFile.DEX2OAT_NEEDED; 343 } 344 } 345} 346