DexManager.java revision c1fe2ce8493b0750aaa210531fda0766b73bad16
1/* 2 * Copyright (C) 2016 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.dex; 18 19import android.content.pm.ApplicationInfo; 20import android.content.pm.IPackageManager; 21import android.content.pm.PackageInfo; 22import android.os.FileUtils; 23import android.os.RemoteException; 24import android.os.storage.StorageManager; 25import android.os.UserHandle; 26 27import android.util.Slog; 28 29import com.android.internal.annotations.GuardedBy; 30import com.android.server.pm.Installer; 31import com.android.server.pm.Installer.InstallerException; 32import com.android.server.pm.PackageDexOptimizer; 33import com.android.server.pm.PackageManagerService; 34import com.android.server.pm.PackageManagerServiceUtils; 35import com.android.server.pm.PackageManagerServiceCompilerMapping; 36 37import java.io.File; 38import java.io.IOException; 39import java.util.List; 40import java.util.HashMap; 41import java.util.HashSet; 42import java.util.Map; 43import java.util.Set; 44 45import static com.android.server.pm.InstructionSets.getAppDexInstructionSets; 46import static com.android.server.pm.dex.PackageDexUsage.PackageUseInfo; 47import static com.android.server.pm.dex.PackageDexUsage.DexUseInfo; 48 49/** 50 * This class keeps track of how dex files are used. 51 * Every time it gets a notification about a dex file being loaded it tracks 52 * its owning package and records it in PackageDexUsage (package-dex-usage.list). 53 * 54 * TODO(calin): Extract related dexopt functionality from PackageManagerService 55 * into this class. 56 */ 57public class DexManager { 58 private static final String TAG = "DexManager"; 59 60 private static final boolean DEBUG = false; 61 62 // Maps package name to code locations. 63 // It caches the code locations for the installed packages. This allows for 64 // faster lookups (no locks) when finding what package owns the dex file. 65 @GuardedBy("mPackageCodeLocationsCache") 66 private final Map<String, PackageCodeLocations> mPackageCodeLocationsCache; 67 68 // PackageDexUsage handles the actual I/O operations. It is responsible to 69 // encode and save the dex usage data. 70 private final PackageDexUsage mPackageDexUsage; 71 72 private final IPackageManager mPackageManager; 73 private final PackageDexOptimizer mPackageDexOptimizer; 74 private final Object mInstallLock; 75 @GuardedBy("mInstallLock") 76 private final Installer mInstaller; 77 78 // Possible outcomes of a dex search. 79 private static int DEX_SEARCH_NOT_FOUND = 0; // dex file not found 80 private static int DEX_SEARCH_FOUND_PRIMARY = 1; // dex file is the primary/base apk 81 private static int DEX_SEARCH_FOUND_SPLIT = 2; // dex file is a split apk 82 private static int DEX_SEARCH_FOUND_SECONDARY = 3; // dex file is a secondary dex 83 84 public DexManager(IPackageManager pms, PackageDexOptimizer pdo, 85 Installer installer, Object installLock) { 86 mPackageCodeLocationsCache = new HashMap<>(); 87 mPackageDexUsage = new PackageDexUsage(); 88 mPackageManager = pms; 89 mPackageDexOptimizer = pdo; 90 mInstaller = installer; 91 mInstallLock = installLock; 92 } 93 94 /** 95 * Notify about dex files loads. 96 * Note that this method is invoked when apps load dex files and it should 97 * return as fast as possible. 98 * 99 * @param loadingAppInfo the package performing the load 100 * @param dexPaths the list of dex files being loaded 101 * @param loaderIsa the ISA of the app loading the dex files 102 * @param loaderUserId the user id which runs the code loading the dex files 103 */ 104 public void notifyDexLoad(ApplicationInfo loadingAppInfo, List<String> dexPaths, 105 String loaderIsa, int loaderUserId) { 106 try { 107 notifyDexLoadInternal(loadingAppInfo, dexPaths, loaderIsa, loaderUserId); 108 } catch (Exception e) { 109 Slog.w(TAG, "Exception while notifying dex load for package " + 110 loadingAppInfo.packageName, e); 111 } 112 } 113 114 private void notifyDexLoadInternal(ApplicationInfo loadingAppInfo, List<String> dexPaths, 115 String loaderIsa, int loaderUserId) { 116 if (!PackageManagerServiceUtils.checkISA(loaderIsa)) { 117 Slog.w(TAG, "Loading dex files " + dexPaths + " in unsupported ISA: " + 118 loaderIsa + "?"); 119 return; 120 } 121 122 for (String dexPath : dexPaths) { 123 // Find the owning package name. 124 DexSearchResult searchResult = getDexPackage(loadingAppInfo, dexPath, loaderUserId); 125 126 if (DEBUG) { 127 Slog.i(TAG, loadingAppInfo.packageName 128 + " loads from " + searchResult + " : " + loaderUserId + " : " + dexPath); 129 } 130 131 if (searchResult.mOutcome != DEX_SEARCH_NOT_FOUND) { 132 // TODO(calin): extend isUsedByOtherApps check to detect the cases where 133 // different apps share the same runtime. In that case we should not mark the dex 134 // file as isUsedByOtherApps. Currently this is a safe approximation. 135 boolean isUsedByOtherApps = !loadingAppInfo.packageName.equals( 136 searchResult.mOwningPackageName); 137 boolean primaryOrSplit = searchResult.mOutcome == DEX_SEARCH_FOUND_PRIMARY || 138 searchResult.mOutcome == DEX_SEARCH_FOUND_SPLIT; 139 140 if (primaryOrSplit && !isUsedByOtherApps) { 141 // If the dex file is the primary apk (or a split) and not isUsedByOtherApps 142 // do not record it. This case does not bring any new usable information 143 // and can be safely skipped. 144 continue; 145 } 146 147 // Record dex file usage. If the current usage is a new pattern (e.g. new secondary, 148 // or UsedBytOtherApps), record will return true and we trigger an async write 149 // to disk to make sure we don't loose the data in case of a reboot. 150 if (mPackageDexUsage.record(searchResult.mOwningPackageName, 151 dexPath, loaderUserId, loaderIsa, isUsedByOtherApps, primaryOrSplit, 152 loadingAppInfo.packageName)) { 153 mPackageDexUsage.maybeWriteAsync(); 154 } 155 } else { 156 // This can happen in a few situations: 157 // - bogus dex loads 158 // - recent installs/uninstalls that we didn't detect. 159 // - new installed splits 160 // If we can't find the owner of the dex we simply do not track it. The impact is 161 // that the dex file will not be considered for offline optimizations. 162 // TODO(calin): add hooks for move/uninstall notifications to 163 // capture package moves or obsolete packages. 164 if (DEBUG) { 165 Slog.i(TAG, "Could not find owning package for dex file: " + dexPath); 166 } 167 } 168 } 169 } 170 171 /** 172 * Read the dex usage from disk and populate the code cache locations. 173 * @param existingPackages a map containing information about what packages 174 * are available to what users. Only packages in this list will be 175 * recognized during notifyDexLoad(). 176 */ 177 public void load(Map<Integer, List<PackageInfo>> existingPackages) { 178 try { 179 loadInternal(existingPackages); 180 } catch (Exception e) { 181 mPackageDexUsage.clear(); 182 Slog.w(TAG, "Exception while loading package dex usage. " + 183 "Starting with a fresh state.", e); 184 } 185 } 186 187 /** 188 * Notifies that a new package was installed for {@code userId}. 189 * {@code userId} must not be {@code UserHandle.USER_ALL}. 190 * 191 * @throws IllegalArgumentException if {@code userId} is {@code UserHandle.USER_ALL}. 192 */ 193 public void notifyPackageInstalled(PackageInfo pi, int userId) { 194 if (userId == UserHandle.USER_ALL) { 195 throw new IllegalArgumentException( 196 "notifyPackageInstalled called with USER_ALL"); 197 } 198 cachePackageInfo(pi, userId); 199 } 200 201 /** 202 * Notifies that package {@code packageName} was updated. 203 * This will clear the UsedByOtherApps mark if it exists. 204 */ 205 public void notifyPackageUpdated(String packageName, String baseCodePath, 206 String[] splitCodePaths) { 207 cachePackageCodeLocation(packageName, baseCodePath, splitCodePaths, null, /*userId*/ -1); 208 // In case there was an update, write the package use info to disk async. 209 // Note that we do the writing here and not in PackageDexUsage in order to be 210 // consistent with other methods in DexManager (e.g. reconcileSecondaryDexFiles performs 211 // multiple updates in PackageDexUsage before writing it). 212 if (mPackageDexUsage.clearUsedByOtherApps(packageName)) { 213 mPackageDexUsage.maybeWriteAsync(); 214 } 215 } 216 217 /** 218 * Notifies that the user {@code userId} data for package {@code packageName} 219 * was destroyed. This will remove all usage info associated with the package 220 * for the given user. 221 * {@code userId} is allowed to be {@code UserHandle.USER_ALL} in which case 222 * all usage information for the package will be removed. 223 */ 224 public void notifyPackageDataDestroyed(String packageName, int userId) { 225 boolean updated = userId == UserHandle.USER_ALL 226 ? mPackageDexUsage.removePackage(packageName) 227 : mPackageDexUsage.removeUserPackage(packageName, userId); 228 // In case there was an update, write the package use info to disk async. 229 // Note that we do the writing here and not in PackageDexUsage in order to be 230 // consistent with other methods in DexManager (e.g. reconcileSecondaryDexFiles performs 231 // multiple updates in PackageDexUsage before writing it). 232 if (updated) { 233 mPackageDexUsage.maybeWriteAsync(); 234 } 235 } 236 237 /** 238 * Caches the code location from the given package info. 239 */ 240 private void cachePackageInfo(PackageInfo pi, int userId) { 241 ApplicationInfo ai = pi.applicationInfo; 242 String[] dataDirs = new String[] {ai.dataDir, ai.deviceProtectedDataDir, 243 ai.credentialProtectedDataDir}; 244 cachePackageCodeLocation(pi.packageName, ai.sourceDir, ai.splitSourceDirs, 245 dataDirs, userId); 246 } 247 248 private void cachePackageCodeLocation(String packageName, String baseCodePath, 249 String[] splitCodePaths, String[] dataDirs, int userId) { 250 synchronized (mPackageCodeLocationsCache) { 251 PackageCodeLocations pcl = putIfAbsent(mPackageCodeLocationsCache, packageName, 252 new PackageCodeLocations(packageName, baseCodePath, splitCodePaths)); 253 // TODO(calin): We are forced to extend the scope of this synchronization because 254 // the values of the cache (PackageCodeLocations) are updated in place. 255 // Make PackageCodeLocations immutable to simplify the synchronization reasoning. 256 pcl.updateCodeLocation(baseCodePath, splitCodePaths); 257 if (dataDirs != null) { 258 for (String dataDir : dataDirs) { 259 // The set of data dirs includes deviceProtectedDataDir and 260 // credentialProtectedDataDir which might be null for shared 261 // libraries. Currently we don't track these but be lenient 262 // and check in case we ever decide to store their usage data. 263 if (dataDir != null) { 264 pcl.mergeAppDataDirs(dataDir, userId); 265 } 266 } 267 } 268 } 269 } 270 271 private void loadInternal(Map<Integer, List<PackageInfo>> existingPackages) { 272 Map<String, Set<Integer>> packageToUsersMap = new HashMap<>(); 273 // Cache the code locations for the installed packages. This allows for 274 // faster lookups (no locks) when finding what package owns the dex file. 275 for (Map.Entry<Integer, List<PackageInfo>> entry : existingPackages.entrySet()) { 276 List<PackageInfo> packageInfoList = entry.getValue(); 277 int userId = entry.getKey(); 278 for (PackageInfo pi : packageInfoList) { 279 // Cache the code locations. 280 cachePackageInfo(pi, userId); 281 282 // Cache a map from package name to the set of user ids who installed the package. 283 // We will use it to sync the data and remove obsolete entries from 284 // mPackageDexUsage. 285 Set<Integer> users = putIfAbsent( 286 packageToUsersMap, pi.packageName, new HashSet<>()); 287 users.add(userId); 288 } 289 } 290 291 mPackageDexUsage.read(); 292 mPackageDexUsage.syncData(packageToUsersMap); 293 } 294 295 /** 296 * Get the package dex usage for the given package name. 297 * @return the package data or null if there is no data available for this package. 298 */ 299 public PackageUseInfo getPackageUseInfo(String packageName) { 300 return mPackageDexUsage.getPackageUseInfo(packageName); 301 } 302 303 /** 304 * Perform dexopt on with the given {@code options} on the secondary dex files. 305 * @return true if all secondary dex files were processed successfully (compiled or skipped 306 * because they don't need to be compiled).. 307 */ 308 public boolean dexoptSecondaryDex(DexoptOptions options) { 309 // Select the dex optimizer based on the force parameter. 310 // Forced compilation is done through ForcedUpdatePackageDexOptimizer which will adjust 311 // the necessary dexopt flags to make sure that compilation is not skipped. This avoid 312 // passing the force flag through the multitude of layers. 313 // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to 314 // allocate an object here. 315 PackageDexOptimizer pdo = options.isForce() 316 ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer) 317 : mPackageDexOptimizer; 318 String packageName = options.getPackageName(); 319 PackageUseInfo useInfo = getPackageUseInfo(packageName); 320 if (useInfo == null || useInfo.getDexUseInfoMap().isEmpty()) { 321 if (DEBUG) { 322 Slog.d(TAG, "No secondary dex use for package:" + packageName); 323 } 324 // Nothing to compile, return true. 325 return true; 326 } 327 boolean success = true; 328 for (Map.Entry<String, DexUseInfo> entry : useInfo.getDexUseInfoMap().entrySet()) { 329 String dexPath = entry.getKey(); 330 DexUseInfo dexUseInfo = entry.getValue(); 331 if (options.isDexoptOnlySharedDex() && !dexUseInfo.isUsedByOtherApps()) { 332 continue; 333 } 334 PackageInfo pkg = null; 335 try { 336 pkg = mPackageManager.getPackageInfo(packageName, /*flags*/0, 337 dexUseInfo.getOwnerUserId()); 338 } catch (RemoteException e) { 339 throw new AssertionError(e); 340 } 341 // It may be that the package gets uninstalled while we try to compile its 342 // secondary dex files. If that's the case, just ignore. 343 // Note that we don't break the entire loop because the package might still be 344 // installed for other users. 345 if (pkg == null) { 346 Slog.d(TAG, "Could not find package when compiling secondary dex " + packageName 347 + " for user " + dexUseInfo.getOwnerUserId()); 348 mPackageDexUsage.removeUserPackage(packageName, dexUseInfo.getOwnerUserId()); 349 continue; 350 } 351 352 int result = pdo.dexOptSecondaryDexPath(pkg.applicationInfo, dexPath, 353 dexUseInfo.getLoaderIsas(), options.getCompilerFilter(), 354 dexUseInfo.isUsedByOtherApps(), options.isDowngrade()); 355 success = success && (result != PackageDexOptimizer.DEX_OPT_FAILED); 356 } 357 return success; 358 } 359 360 /** 361 * Reconcile the information we have about the secondary dex files belonging to 362 * {@code packagName} and the actual dex files. For all dex files that were 363 * deleted, update the internal records and delete any generated oat files. 364 */ 365 public void reconcileSecondaryDexFiles(String packageName) { 366 PackageUseInfo useInfo = getPackageUseInfo(packageName); 367 if (useInfo == null || useInfo.getDexUseInfoMap().isEmpty()) { 368 if (DEBUG) { 369 Slog.d(TAG, "No secondary dex use for package:" + packageName); 370 } 371 // Nothing to reconcile. 372 return; 373 } 374 375 boolean updated = false; 376 for (Map.Entry<String, DexUseInfo> entry : useInfo.getDexUseInfoMap().entrySet()) { 377 String dexPath = entry.getKey(); 378 DexUseInfo dexUseInfo = entry.getValue(); 379 PackageInfo pkg = null; 380 try { 381 // Note that we look for the package in the PackageManager just to be able 382 // to get back the real app uid and its storage kind. These are only used 383 // to perform extra validation in installd. 384 // TODO(calin): maybe a bit overkill. 385 pkg = mPackageManager.getPackageInfo(packageName, /*flags*/0, 386 dexUseInfo.getOwnerUserId()); 387 } catch (RemoteException ignore) { 388 // Can't happen, DexManager is local. 389 } 390 if (pkg == null) { 391 // It may be that the package was uninstalled while we process the secondary 392 // dex files. 393 Slog.d(TAG, "Could not find package when compiling secondary dex " + packageName 394 + " for user " + dexUseInfo.getOwnerUserId()); 395 // Update the usage and continue, another user might still have the package. 396 updated = mPackageDexUsage.removeUserPackage( 397 packageName, dexUseInfo.getOwnerUserId()) || updated; 398 continue; 399 } 400 ApplicationInfo info = pkg.applicationInfo; 401 int flags = 0; 402 if (info.deviceProtectedDataDir != null && 403 FileUtils.contains(info.deviceProtectedDataDir, dexPath)) { 404 flags |= StorageManager.FLAG_STORAGE_DE; 405 } else if (info.credentialProtectedDataDir!= null && 406 FileUtils.contains(info.credentialProtectedDataDir, dexPath)) { 407 flags |= StorageManager.FLAG_STORAGE_CE; 408 } else { 409 Slog.e(TAG, "Could not infer CE/DE storage for path " + dexPath); 410 updated = mPackageDexUsage.removeDexFile( 411 packageName, dexPath, dexUseInfo.getOwnerUserId()) || updated; 412 continue; 413 } 414 415 boolean dexStillExists = true; 416 synchronized(mInstallLock) { 417 try { 418 String[] isas = dexUseInfo.getLoaderIsas().toArray(new String[0]); 419 dexStillExists = mInstaller.reconcileSecondaryDexFile(dexPath, packageName, 420 pkg.applicationInfo.uid, isas, pkg.applicationInfo.volumeUuid, flags); 421 } catch (InstallerException e) { 422 Slog.e(TAG, "Got InstallerException when reconciling dex " + dexPath + 423 " : " + e.getMessage()); 424 } 425 } 426 if (!dexStillExists) { 427 updated = mPackageDexUsage.removeDexFile( 428 packageName, dexPath, dexUseInfo.getOwnerUserId()) || updated; 429 } 430 431 } 432 if (updated) { 433 mPackageDexUsage.maybeWriteAsync(); 434 } 435 } 436 437 public RegisterDexModuleResult registerDexModule(ApplicationInfo info, String dexPath, 438 boolean isUsedByOtherApps, int userId) { 439 // Find the owning package record. 440 DexSearchResult searchResult = getDexPackage(info, dexPath, userId); 441 442 if (searchResult.mOutcome == DEX_SEARCH_NOT_FOUND) { 443 return new RegisterDexModuleResult(false, "Package not found"); 444 } 445 if (!info.packageName.equals(searchResult.mOwningPackageName)) { 446 return new RegisterDexModuleResult(false, "Dex path does not belong to package"); 447 } 448 if (searchResult.mOutcome == DEX_SEARCH_FOUND_PRIMARY || 449 searchResult.mOutcome == DEX_SEARCH_FOUND_SPLIT) { 450 return new RegisterDexModuleResult(false, "Main apks cannot be registered"); 451 } 452 453 // We found the package. Now record the usage for all declared ISAs. 454 boolean update = false; 455 Set<String> isas = new HashSet<>(); 456 for (String isa : getAppDexInstructionSets(info)) { 457 isas.add(isa); 458 boolean newUpdate = mPackageDexUsage.record(searchResult.mOwningPackageName, 459 dexPath, userId, isa, isUsedByOtherApps, /*primaryOrSplit*/ false, 460 searchResult.mOwningPackageName); 461 update |= newUpdate; 462 } 463 if (update) { 464 mPackageDexUsage.maybeWriteAsync(); 465 } 466 467 // Try to optimize the package according to the install reason. 468 String compilerFilter = PackageManagerServiceCompilerMapping.getCompilerFilterForReason( 469 PackageManagerService.REASON_INSTALL); 470 int result = mPackageDexOptimizer.dexOptSecondaryDexPath(info, dexPath, isas, 471 compilerFilter, isUsedByOtherApps, /* downgrade */ false); 472 473 // If we fail to optimize the package log an error but don't propagate the error 474 // back to the app. The app cannot do much about it and the background job 475 // will rety again when it executes. 476 // TODO(calin): there might be some value to return the error here but it may 477 // cause red herrings since that doesn't mean the app cannot use the module. 478 if (result != PackageDexOptimizer.DEX_OPT_FAILED) { 479 Slog.e(TAG, "Failed to optimize dex module " + dexPath); 480 } 481 return new RegisterDexModuleResult(true, "Dex module registered successfully"); 482 } 483 484 /** 485 * Return all packages that contain records of secondary dex files. 486 */ 487 public Set<String> getAllPackagesWithSecondaryDexFiles() { 488 return mPackageDexUsage.getAllPackagesWithSecondaryDexFiles(); 489 } 490 491 /** 492 * Return true if the profiling data collected for the given app indicate 493 * that the apps's APK has been loaded by another app. 494 * Note that this returns false for all apps without any collected profiling data. 495 */ 496 public boolean isUsedByOtherApps(String packageName) { 497 PackageUseInfo useInfo = getPackageUseInfo(packageName); 498 if (useInfo == null) { 499 // No use info, means the package was not used or it was used but not by other apps. 500 // Note that right now we might prune packages which are not used by other apps. 501 // TODO(calin): maybe we should not (prune) so we can have an accurate view when we try 502 // to access the package use. 503 return false; 504 } 505 return useInfo.isUsedByOtherApps(); 506 } 507 508 /** 509 * Retrieves the package which owns the given dexPath. 510 */ 511 private DexSearchResult getDexPackage( 512 ApplicationInfo loadingAppInfo, String dexPath, int userId) { 513 // Ignore framework code. 514 // TODO(calin): is there a better way to detect it? 515 if (dexPath.startsWith("/system/framework/")) { 516 return new DexSearchResult("framework", DEX_SEARCH_NOT_FOUND); 517 } 518 519 // First, check if the package which loads the dex file actually owns it. 520 // Most of the time this will be true and we can return early. 521 PackageCodeLocations loadingPackageCodeLocations = 522 new PackageCodeLocations(loadingAppInfo, userId); 523 int outcome = loadingPackageCodeLocations.searchDex(dexPath, userId); 524 if (outcome != DEX_SEARCH_NOT_FOUND) { 525 // TODO(calin): evaluate if we bother to detect symlinks at the dexPath level. 526 return new DexSearchResult(loadingPackageCodeLocations.mPackageName, outcome); 527 } 528 529 // The loadingPackage does not own the dex file. 530 // Perform a reverse look-up in the cache to detect if any package has ownership. 531 // Note that we can have false negatives if the cache falls out of date. 532 synchronized (mPackageCodeLocationsCache) { 533 for (PackageCodeLocations pcl : mPackageCodeLocationsCache.values()) { 534 outcome = pcl.searchDex(dexPath, userId); 535 if (outcome != DEX_SEARCH_NOT_FOUND) { 536 return new DexSearchResult(pcl.mPackageName, outcome); 537 } 538 } 539 } 540 541 if (DEBUG) { 542 // TODO(calin): Consider checking for /data/data symlink. 543 // /data/data/ symlinks /data/user/0/ and there's nothing stopping apps 544 // to load dex files through it. 545 try { 546 String dexPathReal = PackageManagerServiceUtils.realpath(new File(dexPath)); 547 if (dexPathReal != dexPath) { 548 Slog.d(TAG, "Dex loaded with symlink. dexPath=" + 549 dexPath + " dexPathReal=" + dexPathReal); 550 } 551 } catch (IOException e) { 552 // Ignore 553 } 554 } 555 // Cache miss. The cache is updated during installs and uninstalls, 556 // so if we get here we're pretty sure the dex path does not exist. 557 return new DexSearchResult(null, DEX_SEARCH_NOT_FOUND); 558 } 559 560 private static <K,V> V putIfAbsent(Map<K,V> map, K key, V newValue) { 561 V existingValue = map.putIfAbsent(key, newValue); 562 return existingValue == null ? newValue : existingValue; 563 } 564 565 /** 566 * Saves the in-memory package dex usage to disk right away. 567 */ 568 public void savePackageDexUsageNow() { 569 mPackageDexUsage.writeNow(); 570 } 571 572 public static class RegisterDexModuleResult { 573 public RegisterDexModuleResult() { 574 this(false, null); 575 } 576 577 public RegisterDexModuleResult(boolean success, String message) { 578 this.success = success; 579 this.message = message; 580 } 581 582 public final boolean success; 583 public final String message; 584 } 585 586 /** 587 * Convenience class to store the different locations where a package might 588 * own code. 589 */ 590 private static class PackageCodeLocations { 591 private final String mPackageName; 592 private String mBaseCodePath; 593 private final Set<String> mSplitCodePaths; 594 // Maps user id to the application private directory. 595 private final Map<Integer, Set<String>> mAppDataDirs; 596 597 public PackageCodeLocations(ApplicationInfo ai, int userId) { 598 this(ai.packageName, ai.sourceDir, ai.splitSourceDirs); 599 mergeAppDataDirs(ai.dataDir, userId); 600 } 601 public PackageCodeLocations(String packageName, String baseCodePath, 602 String[] splitCodePaths) { 603 mPackageName = packageName; 604 mSplitCodePaths = new HashSet<>(); 605 mAppDataDirs = new HashMap<>(); 606 updateCodeLocation(baseCodePath, splitCodePaths); 607 } 608 609 public void updateCodeLocation(String baseCodePath, String[] splitCodePaths) { 610 mBaseCodePath = baseCodePath; 611 mSplitCodePaths.clear(); 612 if (splitCodePaths != null) { 613 for (String split : splitCodePaths) { 614 mSplitCodePaths.add(split); 615 } 616 } 617 } 618 619 public void mergeAppDataDirs(String dataDir, int userId) { 620 Set<String> dataDirs = putIfAbsent(mAppDataDirs, userId, new HashSet<>()); 621 dataDirs.add(dataDir); 622 } 623 624 public int searchDex(String dexPath, int userId) { 625 // First check that this package is installed or active for the given user. 626 // A missing data dir means the package is not installed. 627 Set<String> userDataDirs = mAppDataDirs.get(userId); 628 if (userDataDirs == null) { 629 return DEX_SEARCH_NOT_FOUND; 630 } 631 632 if (mBaseCodePath.equals(dexPath)) { 633 return DEX_SEARCH_FOUND_PRIMARY; 634 } 635 if (mSplitCodePaths.contains(dexPath)) { 636 return DEX_SEARCH_FOUND_SPLIT; 637 } 638 for (String dataDir : userDataDirs) { 639 if (dexPath.startsWith(dataDir)) { 640 return DEX_SEARCH_FOUND_SECONDARY; 641 } 642 } 643 644 return DEX_SEARCH_NOT_FOUND; 645 } 646 } 647 648 /** 649 * Convenience class to store ownership search results. 650 */ 651 private class DexSearchResult { 652 private String mOwningPackageName; 653 private int mOutcome; 654 655 public DexSearchResult(String owningPackageName, int outcome) { 656 this.mOwningPackageName = owningPackageName; 657 this.mOutcome = outcome; 658 } 659 660 @Override 661 public String toString() { 662 return mOwningPackageName + "-" + mOutcome; 663 } 664 } 665} 666