PackageDexOptimizer.java revision c6540daf8388ce1ebd2e4157ec70b9651ae14b4f
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.FileUtils; 24import android.os.PowerManager; 25import android.os.SystemClock; 26import android.os.SystemProperties; 27import android.os.UserHandle; 28import android.os.WorkSource; 29import android.util.Log; 30import android.util.Slog; 31 32import com.android.internal.annotations.GuardedBy; 33import com.android.internal.util.IndentingPrintWriter; 34import com.android.server.pm.Installer.InstallerException; 35import com.android.server.pm.dex.DexManager; 36import com.android.server.pm.dex.DexoptOptions; 37import com.android.server.pm.dex.DexoptUtils; 38import com.android.server.pm.dex.PackageDexUsage; 39 40import java.io.File; 41import java.io.IOException; 42import java.util.ArrayList; 43import java.util.Arrays; 44import java.util.List; 45import java.util.Map; 46 47import dalvik.system.DexFile; 48 49import static com.android.server.pm.Installer.DEXOPT_BOOTCOMPLETE; 50import static com.android.server.pm.Installer.DEXOPT_DEBUGGABLE; 51import static com.android.server.pm.Installer.DEXOPT_PROFILE_GUIDED; 52import static com.android.server.pm.Installer.DEXOPT_PUBLIC; 53import static com.android.server.pm.Installer.DEXOPT_SECONDARY_DEX; 54import static com.android.server.pm.Installer.DEXOPT_FORCE; 55import static com.android.server.pm.Installer.DEXOPT_STORAGE_CE; 56import static com.android.server.pm.Installer.DEXOPT_STORAGE_DE; 57import static com.android.server.pm.Installer.DEXOPT_IDLE_BACKGROUND_JOB; 58import static com.android.server.pm.InstructionSets.getAppDexInstructionSets; 59import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets; 60 61import static com.android.server.pm.PackageManagerService.WATCHDOG_TIMEOUT; 62 63import static dalvik.system.DexFile.getNonProfileGuidedCompilerFilter; 64import static dalvik.system.DexFile.getSafeModeCompilerFilter; 65import static dalvik.system.DexFile.isProfileGuidedCompilerFilter; 66 67/** 68 * Helper class for running dexopt command on packages. 69 */ 70public class PackageDexOptimizer { 71 private static final String TAG = "PackageManager.DexOptimizer"; 72 static final String OAT_DIR_NAME = "oat"; 73 // TODO b/19550105 Remove error codes and use exceptions 74 public static final int DEX_OPT_SKIPPED = 0; 75 public static final int DEX_OPT_PERFORMED = 1; 76 public static final int DEX_OPT_FAILED = -1; 77 // One minute over PM WATCHDOG_TIMEOUT 78 private static final long WAKELOCK_TIMEOUT_MS = WATCHDOG_TIMEOUT + 1000 * 60; 79 80 /** Special library name that skips shared libraries check during compilation. */ 81 public static final String SKIP_SHARED_LIBRARY_CHECK = "&"; 82 83 @GuardedBy("mInstallLock") 84 private final Installer mInstaller; 85 private final Object mInstallLock; 86 87 @GuardedBy("mInstallLock") 88 private final PowerManager.WakeLock mDexoptWakeLock; 89 private volatile boolean mSystemReady; 90 91 PackageDexOptimizer(Installer installer, Object installLock, Context context, 92 String wakeLockTag) { 93 this.mInstaller = installer; 94 this.mInstallLock = installLock; 95 96 PowerManager powerManager = (PowerManager)context.getSystemService(Context.POWER_SERVICE); 97 mDexoptWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, wakeLockTag); 98 } 99 100 protected PackageDexOptimizer(PackageDexOptimizer from) { 101 this.mInstaller = from.mInstaller; 102 this.mInstallLock = from.mInstallLock; 103 this.mDexoptWakeLock = from.mDexoptWakeLock; 104 this.mSystemReady = from.mSystemReady; 105 } 106 107 static boolean canOptimizePackage(PackageParser.Package pkg) { 108 // We do not dexopt a package with no code. 109 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) == 0) { 110 return false; 111 } 112 113 // We do not dexopt a priv-app package when pm.dexopt.priv-apps-oob is true. 114 if (pkg.isPrivileged()) { 115 return !SystemProperties.getBoolean("pm.dexopt.priv-apps-oob", false); 116 } 117 118 return true; 119 } 120 121 /** 122 * Performs dexopt on all code paths and libraries of the specified package for specified 123 * instruction sets. 124 * 125 * <p>Calls to {@link com.android.server.pm.Installer#dexopt} on {@link #mInstaller} are 126 * synchronized on {@link #mInstallLock}. 127 */ 128 int performDexOpt(PackageParser.Package pkg, String[] sharedLibraries, 129 String[] instructionSets, CompilerStats.PackageStats packageStats, 130 PackageDexUsage.PackageUseInfo packageUseInfo, DexoptOptions options) { 131 if (pkg.applicationInfo.uid == -1) { 132 throw new IllegalArgumentException("Dexopt for " + pkg.packageName 133 + " has invalid uid."); 134 } 135 if (!canOptimizePackage(pkg)) { 136 return DEX_OPT_SKIPPED; 137 } 138 synchronized (mInstallLock) { 139 final long acquireTime = acquireWakeLockLI(pkg.applicationInfo.uid); 140 try { 141 return performDexOptLI(pkg, sharedLibraries, instructionSets, 142 packageStats, packageUseInfo, options); 143 } finally { 144 releaseWakeLockLI(acquireTime); 145 } 146 } 147 } 148 149 /** 150 * Performs dexopt on all code paths of the given package. 151 * It assumes the install lock is held. 152 */ 153 @GuardedBy("mInstallLock") 154 private int performDexOptLI(PackageParser.Package pkg, String[] sharedLibraries, 155 String[] targetInstructionSets, CompilerStats.PackageStats packageStats, 156 PackageDexUsage.PackageUseInfo packageUseInfo, DexoptOptions options) { 157 final String[] instructionSets = targetInstructionSets != null ? 158 targetInstructionSets : getAppDexInstructionSets(pkg.applicationInfo); 159 final String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 160 final List<String> paths = pkg.getAllCodePaths(); 161 162 int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 163 if (sharedGid == -1) { 164 Slog.wtf(TAG, "Well this is awkward; package " + pkg.applicationInfo.name + " had UID " 165 + pkg.applicationInfo.uid, new Throwable()); 166 sharedGid = android.os.Process.NOBODY_UID; 167 } 168 169 // Get the class loader context dependencies. 170 // For each code path in the package, this array contains the class loader context that 171 // needs to be passed to dexopt in order to ensure correct optimizations. 172 boolean[] pathsWithCode = new boolean[paths.size()]; 173 pathsWithCode[0] = (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0; 174 for (int i = 1; i < paths.size(); i++) { 175 pathsWithCode[i] = (pkg.splitFlags[i - 1] & ApplicationInfo.FLAG_HAS_CODE) != 0; 176 } 177 String[] classLoaderContexts = DexoptUtils.getClassLoaderContexts( 178 pkg.applicationInfo, sharedLibraries, pathsWithCode); 179 180 // Sanity check that we do not call dexopt with inconsistent data. 181 if (paths.size() != classLoaderContexts.length) { 182 String[] splitCodePaths = pkg.applicationInfo.getSplitCodePaths(); 183 throw new IllegalStateException("Inconsistent information " 184 + "between PackageParser.Package and its ApplicationInfo. " 185 + "pkg.getAllCodePaths=" + paths 186 + " pkg.applicationInfo.getBaseCodePath=" + pkg.applicationInfo.getBaseCodePath() 187 + " pkg.applicationInfo.getSplitCodePaths=" 188 + (splitCodePaths == null ? "null" : Arrays.toString(splitCodePaths))); 189 } 190 191 int result = DEX_OPT_SKIPPED; 192 for (int i = 0; i < paths.size(); i++) { 193 // Skip paths that have no code. 194 if (!pathsWithCode[i]) { 195 continue; 196 } 197 if (classLoaderContexts[i] == null) { 198 throw new IllegalStateException("Inconsistent information in the " 199 + "package structure. A split is marked to contain code " 200 + "but has no dependency listed. Index=" + i + " path=" + paths.get(i)); 201 } 202 203 // Append shared libraries with split dependencies for this split. 204 String path = paths.get(i); 205 if (options.getSplitName() != null) { 206 // We are asked to compile only a specific split. Check that the current path is 207 // what we are looking for. 208 if (!options.getSplitName().equals(new File(path).getName())) { 209 continue; 210 } 211 } 212 213 final boolean isUsedByOtherApps = options.isDexoptAsSharedLibrary() 214 || packageUseInfo.isUsedByOtherApps(path); 215 final String compilerFilter = getRealCompilerFilter(pkg.applicationInfo, 216 options.getCompilerFilter(), isUsedByOtherApps); 217 final boolean profileUpdated = options.isCheckForProfileUpdates() && 218 isProfileUpdated(pkg, sharedGid, compilerFilter); 219 220 // Get the dexopt flags after getRealCompilerFilter to make sure we get the correct 221 // flags. 222 final int dexoptFlags = getDexFlags(pkg, compilerFilter, options); 223 224 for (String dexCodeIsa : dexCodeInstructionSets) { 225 int newResult = dexOptPath(pkg, path, dexCodeIsa, compilerFilter, 226 profileUpdated, classLoaderContexts[i], dexoptFlags, sharedGid, 227 packageStats, options.isDowngrade()); 228 // The end result is: 229 // - FAILED if any path failed, 230 // - PERFORMED if at least one path needed compilation, 231 // - SKIPPED when all paths are up to date 232 if ((result != DEX_OPT_FAILED) && (newResult != DEX_OPT_SKIPPED)) { 233 result = newResult; 234 } 235 } 236 } 237 return result; 238 } 239 240 /** 241 * Performs dexopt on the {@code path} belonging to the package {@code pkg}. 242 * 243 * @return 244 * DEX_OPT_FAILED if there was any exception during dexopt 245 * DEX_OPT_PERFORMED if dexopt was performed successfully on the given path. 246 * DEX_OPT_SKIPPED if the path does not need to be deopt-ed. 247 */ 248 @GuardedBy("mInstallLock") 249 private int dexOptPath(PackageParser.Package pkg, String path, String isa, 250 String compilerFilter, boolean profileUpdated, String classLoaderContext, 251 int dexoptFlags, int uid, CompilerStats.PackageStats packageStats, boolean downgrade) { 252 int dexoptNeeded = getDexoptNeeded(path, isa, compilerFilter, classLoaderContext, 253 profileUpdated, downgrade); 254 if (Math.abs(dexoptNeeded) == DexFile.NO_DEXOPT_NEEDED) { 255 return DEX_OPT_SKIPPED; 256 } 257 258 // TODO(calin): there's no need to try to create the oat dir over and over again, 259 // especially since it involve an extra installd call. We should create 260 // if (if supported) on the fly during the dexopt call. 261 String oatDir = createOatDirIfSupported(pkg, isa); 262 263 Log.i(TAG, "Running dexopt (dexoptNeeded=" + dexoptNeeded + ") on: " + path 264 + " pkg=" + pkg.applicationInfo.packageName + " isa=" + isa 265 + " dexoptFlags=" + printDexoptFlags(dexoptFlags) 266 + " targetFilter=" + compilerFilter + " oatDir=" + oatDir 267 + " classLoaderContext=" + classLoaderContext); 268 269 try { 270 long startTime = System.currentTimeMillis(); 271 272 // TODO: Consider adding 2 different APIs for primary and secondary dexopt. 273 // installd only uses downgrade flag for secondary dex files and ignores it for 274 // primary dex files. 275 mInstaller.dexopt(path, uid, pkg.packageName, isa, dexoptNeeded, oatDir, dexoptFlags, 276 compilerFilter, pkg.volumeUuid, classLoaderContext, pkg.applicationInfo.seInfo, 277 false /* downgrade*/); 278 279 if (packageStats != null) { 280 long endTime = System.currentTimeMillis(); 281 packageStats.setCompileTime(path, (int)(endTime - startTime)); 282 } 283 return DEX_OPT_PERFORMED; 284 } catch (InstallerException e) { 285 Slog.w(TAG, "Failed to dexopt", e); 286 return DEX_OPT_FAILED; 287 } 288 } 289 290 /** 291 * Performs dexopt on the secondary dex {@code path} belonging to the app {@code info}. 292 * 293 * @return 294 * DEX_OPT_FAILED if there was any exception during dexopt 295 * DEX_OPT_PERFORMED if dexopt was performed successfully on the given path. 296 * NOTE that DEX_OPT_PERFORMED for secondary dex files includes the case when the dex file 297 * didn't need an update. That's because at the moment we don't get more than success/failure 298 * from installd. 299 * 300 * TODO(calin): Consider adding return codes to installd dexopt invocation (rather than 301 * throwing exceptions). Or maybe make a separate call to installd to get DexOptNeeded, though 302 * that seems wasteful. 303 */ 304 public int dexOptSecondaryDexPath(ApplicationInfo info, String path, 305 PackageDexUsage.DexUseInfo dexUseInfo, DexoptOptions options) { 306 if (info.uid == -1) { 307 throw new IllegalArgumentException("Dexopt for path " + path + " has invalid uid."); 308 } 309 synchronized (mInstallLock) { 310 final long acquireTime = acquireWakeLockLI(info.uid); 311 try { 312 return dexOptSecondaryDexPathLI(info, path, dexUseInfo, options); 313 } finally { 314 releaseWakeLockLI(acquireTime); 315 } 316 } 317 } 318 319 @GuardedBy("mInstallLock") 320 private long acquireWakeLockLI(final int uid) { 321 // During boot the system doesn't need to instantiate and obtain a wake lock. 322 // PowerManager might not be ready, but that doesn't mean that we can't proceed with 323 // dexopt. 324 if (!mSystemReady) { 325 return -1; 326 } 327 mDexoptWakeLock.setWorkSource(new WorkSource(uid)); 328 mDexoptWakeLock.acquire(WAKELOCK_TIMEOUT_MS); 329 return SystemClock.elapsedRealtime(); 330 } 331 332 @GuardedBy("mInstallLock") 333 private void releaseWakeLockLI(final long acquireTime) { 334 if (acquireTime < 0) { 335 return; 336 } 337 try { 338 if (mDexoptWakeLock.isHeld()) { 339 mDexoptWakeLock.release(); 340 } 341 final long duration = SystemClock.elapsedRealtime() - acquireTime; 342 if (duration >= WAKELOCK_TIMEOUT_MS) { 343 Slog.wtf(TAG, "WakeLock " + mDexoptWakeLock.getTag() 344 + " time out. Operation took " + duration + " ms. Thread: " 345 + Thread.currentThread().getName()); 346 } 347 } catch (Exception e) { 348 Slog.wtf(TAG, "Error while releasing " + mDexoptWakeLock.getTag() + " lock", e); 349 } 350 } 351 352 @GuardedBy("mInstallLock") 353 private int dexOptSecondaryDexPathLI(ApplicationInfo info, String path, 354 PackageDexUsage.DexUseInfo dexUseInfo, DexoptOptions options) { 355 if (options.isDexoptOnlySharedDex() && !dexUseInfo.isUsedByOtherApps()) { 356 // We are asked to optimize only the dex files used by other apps and this is not 357 // on of them: skip it. 358 return DEX_OPT_SKIPPED; 359 } 360 361 String compilerFilter = getRealCompilerFilter(info, options.getCompilerFilter(), 362 dexUseInfo.isUsedByOtherApps()); 363 // Get the dexopt flags after getRealCompilerFilter to make sure we get the correct flags. 364 // Secondary dex files are currently not compiled at boot. 365 int dexoptFlags = getDexFlags(info, compilerFilter, options) | DEXOPT_SECONDARY_DEX; 366 // Check the app storage and add the appropriate flags. 367 if (info.deviceProtectedDataDir != null && 368 FileUtils.contains(info.deviceProtectedDataDir, path)) { 369 dexoptFlags |= DEXOPT_STORAGE_DE; 370 } else if (info.credentialProtectedDataDir != null && 371 FileUtils.contains(info.credentialProtectedDataDir, path)) { 372 dexoptFlags |= DEXOPT_STORAGE_CE; 373 } else { 374 Slog.e(TAG, "Could not infer CE/DE storage for package " + info.packageName); 375 return DEX_OPT_FAILED; 376 } 377 Log.d(TAG, "Running dexopt on: " + path 378 + " pkg=" + info.packageName + " isa=" + dexUseInfo.getLoaderIsas() 379 + " dexoptFlags=" + printDexoptFlags(dexoptFlags) 380 + " target-filter=" + compilerFilter); 381 382 // TODO(calin): b/64530081 b/66984396. Use SKIP_SHARED_LIBRARY_CHECK for the context 383 // (instead of dexUseInfo.getClassLoaderContext()) in order to compile secondary dex files 384 // in isolation (and avoid to extract/verify the main apk if it's in the class path). 385 // Note this trades correctness for performance since the resulting slow down is 386 // unacceptable in some cases until b/64530081 is fixed. 387 String classLoaderContext = SKIP_SHARED_LIBRARY_CHECK; 388 389 try { 390 for (String isa : dexUseInfo.getLoaderIsas()) { 391 // Reuse the same dexopt path as for the primary apks. We don't need all the 392 // arguments as some (dexopNeeded and oatDir) will be computed by installd because 393 // system server cannot read untrusted app content. 394 // TODO(calin): maybe add a separate call. 395 mInstaller.dexopt(path, info.uid, info.packageName, isa, /*dexoptNeeded*/ 0, 396 /*oatDir*/ null, dexoptFlags, 397 compilerFilter, info.volumeUuid, classLoaderContext, info.seInfoUser, 398 options.isDowngrade()); 399 } 400 401 return DEX_OPT_PERFORMED; 402 } catch (InstallerException e) { 403 Slog.w(TAG, "Failed to dexopt", e); 404 return DEX_OPT_FAILED; 405 } 406 } 407 408 /** 409 * Adjust the given dexopt-needed value. Can be overridden to influence the decision to 410 * optimize or not (and in what way). 411 */ 412 protected int adjustDexoptNeeded(int dexoptNeeded) { 413 return dexoptNeeded; 414 } 415 416 /** 417 * Adjust the given dexopt flags that will be passed to the installer. 418 */ 419 protected int adjustDexoptFlags(int dexoptFlags) { 420 return dexoptFlags; 421 } 422 423 /** 424 * Dumps the dexopt state of the given package {@code pkg} to the given {@code PrintWriter}. 425 */ 426 void dumpDexoptState(IndentingPrintWriter pw, PackageParser.Package pkg, 427 PackageDexUsage.PackageUseInfo useInfo) { 428 final String[] instructionSets = getAppDexInstructionSets(pkg.applicationInfo); 429 final String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 430 431 final List<String> paths = pkg.getAllCodePathsExcludingResourceOnly(); 432 433 for (String path : paths) { 434 pw.println("path: " + path); 435 pw.increaseIndent(); 436 437 for (String isa : dexCodeInstructionSets) { 438 String status = null; 439 try { 440 status = DexFile.getDexFileStatus(path, isa); 441 } catch (IOException ioe) { 442 status = "[Exception]: " + ioe.getMessage(); 443 } 444 pw.println(isa + ": " + status); 445 } 446 447 if (useInfo.isUsedByOtherApps(path)) { 448 pw.println("used by other apps: " + useInfo.getLoadingPackages(path)); 449 } 450 451 Map<String, PackageDexUsage.DexUseInfo> dexUseInfoMap = useInfo.getDexUseInfoMap(); 452 453 if (!dexUseInfoMap.isEmpty()) { 454 pw.println("known secondary dex files:"); 455 pw.increaseIndent(); 456 for (Map.Entry<String, PackageDexUsage.DexUseInfo> e : dexUseInfoMap.entrySet()) { 457 String dex = e.getKey(); 458 PackageDexUsage.DexUseInfo dexUseInfo = e.getValue(); 459 pw.println(dex); 460 pw.increaseIndent(); 461 // TODO(calin): get the status of the oat file (needs installd call) 462 pw.println("class loader context: " + dexUseInfo.getClassLoaderContext()); 463 if (dexUseInfo.isUsedByOtherApps()) { 464 pw.println("used by other apps: " + dexUseInfo.getLoadingPackages()); 465 } 466 pw.decreaseIndent(); 467 } 468 pw.decreaseIndent(); 469 } 470 pw.decreaseIndent(); 471 } 472 } 473 474 /** 475 * Returns the compiler filter that should be used to optimize the package code. 476 * The target filter will be updated if the package code is used by other apps 477 * or if it has the safe mode flag set. 478 */ 479 private String getRealCompilerFilter(ApplicationInfo info, String targetCompilerFilter, 480 boolean isUsedByOtherApps) { 481 int flags = info.flags; 482 boolean vmSafeMode = (flags & ApplicationInfo.FLAG_VM_SAFE_MODE) != 0; 483 if (vmSafeMode) { 484 return getSafeModeCompilerFilter(targetCompilerFilter); 485 } 486 487 if (isProfileGuidedCompilerFilter(targetCompilerFilter) && isUsedByOtherApps) { 488 // If the dex files is used by other apps, apply the shared filter. 489 return PackageManagerServiceCompilerMapping.getCompilerFilterForReason( 490 PackageManagerService.REASON_SHARED); 491 } 492 493 return targetCompilerFilter; 494 } 495 496 /** 497 * Computes the dex flags that needs to be pass to installd for the given package and compiler 498 * filter. 499 */ 500 private int getDexFlags(PackageParser.Package pkg, String compilerFilter, 501 DexoptOptions options) { 502 return getDexFlags(pkg.applicationInfo, compilerFilter, options); 503 } 504 505 private int getDexFlags(ApplicationInfo info, String compilerFilter, DexoptOptions options) { 506 int flags = info.flags; 507 boolean debuggable = (flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0; 508 // Profile guide compiled oat files should not be public. 509 boolean isProfileGuidedFilter = isProfileGuidedCompilerFilter(compilerFilter); 510 boolean isPublic = !info.isForwardLocked() && !isProfileGuidedFilter; 511 int profileFlag = isProfileGuidedFilter ? DEXOPT_PROFILE_GUIDED : 0; 512 int dexFlags = 513 (isPublic ? DEXOPT_PUBLIC : 0) 514 | (debuggable ? DEXOPT_DEBUGGABLE : 0) 515 | profileFlag 516 | (options.isBootComplete() ? DEXOPT_BOOTCOMPLETE : 0) 517 | (options.isDexoptIdleBackgroundJob() ? DEXOPT_IDLE_BACKGROUND_JOB : 0); 518 return adjustDexoptFlags(dexFlags); 519 } 520 521 /** 522 * Assesses if there's a need to perform dexopt on {@code path} for the given 523 * configuration (isa, compiler filter, profile). 524 */ 525 private int getDexoptNeeded(String path, String isa, String compilerFilter, 526 String classLoaderContext, boolean newProfile, boolean downgrade) { 527 int dexoptNeeded; 528 try { 529 dexoptNeeded = DexFile.getDexOptNeeded(path, isa, compilerFilter, classLoaderContext, 530 newProfile, downgrade); 531 } catch (IOException ioe) { 532 Slog.w(TAG, "IOException reading apk: " + path, ioe); 533 return DEX_OPT_FAILED; 534 } 535 return adjustDexoptNeeded(dexoptNeeded); 536 } 537 538 /** 539 * Checks if there is an update on the profile information of the {@code pkg}. 540 * If the compiler filter is not profile guided the method returns false. 541 * 542 * Note that this is a "destructive" operation with side effects. Under the hood the 543 * current profile and the reference profile will be merged and subsequent calls 544 * may return a different result. 545 */ 546 private boolean isProfileUpdated(PackageParser.Package pkg, int uid, String compilerFilter) { 547 // Check if we are allowed to merge and if the compiler filter is profile guided. 548 if (!isProfileGuidedCompilerFilter(compilerFilter)) { 549 return false; 550 } 551 // Merge profiles. It returns whether or not there was an updated in the profile info. 552 try { 553 return mInstaller.mergeProfiles(uid, pkg.packageName); 554 } catch (InstallerException e) { 555 Slog.w(TAG, "Failed to merge profiles", e); 556 } 557 return false; 558 } 559 560 /** 561 * Creates oat dir for the specified package if needed and supported. 562 * In certain cases oat directory 563 * <strong>cannot</strong> be created: 564 * <ul> 565 * <li>{@code pkg} is a system app, which is not updated.</li> 566 * <li>Package location is not a directory, i.e. monolithic install.</li> 567 * </ul> 568 * 569 * @return Absolute path to the oat directory or null, if oat directory 570 * cannot be created. 571 */ 572 @Nullable 573 private String createOatDirIfSupported(PackageParser.Package pkg, String dexInstructionSet) { 574 if (!pkg.canHaveOatDir()) { 575 return null; 576 } 577 File codePath = new File(pkg.codePath); 578 if (codePath.isDirectory()) { 579 // TODO(calin): why do we create this only if the codePath is a directory? (i.e for 580 // cluster packages). It seems that the logic for the folder creation is 581 // split between installd and here. 582 File oatDir = getOatDir(codePath); 583 try { 584 mInstaller.createOatDir(oatDir.getAbsolutePath(), dexInstructionSet); 585 } catch (InstallerException e) { 586 Slog.w(TAG, "Failed to create oat dir", e); 587 return null; 588 } 589 return oatDir.getAbsolutePath(); 590 } 591 return null; 592 } 593 594 static File getOatDir(File codePath) { 595 return new File(codePath, OAT_DIR_NAME); 596 } 597 598 void systemReady() { 599 mSystemReady = true; 600 } 601 602 private String printDexoptFlags(int flags) { 603 ArrayList<String> flagsList = new ArrayList<>(); 604 605 if ((flags & DEXOPT_BOOTCOMPLETE) == DEXOPT_BOOTCOMPLETE) { 606 flagsList.add("boot_complete"); 607 } 608 if ((flags & DEXOPT_DEBUGGABLE) == DEXOPT_DEBUGGABLE) { 609 flagsList.add("debuggable"); 610 } 611 if ((flags & DEXOPT_PROFILE_GUIDED) == DEXOPT_PROFILE_GUIDED) { 612 flagsList.add("profile_guided"); 613 } 614 if ((flags & DEXOPT_PUBLIC) == DEXOPT_PUBLIC) { 615 flagsList.add("public"); 616 } 617 if ((flags & DEXOPT_SECONDARY_DEX) == DEXOPT_SECONDARY_DEX) { 618 flagsList.add("secondary"); 619 } 620 if ((flags & DEXOPT_FORCE) == DEXOPT_FORCE) { 621 flagsList.add("force"); 622 } 623 if ((flags & DEXOPT_STORAGE_CE) == DEXOPT_STORAGE_CE) { 624 flagsList.add("storage_ce"); 625 } 626 if ((flags & DEXOPT_STORAGE_DE) == DEXOPT_STORAGE_DE) { 627 flagsList.add("storage_de"); 628 } 629 if ((flags & DEXOPT_IDLE_BACKGROUND_JOB) == DEXOPT_IDLE_BACKGROUND_JOB) { 630 flagsList.add("idle_background_job"); 631 } 632 633 return String.join(",", flagsList); 634 } 635 636 /** 637 * A specialized PackageDexOptimizer that overrides already-installed checks, forcing a 638 * dexopt path. 639 */ 640 public static class ForcedUpdatePackageDexOptimizer extends PackageDexOptimizer { 641 642 public ForcedUpdatePackageDexOptimizer(Installer installer, Object installLock, 643 Context context, String wakeLockTag) { 644 super(installer, installLock, context, wakeLockTag); 645 } 646 647 public ForcedUpdatePackageDexOptimizer(PackageDexOptimizer from) { 648 super(from); 649 } 650 651 @Override 652 protected int adjustDexoptNeeded(int dexoptNeeded) { 653 if (dexoptNeeded == DexFile.NO_DEXOPT_NEEDED) { 654 // Ensure compilation by pretending a compiler filter change on the 655 // apk/odex location (the reason for the '-'. A positive value means 656 // the 'oat' location). 657 return -DexFile.DEX2OAT_FOR_FILTER; 658 } 659 return dexoptNeeded; 660 } 661 662 @Override 663 protected int adjustDexoptFlags(int flags) { 664 // Add DEXOPT_FORCE flag to signal installd that it should force compilation 665 // and discard dexoptanalyzer result. 666 return flags | DEXOPT_FORCE; 667 } 668 } 669} 670