PackageManagerService.java revision 20770ddbd4d6f2af0093f36462a8f44a678b084b
1/* 2 * Copyright (C) 2006 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 static android.Manifest.permission.GRANT_REVOKE_PERMISSIONS; 20import static android.Manifest.permission.READ_EXTERNAL_STORAGE; 21import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT; 22import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED; 23import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED; 24import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER; 25import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED; 26import static android.content.pm.PackageManager.INSTALL_EXTERNAL; 27import static android.content.pm.PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 28import static android.content.pm.PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER; 29import static android.content.pm.PackageManager.INSTALL_FAILED_DEXOPT; 30import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE; 31import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION; 32import static android.content.pm.PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 33import static android.content.pm.PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 34import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK; 35import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 36import static android.content.pm.PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY; 37import static android.content.pm.PackageManager.INSTALL_FAILED_PACKAGE_CHANGED; 38import static android.content.pm.PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE; 39import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE; 40import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY; 41import static android.content.pm.PackageManager.INSTALL_FAILED_UID_CHANGED; 42import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE; 43import static android.content.pm.PackageManager.INSTALL_FAILED_USER_RESTRICTED; 44import static android.content.pm.PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 45import static android.content.pm.PackageManager.INSTALL_FORWARD_LOCK; 46import static android.content.pm.PackageManager.INSTALL_INTERNAL; 47import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES; 48import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 49import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 50import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER; 51import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 52import static android.content.pm.PackageManager.MATCH_ALL; 53import static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST; 54import static android.content.pm.PackageManager.MOVE_FAILED_INTERNAL_ERROR; 55import static android.content.pm.PackageManager.MOVE_FAILED_OPERATION_PENDING; 56import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE; 57import static android.content.pm.PackageParser.isApkFile; 58import static android.os.Process.FIRST_APPLICATION_UID; 59import static android.os.Process.PACKAGE_INFO_GID; 60import static android.os.Process.SYSTEM_UID; 61import static android.system.OsConstants.O_CREAT; 62import static android.system.OsConstants.O_RDWR; 63import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE; 64import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_USER_OWNER; 65import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME; 66import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME; 67import static com.android.internal.util.ArrayUtils.appendInt; 68import static com.android.server.pm.InstructionSets.getAppDexInstructionSets; 69import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet; 70import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets; 71import static com.android.server.pm.InstructionSets.getPreferredInstructionSet; 72import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet; 73 74import android.Manifest; 75import android.app.ActivityManager; 76import android.app.ActivityManagerNative; 77import android.app.AppGlobals; 78import android.app.IActivityManager; 79import android.app.admin.IDevicePolicyManager; 80import android.app.backup.IBackupManager; 81import android.app.usage.UsageStats; 82import android.app.usage.UsageStatsManager; 83import android.content.BroadcastReceiver; 84import android.content.ComponentName; 85import android.content.Context; 86import android.content.IIntentReceiver; 87import android.content.Intent; 88import android.content.IntentFilter; 89import android.content.IntentSender; 90import android.content.IntentSender.SendIntentException; 91import android.content.ServiceConnection; 92import android.content.pm.ActivityInfo; 93import android.content.pm.ApplicationInfo; 94import android.content.pm.FeatureInfo; 95import android.content.pm.IPackageDataObserver; 96import android.content.pm.IPackageDeleteObserver; 97import android.content.pm.IPackageDeleteObserver2; 98import android.content.pm.IPackageInstallObserver2; 99import android.content.pm.IPackageInstaller; 100import android.content.pm.IPackageManager; 101import android.content.pm.IPackageMoveObserver; 102import android.content.pm.IPackageStatsObserver; 103import android.content.pm.InstrumentationInfo; 104import android.content.pm.IntentFilterVerificationInfo; 105import android.content.pm.KeySet; 106import android.content.pm.ManifestDigest; 107import android.content.pm.PackageCleanItem; 108import android.content.pm.PackageInfo; 109import android.content.pm.PackageInfoLite; 110import android.content.pm.PackageInstaller; 111import android.content.pm.PackageManager; 112import android.content.pm.PackageManager.LegacyPackageDeleteObserver; 113import android.content.pm.PackageParser; 114import android.content.pm.PackageParser.ActivityIntentInfo; 115import android.content.pm.PackageParser.PackageLite; 116import android.content.pm.PackageParser.PackageParserException; 117import android.content.pm.PackageStats; 118import android.content.pm.PackageUserState; 119import android.content.pm.ParceledListSlice; 120import android.content.pm.PermissionGroupInfo; 121import android.content.pm.PermissionInfo; 122import android.content.pm.ProviderInfo; 123import android.content.pm.ResolveInfo; 124import android.content.pm.ServiceInfo; 125import android.content.pm.Signature; 126import android.content.pm.UserInfo; 127import android.content.pm.VerificationParams; 128import android.content.pm.VerifierDeviceIdentity; 129import android.content.pm.VerifierInfo; 130import android.content.res.Resources; 131import android.hardware.display.DisplayManager; 132import android.net.Uri; 133import android.os.Binder; 134import android.os.Build; 135import android.os.Bundle; 136import android.os.Debug; 137import android.os.Environment; 138import android.os.Environment.UserEnvironment; 139import android.os.FileUtils; 140import android.os.Handler; 141import android.os.IBinder; 142import android.os.Looper; 143import android.os.Message; 144import android.os.Parcel; 145import android.os.ParcelFileDescriptor; 146import android.os.Process; 147import android.os.RemoteCallbackList; 148import android.os.RemoteException; 149import android.os.SELinux; 150import android.os.ServiceManager; 151import android.os.SystemClock; 152import android.os.SystemProperties; 153import android.os.UserHandle; 154import android.os.UserManager; 155import android.os.storage.IMountService; 156import android.os.storage.StorageEventListener; 157import android.os.storage.StorageManager; 158import android.os.storage.VolumeInfo; 159import android.os.storage.VolumeRecord; 160import android.security.KeyStore; 161import android.security.SystemKeyStore; 162import android.system.ErrnoException; 163import android.system.Os; 164import android.system.StructStat; 165import android.text.TextUtils; 166import android.text.format.DateUtils; 167import android.util.ArrayMap; 168import android.util.ArraySet; 169import android.util.AtomicFile; 170import android.util.DisplayMetrics; 171import android.util.EventLog; 172import android.util.ExceptionUtils; 173import android.util.Log; 174import android.util.LogPrinter; 175import android.util.MathUtils; 176import android.util.PrintStreamPrinter; 177import android.util.Slog; 178import android.util.SparseArray; 179import android.util.SparseBooleanArray; 180import android.util.SparseIntArray; 181import android.util.Xml; 182import android.view.Display; 183 184import dalvik.system.DexFile; 185import dalvik.system.VMRuntime; 186 187import libcore.io.IoUtils; 188import libcore.util.EmptyArray; 189 190import com.android.internal.R; 191import com.android.internal.app.IMediaContainerService; 192import com.android.internal.app.ResolverActivity; 193import com.android.internal.content.NativeLibraryHelper; 194import com.android.internal.content.PackageHelper; 195import com.android.internal.os.IParcelFileDescriptorFactory; 196import com.android.internal.os.SomeArgs; 197import com.android.internal.util.ArrayUtils; 198import com.android.internal.util.FastPrintWriter; 199import com.android.internal.util.FastXmlSerializer; 200import com.android.internal.util.IndentingPrintWriter; 201import com.android.internal.util.Preconditions; 202import com.android.server.EventLogTags; 203import com.android.server.FgThread; 204import com.android.server.IntentResolver; 205import com.android.server.LocalServices; 206import com.android.server.ServiceThread; 207import com.android.server.SystemConfig; 208import com.android.server.Watchdog; 209import com.android.server.pm.Settings.DatabaseVersion; 210import com.android.server.pm.PermissionsState.PermissionState; 211import com.android.server.storage.DeviceStorageMonitorInternal; 212 213import org.xmlpull.v1.XmlPullParser; 214import org.xmlpull.v1.XmlSerializer; 215 216import java.io.BufferedInputStream; 217import java.io.BufferedOutputStream; 218import java.io.BufferedReader; 219import java.io.ByteArrayInputStream; 220import java.io.ByteArrayOutputStream; 221import java.io.File; 222import java.io.FileDescriptor; 223import java.io.FileNotFoundException; 224import java.io.FileOutputStream; 225import java.io.FileReader; 226import java.io.FilenameFilter; 227import java.io.IOException; 228import java.io.InputStream; 229import java.io.PrintWriter; 230import java.nio.charset.StandardCharsets; 231import java.security.NoSuchAlgorithmException; 232import java.security.PublicKey; 233import java.security.cert.CertificateEncodingException; 234import java.security.cert.CertificateException; 235import java.text.SimpleDateFormat; 236import java.util.ArrayList; 237import java.util.Arrays; 238import java.util.Collection; 239import java.util.Collections; 240import java.util.Comparator; 241import java.util.Date; 242import java.util.Iterator; 243import java.util.List; 244import java.util.Map; 245import java.util.Objects; 246import java.util.Set; 247import java.util.concurrent.CountDownLatch; 248import java.util.concurrent.TimeUnit; 249import java.util.concurrent.atomic.AtomicBoolean; 250import java.util.concurrent.atomic.AtomicInteger; 251import java.util.concurrent.atomic.AtomicLong; 252 253/** 254 * Keep track of all those .apks everywhere. 255 * 256 * This is very central to the platform's security; please run the unit 257 * tests whenever making modifications here: 258 * 259mmm frameworks/base/tests/AndroidTests 260adb install -r -f out/target/product/passion/data/app/AndroidTests.apk 261adb shell am instrument -w -e class com.android.unit_tests.PackageManagerTests com.android.unit_tests/android.test.InstrumentationTestRunner 262 * 263 * {@hide} 264 */ 265public class PackageManagerService extends IPackageManager.Stub { 266 static final String TAG = "PackageManager"; 267 static final boolean DEBUG_SETTINGS = false; 268 static final boolean DEBUG_PREFERRED = false; 269 static final boolean DEBUG_UPGRADE = false; 270 private static final boolean DEBUG_BACKUP = true; 271 private static final boolean DEBUG_INSTALL = false; 272 private static final boolean DEBUG_REMOVE = false; 273 private static final boolean DEBUG_BROADCASTS = false; 274 private static final boolean DEBUG_SHOW_INFO = false; 275 private static final boolean DEBUG_PACKAGE_INFO = false; 276 private static final boolean DEBUG_INTENT_MATCHING = false; 277 private static final boolean DEBUG_PACKAGE_SCANNING = false; 278 private static final boolean DEBUG_VERIFY = false; 279 private static final boolean DEBUG_DEXOPT = false; 280 private static final boolean DEBUG_ABI_SELECTION = false; 281 282 private static final int RADIO_UID = Process.PHONE_UID; 283 private static final int LOG_UID = Process.LOG_UID; 284 private static final int NFC_UID = Process.NFC_UID; 285 private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID; 286 private static final int SHELL_UID = Process.SHELL_UID; 287 288 // Cap the size of permission trees that 3rd party apps can define 289 private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768; // characters of text 290 291 // Suffix used during package installation when copying/moving 292 // package apks to install directory. 293 private static final String INSTALL_PACKAGE_SUFFIX = "-"; 294 295 static final int SCAN_NO_DEX = 1<<1; 296 static final int SCAN_FORCE_DEX = 1<<2; 297 static final int SCAN_UPDATE_SIGNATURE = 1<<3; 298 static final int SCAN_NEW_INSTALL = 1<<4; 299 static final int SCAN_NO_PATHS = 1<<5; 300 static final int SCAN_UPDATE_TIME = 1<<6; 301 static final int SCAN_DEFER_DEX = 1<<7; 302 static final int SCAN_BOOTING = 1<<8; 303 static final int SCAN_TRUSTED_OVERLAY = 1<<9; 304 static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10; 305 static final int SCAN_REQUIRE_KNOWN = 1<<12; 306 static final int SCAN_MOVE = 1<<13; 307 308 static final int REMOVE_CHATTY = 1<<16; 309 310 private static final int[] EMPTY_INT_ARRAY = new int[0]; 311 312 /** 313 * Timeout (in milliseconds) after which the watchdog should declare that 314 * our handler thread is wedged. The usual default for such things is one 315 * minute but we sometimes do very lengthy I/O operations on this thread, 316 * such as installing multi-gigabyte applications, so ours needs to be longer. 317 */ 318 private static final long WATCHDOG_TIMEOUT = 1000*60*10; // ten minutes 319 320 /** 321 * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim 322 * be run on this device. We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL 323 * settings entry if available, otherwise we use the hardcoded default. If it's been 324 * more than this long since the last fstrim, we force one during the boot sequence. 325 * 326 * This backstops other fstrim scheduling: if the device is alive at midnight+idle, 327 * one gets run at the next available charging+idle time. This final mandatory 328 * no-fstrim check kicks in only of the other scheduling criteria is never met. 329 */ 330 private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS; 331 332 /** 333 * Whether verification is enabled by default. 334 */ 335 private static final boolean DEFAULT_VERIFY_ENABLE = true; 336 337 /** 338 * The default maximum time to wait for the verification agent to return in 339 * milliseconds. 340 */ 341 private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000; 342 343 /** 344 * The default response for package verification timeout. 345 * 346 * This can be either PackageManager.VERIFICATION_ALLOW or 347 * PackageManager.VERIFICATION_REJECT. 348 */ 349 private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW; 350 351 static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer"; 352 353 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName( 354 DEFAULT_CONTAINER_PACKAGE, 355 "com.android.defcontainer.DefaultContainerService"); 356 357 private static final String KILL_APP_REASON_GIDS_CHANGED = 358 "permission grant or revoke changed gids"; 359 360 private static final String KILL_APP_REASON_PERMISSIONS_REVOKED = 361 "permissions revoked"; 362 363 private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive"; 364 365 private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay"; 366 367 /** Permission grant: not grant the permission. */ 368 private static final int GRANT_DENIED = 1; 369 370 /** Permission grant: grant the permission as an install permission. */ 371 private static final int GRANT_INSTALL = 2; 372 373 /** Permission grant: grant the permission as an install permission for a legacy app. */ 374 private static final int GRANT_INSTALL_LEGACY = 3; 375 376 /** Permission grant: grant the permission as a runtime one. */ 377 private static final int GRANT_RUNTIME = 4; 378 379 /** Permission grant: grant as runtime a permission that was granted as an install time one. */ 380 private static final int GRANT_UPGRADE = 5; 381 382 final ServiceThread mHandlerThread; 383 384 final PackageHandler mHandler; 385 386 /** 387 * Messages for {@link #mHandler} that need to wait for system ready before 388 * being dispatched. 389 */ 390 private ArrayList<Message> mPostSystemReadyMessages; 391 392 final int mSdkVersion = Build.VERSION.SDK_INT; 393 394 final Context mContext; 395 final boolean mFactoryTest; 396 final boolean mOnlyCore; 397 final boolean mLazyDexOpt; 398 final long mDexOptLRUThresholdInMills; 399 final DisplayMetrics mMetrics; 400 final int mDefParseFlags; 401 final String[] mSeparateProcesses; 402 final boolean mIsUpgrade; 403 404 // This is where all application persistent data goes. 405 final File mAppDataDir; 406 407 // This is where all application persistent data goes for secondary users. 408 final File mUserAppDataDir; 409 410 /** The location for ASEC container files on internal storage. */ 411 final String mAsecInternalPath; 412 413 // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages 414 // LOCK HELD. Can be called with mInstallLock held. 415 final Installer mInstaller; 416 417 /** Directory where installed third-party apps stored */ 418 final File mAppInstallDir; 419 420 /** 421 * Directory to which applications installed internally have their 422 * 32 bit native libraries copied. 423 */ 424 private File mAppLib32InstallDir; 425 426 // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked 427 // apps. 428 final File mDrmAppPrivateInstallDir; 429 430 // ---------------------------------------------------------------- 431 432 // Lock for state used when installing and doing other long running 433 // operations. Methods that must be called with this lock held have 434 // the suffix "LI". 435 final Object mInstallLock = new Object(); 436 437 // ---------------------------------------------------------------- 438 439 // Keys are String (package name), values are Package. This also serves 440 // as the lock for the global state. Methods that must be called with 441 // this lock held have the prefix "LP". 442 final ArrayMap<String, PackageParser.Package> mPackages = 443 new ArrayMap<String, PackageParser.Package>(); 444 445 // Tracks available target package names -> overlay package paths. 446 final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays = 447 new ArrayMap<String, ArrayMap<String, PackageParser.Package>>(); 448 449 final Settings mSettings; 450 boolean mRestoredSettings; 451 452 // System configuration read by SystemConfig. 453 final int[] mGlobalGids; 454 final SparseArray<ArraySet<String>> mSystemPermissions; 455 final ArrayMap<String, FeatureInfo> mAvailableFeatures; 456 457 // If mac_permissions.xml was found for seinfo labeling. 458 boolean mFoundPolicyFile; 459 460 // If a recursive restorecon of /data/data/<pkg> is needed. 461 private boolean mShouldRestoreconData = SELinuxMMAC.shouldRestorecon(); 462 463 public static final class SharedLibraryEntry { 464 public final String path; 465 public final String apk; 466 467 SharedLibraryEntry(String _path, String _apk) { 468 path = _path; 469 apk = _apk; 470 } 471 } 472 473 // Currently known shared libraries. 474 final ArrayMap<String, SharedLibraryEntry> mSharedLibraries = 475 new ArrayMap<String, SharedLibraryEntry>(); 476 477 // All available activities, for your resolving pleasure. 478 final ActivityIntentResolver mActivities = 479 new ActivityIntentResolver(); 480 481 // All available receivers, for your resolving pleasure. 482 final ActivityIntentResolver mReceivers = 483 new ActivityIntentResolver(); 484 485 // All available services, for your resolving pleasure. 486 final ServiceIntentResolver mServices = new ServiceIntentResolver(); 487 488 // All available providers, for your resolving pleasure. 489 final ProviderIntentResolver mProviders = new ProviderIntentResolver(); 490 491 // Mapping from provider base names (first directory in content URI codePath) 492 // to the provider information. 493 final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority = 494 new ArrayMap<String, PackageParser.Provider>(); 495 496 // Mapping from instrumentation class names to info about them. 497 final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation = 498 new ArrayMap<ComponentName, PackageParser.Instrumentation>(); 499 500 // Mapping from permission names to info about them. 501 final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups = 502 new ArrayMap<String, PackageParser.PermissionGroup>(); 503 504 // Packages whose data we have transfered into another package, thus 505 // should no longer exist. 506 final ArraySet<String> mTransferedPackages = new ArraySet<String>(); 507 508 // Broadcast actions that are only available to the system. 509 final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>(); 510 511 /** List of packages waiting for verification. */ 512 final SparseArray<PackageVerificationState> mPendingVerification 513 = new SparseArray<PackageVerificationState>(); 514 515 /** Set of packages associated with each app op permission. */ 516 final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>(); 517 518 final PackageInstallerService mInstallerService; 519 520 private final PackageDexOptimizer mPackageDexOptimizer; 521 522 private AtomicInteger mNextMoveId = new AtomicInteger(); 523 private final MoveCallbacks mMoveCallbacks; 524 525 // Cache of users who need badging. 526 SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray(); 527 528 /** Token for keys in mPendingVerification. */ 529 private int mPendingVerificationToken = 0; 530 531 volatile boolean mSystemReady; 532 volatile boolean mSafeMode; 533 volatile boolean mHasSystemUidErrors; 534 535 ApplicationInfo mAndroidApplication; 536 final ActivityInfo mResolveActivity = new ActivityInfo(); 537 final ResolveInfo mResolveInfo = new ResolveInfo(); 538 ComponentName mResolveComponentName; 539 PackageParser.Package mPlatformPackage; 540 ComponentName mCustomResolverComponentName; 541 542 boolean mResolverReplaced = false; 543 544 private final ComponentName mIntentFilterVerifierComponent; 545 private int mIntentFilterVerificationToken = 0; 546 547 final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates 548 = new SparseArray<IntentFilterVerificationState>(); 549 550 private interface IntentFilterVerifier<T extends IntentFilter> { 551 boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId, 552 T filter, String packageName); 553 void startVerifications(int userId); 554 void receiveVerificationResponse(int verificationId); 555 } 556 557 private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> { 558 private Context mContext; 559 private ComponentName mIntentFilterVerifierComponent; 560 private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>(); 561 562 public IntentVerifierProxy(Context context, ComponentName verifierComponent) { 563 mContext = context; 564 mIntentFilterVerifierComponent = verifierComponent; 565 } 566 567 private String getDefaultScheme() { 568 // TODO: replace SCHEME_HTTP with SCHEME_HTTPS 569 return IntentFilter.SCHEME_HTTP; 570 } 571 572 @Override 573 public void startVerifications(int userId) { 574 // Launch verifications requests 575 int count = mCurrentIntentFilterVerifications.size(); 576 for (int n=0; n<count; n++) { 577 int verificationId = mCurrentIntentFilterVerifications.get(n); 578 final IntentFilterVerificationState ivs = 579 mIntentFilterVerificationStates.get(verificationId); 580 581 String packageName = ivs.getPackageName(); 582 583 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 584 final int filterCount = filters.size(); 585 ArraySet<String> domainsSet = new ArraySet<>(); 586 for (int m=0; m<filterCount; m++) { 587 PackageParser.ActivityIntentInfo filter = filters.get(m); 588 domainsSet.addAll(filter.getHostsList()); 589 } 590 ArrayList<String> domainsList = new ArrayList<>(domainsSet); 591 synchronized (mPackages) { 592 if (mSettings.createIntentFilterVerificationIfNeededLPw( 593 packageName, domainsList) != null) { 594 scheduleWriteSettingsLocked(); 595 } 596 } 597 sendVerificationRequest(userId, verificationId, ivs); 598 } 599 mCurrentIntentFilterVerifications.clear(); 600 } 601 602 private void sendVerificationRequest(int userId, int verificationId, 603 IntentFilterVerificationState ivs) { 604 605 Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 606 verificationIntent.putExtra( 607 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID, 608 verificationId); 609 verificationIntent.putExtra( 610 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME, 611 getDefaultScheme()); 612 verificationIntent.putExtra( 613 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS, 614 ivs.getHostsString()); 615 verificationIntent.putExtra( 616 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME, 617 ivs.getPackageName()); 618 verificationIntent.setComponent(mIntentFilterVerifierComponent); 619 verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 620 621 UserHandle user = new UserHandle(userId); 622 mContext.sendBroadcastAsUser(verificationIntent, user); 623 Slog.d(TAG, "Sending IntenFilter verification broadcast"); 624 } 625 626 public void receiveVerificationResponse(int verificationId) { 627 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 628 629 final boolean verified = ivs.isVerified(); 630 631 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 632 final int count = filters.size(); 633 for (int n=0; n<count; n++) { 634 PackageParser.ActivityIntentInfo filter = filters.get(n); 635 filter.setVerified(verified); 636 637 Slog.d(TAG, "IntentFilter " + filter.toString() + " verified with result:" 638 + verified + " and hosts:" + ivs.getHostsString()); 639 } 640 641 mIntentFilterVerificationStates.remove(verificationId); 642 643 final String packageName = ivs.getPackageName(); 644 IntentFilterVerificationInfo ivi = null; 645 646 synchronized (mPackages) { 647 ivi = mSettings.getIntentFilterVerificationLPr(packageName); 648 } 649 if (ivi == null) { 650 Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:" 651 + verificationId + " packageName:" + packageName); 652 return; 653 } 654 Slog.d(TAG, "Updating IntentFilterVerificationInfo for verificationId:" 655 + verificationId); 656 657 synchronized (mPackages) { 658 if (verified) { 659 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS); 660 } else { 661 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK); 662 } 663 scheduleWriteSettingsLocked(); 664 665 final int userId = ivs.getUserId(); 666 if (userId != UserHandle.USER_ALL) { 667 final int userStatus = 668 mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 669 670 int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 671 boolean needUpdate = false; 672 673 // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have 674 // already been set by the User thru the Disambiguation dialog 675 switch (userStatus) { 676 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 677 if (verified) { 678 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 679 } else { 680 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 681 } 682 needUpdate = true; 683 break; 684 685 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 686 if (verified) { 687 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 688 needUpdate = true; 689 } 690 break; 691 692 default: 693 // Nothing to do 694 } 695 696 if (needUpdate) { 697 mSettings.updateIntentFilterVerificationStatusLPw( 698 packageName, updatedStatus, userId); 699 scheduleWritePackageRestrictionsLocked(userId); 700 } 701 } 702 } 703 } 704 705 @Override 706 public boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId, 707 ActivityIntentInfo filter, String packageName) { 708 if (!(filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 709 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) { 710 Slog.d(TAG, "IntentFilter does not contain HTTP nor HTTPS data scheme"); 711 return false; 712 } 713 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 714 if (ivs == null) { 715 ivs = createDomainVerificationState(verifierId, userId, verificationId, 716 packageName); 717 } 718 if (!hasValidDomains(filter)) { 719 return false; 720 } 721 ivs.addFilter(filter); 722 return true; 723 } 724 725 private IntentFilterVerificationState createDomainVerificationState(int verifierId, 726 int userId, int verificationId, String packageName) { 727 IntentFilterVerificationState ivs = new IntentFilterVerificationState( 728 verifierId, userId, packageName); 729 ivs.setPendingState(); 730 synchronized (mPackages) { 731 mIntentFilterVerificationStates.append(verificationId, ivs); 732 mCurrentIntentFilterVerifications.add(verificationId); 733 } 734 return ivs; 735 } 736 } 737 738 private static boolean hasValidDomains(ActivityIntentInfo filter) { 739 return hasValidDomains(filter, true); 740 } 741 742 private static boolean hasValidDomains(ActivityIntentInfo filter, boolean logging) { 743 boolean hasHTTPorHTTPS = filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 744 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS); 745 if (!hasHTTPorHTTPS) { 746 if (logging) { 747 Slog.d(TAG, "IntentFilter does not contain any HTTP or HTTPS data scheme"); 748 } 749 return false; 750 } 751 return true; 752 } 753 754 private IntentFilterVerifier mIntentFilterVerifier; 755 756 // Set of pending broadcasts for aggregating enable/disable of components. 757 static class PendingPackageBroadcasts { 758 // for each user id, a map of <package name -> components within that package> 759 final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap; 760 761 public PendingPackageBroadcasts() { 762 mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2); 763 } 764 765 public ArrayList<String> get(int userId, String packageName) { 766 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 767 return packages.get(packageName); 768 } 769 770 public void put(int userId, String packageName, ArrayList<String> components) { 771 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 772 packages.put(packageName, components); 773 } 774 775 public void remove(int userId, String packageName) { 776 ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId); 777 if (packages != null) { 778 packages.remove(packageName); 779 } 780 } 781 782 public void remove(int userId) { 783 mUidMap.remove(userId); 784 } 785 786 public int userIdCount() { 787 return mUidMap.size(); 788 } 789 790 public int userIdAt(int n) { 791 return mUidMap.keyAt(n); 792 } 793 794 public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) { 795 return mUidMap.get(userId); 796 } 797 798 public int size() { 799 // total number of pending broadcast entries across all userIds 800 int num = 0; 801 for (int i = 0; i< mUidMap.size(); i++) { 802 num += mUidMap.valueAt(i).size(); 803 } 804 return num; 805 } 806 807 public void clear() { 808 mUidMap.clear(); 809 } 810 811 private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) { 812 ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId); 813 if (map == null) { 814 map = new ArrayMap<String, ArrayList<String>>(); 815 mUidMap.put(userId, map); 816 } 817 return map; 818 } 819 } 820 final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts(); 821 822 // Service Connection to remote media container service to copy 823 // package uri's from external media onto secure containers 824 // or internal storage. 825 private IMediaContainerService mContainerService = null; 826 827 static final int SEND_PENDING_BROADCAST = 1; 828 static final int MCS_BOUND = 3; 829 static final int END_COPY = 4; 830 static final int INIT_COPY = 5; 831 static final int MCS_UNBIND = 6; 832 static final int START_CLEANING_PACKAGE = 7; 833 static final int FIND_INSTALL_LOC = 8; 834 static final int POST_INSTALL = 9; 835 static final int MCS_RECONNECT = 10; 836 static final int MCS_GIVE_UP = 11; 837 static final int UPDATED_MEDIA_STATUS = 12; 838 static final int WRITE_SETTINGS = 13; 839 static final int WRITE_PACKAGE_RESTRICTIONS = 14; 840 static final int PACKAGE_VERIFIED = 15; 841 static final int CHECK_PENDING_VERIFICATION = 16; 842 static final int START_INTENT_FILTER_VERIFICATIONS = 17; 843 static final int INTENT_FILTER_VERIFIED = 18; 844 845 static final int WRITE_SETTINGS_DELAY = 10*1000; // 10 seconds 846 847 // Delay time in millisecs 848 static final int BROADCAST_DELAY = 10 * 1000; 849 850 static UserManagerService sUserManager; 851 852 // Stores a list of users whose package restrictions file needs to be updated 853 private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>(); 854 855 final private DefaultContainerConnection mDefContainerConn = 856 new DefaultContainerConnection(); 857 class DefaultContainerConnection implements ServiceConnection { 858 public void onServiceConnected(ComponentName name, IBinder service) { 859 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected"); 860 IMediaContainerService imcs = 861 IMediaContainerService.Stub.asInterface(service); 862 mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs)); 863 } 864 865 public void onServiceDisconnected(ComponentName name) { 866 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected"); 867 } 868 }; 869 870 // Recordkeeping of restore-after-install operations that are currently in flight 871 // between the Package Manager and the Backup Manager 872 class PostInstallData { 873 public InstallArgs args; 874 public PackageInstalledInfo res; 875 876 PostInstallData(InstallArgs _a, PackageInstalledInfo _r) { 877 args = _a; 878 res = _r; 879 } 880 }; 881 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>(); 882 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows 883 884 // backup/restore of preferred activity state 885 private static final String TAG_PREFERRED_BACKUP = "pa"; 886 887 private final String mRequiredVerifierPackage; 888 889 private final PackageUsage mPackageUsage = new PackageUsage(); 890 891 private class PackageUsage { 892 private static final int WRITE_INTERVAL 893 = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms 894 895 private final Object mFileLock = new Object(); 896 private final AtomicLong mLastWritten = new AtomicLong(0); 897 private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false); 898 899 private boolean mIsHistoricalPackageUsageAvailable = true; 900 901 boolean isHistoricalPackageUsageAvailable() { 902 return mIsHistoricalPackageUsageAvailable; 903 } 904 905 void write(boolean force) { 906 if (force) { 907 writeInternal(); 908 return; 909 } 910 if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL 911 && !DEBUG_DEXOPT) { 912 return; 913 } 914 if (mBackgroundWriteRunning.compareAndSet(false, true)) { 915 new Thread("PackageUsage_DiskWriter") { 916 @Override 917 public void run() { 918 try { 919 writeInternal(); 920 } finally { 921 mBackgroundWriteRunning.set(false); 922 } 923 } 924 }.start(); 925 } 926 } 927 928 private void writeInternal() { 929 synchronized (mPackages) { 930 synchronized (mFileLock) { 931 AtomicFile file = getFile(); 932 FileOutputStream f = null; 933 try { 934 f = file.startWrite(); 935 BufferedOutputStream out = new BufferedOutputStream(f); 936 FileUtils.setPermissions(file.getBaseFile().getPath(), 0640, SYSTEM_UID, PACKAGE_INFO_GID); 937 StringBuilder sb = new StringBuilder(); 938 for (PackageParser.Package pkg : mPackages.values()) { 939 if (pkg.mLastPackageUsageTimeInMills == 0) { 940 continue; 941 } 942 sb.setLength(0); 943 sb.append(pkg.packageName); 944 sb.append(' '); 945 sb.append((long)pkg.mLastPackageUsageTimeInMills); 946 sb.append('\n'); 947 out.write(sb.toString().getBytes(StandardCharsets.US_ASCII)); 948 } 949 out.flush(); 950 file.finishWrite(f); 951 } catch (IOException e) { 952 if (f != null) { 953 file.failWrite(f); 954 } 955 Log.e(TAG, "Failed to write package usage times", e); 956 } 957 } 958 } 959 mLastWritten.set(SystemClock.elapsedRealtime()); 960 } 961 962 void readLP() { 963 synchronized (mFileLock) { 964 AtomicFile file = getFile(); 965 BufferedInputStream in = null; 966 try { 967 in = new BufferedInputStream(file.openRead()); 968 StringBuffer sb = new StringBuffer(); 969 while (true) { 970 String packageName = readToken(in, sb, ' '); 971 if (packageName == null) { 972 break; 973 } 974 String timeInMillisString = readToken(in, sb, '\n'); 975 if (timeInMillisString == null) { 976 throw new IOException("Failed to find last usage time for package " 977 + packageName); 978 } 979 PackageParser.Package pkg = mPackages.get(packageName); 980 if (pkg == null) { 981 continue; 982 } 983 long timeInMillis; 984 try { 985 timeInMillis = Long.parseLong(timeInMillisString.toString()); 986 } catch (NumberFormatException e) { 987 throw new IOException("Failed to parse " + timeInMillisString 988 + " as a long.", e); 989 } 990 pkg.mLastPackageUsageTimeInMills = timeInMillis; 991 } 992 } catch (FileNotFoundException expected) { 993 mIsHistoricalPackageUsageAvailable = false; 994 } catch (IOException e) { 995 Log.w(TAG, "Failed to read package usage times", e); 996 } finally { 997 IoUtils.closeQuietly(in); 998 } 999 } 1000 mLastWritten.set(SystemClock.elapsedRealtime()); 1001 } 1002 1003 private String readToken(InputStream in, StringBuffer sb, char endOfToken) 1004 throws IOException { 1005 sb.setLength(0); 1006 while (true) { 1007 int ch = in.read(); 1008 if (ch == -1) { 1009 if (sb.length() == 0) { 1010 return null; 1011 } 1012 throw new IOException("Unexpected EOF"); 1013 } 1014 if (ch == endOfToken) { 1015 return sb.toString(); 1016 } 1017 sb.append((char)ch); 1018 } 1019 } 1020 1021 private AtomicFile getFile() { 1022 File dataDir = Environment.getDataDirectory(); 1023 File systemDir = new File(dataDir, "system"); 1024 File fname = new File(systemDir, "package-usage.list"); 1025 return new AtomicFile(fname); 1026 } 1027 } 1028 1029 class PackageHandler extends Handler { 1030 private boolean mBound = false; 1031 final ArrayList<HandlerParams> mPendingInstalls = 1032 new ArrayList<HandlerParams>(); 1033 1034 private boolean connectToService() { 1035 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" + 1036 " DefaultContainerService"); 1037 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 1038 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1039 if (mContext.bindServiceAsUser(service, mDefContainerConn, 1040 Context.BIND_AUTO_CREATE, UserHandle.OWNER)) { 1041 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1042 mBound = true; 1043 return true; 1044 } 1045 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1046 return false; 1047 } 1048 1049 private void disconnectService() { 1050 mContainerService = null; 1051 mBound = false; 1052 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1053 mContext.unbindService(mDefContainerConn); 1054 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1055 } 1056 1057 PackageHandler(Looper looper) { 1058 super(looper); 1059 } 1060 1061 public void handleMessage(Message msg) { 1062 try { 1063 doHandleMessage(msg); 1064 } finally { 1065 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1066 } 1067 } 1068 1069 void doHandleMessage(Message msg) { 1070 switch (msg.what) { 1071 case INIT_COPY: { 1072 HandlerParams params = (HandlerParams) msg.obj; 1073 int idx = mPendingInstalls.size(); 1074 if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params); 1075 // If a bind was already initiated we dont really 1076 // need to do anything. The pending install 1077 // will be processed later on. 1078 if (!mBound) { 1079 // If this is the only one pending we might 1080 // have to bind to the service again. 1081 if (!connectToService()) { 1082 Slog.e(TAG, "Failed to bind to media container service"); 1083 params.serviceError(); 1084 return; 1085 } else { 1086 // Once we bind to the service, the first 1087 // pending request will be processed. 1088 mPendingInstalls.add(idx, params); 1089 } 1090 } else { 1091 mPendingInstalls.add(idx, params); 1092 // Already bound to the service. Just make 1093 // sure we trigger off processing the first request. 1094 if (idx == 0) { 1095 mHandler.sendEmptyMessage(MCS_BOUND); 1096 } 1097 } 1098 break; 1099 } 1100 case MCS_BOUND: { 1101 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound"); 1102 if (msg.obj != null) { 1103 mContainerService = (IMediaContainerService) msg.obj; 1104 } 1105 if (mContainerService == null) { 1106 // Something seriously wrong. Bail out 1107 Slog.e(TAG, "Cannot bind to media container service"); 1108 for (HandlerParams params : mPendingInstalls) { 1109 // Indicate service bind error 1110 params.serviceError(); 1111 } 1112 mPendingInstalls.clear(); 1113 } else if (mPendingInstalls.size() > 0) { 1114 HandlerParams params = mPendingInstalls.get(0); 1115 if (params != null) { 1116 if (params.startCopy()) { 1117 // We are done... look for more work or to 1118 // go idle. 1119 if (DEBUG_SD_INSTALL) Log.i(TAG, 1120 "Checking for more work or unbind..."); 1121 // Delete pending install 1122 if (mPendingInstalls.size() > 0) { 1123 mPendingInstalls.remove(0); 1124 } 1125 if (mPendingInstalls.size() == 0) { 1126 if (mBound) { 1127 if (DEBUG_SD_INSTALL) Log.i(TAG, 1128 "Posting delayed MCS_UNBIND"); 1129 removeMessages(MCS_UNBIND); 1130 Message ubmsg = obtainMessage(MCS_UNBIND); 1131 // Unbind after a little delay, to avoid 1132 // continual thrashing. 1133 sendMessageDelayed(ubmsg, 10000); 1134 } 1135 } else { 1136 // There are more pending requests in queue. 1137 // Just post MCS_BOUND message to trigger processing 1138 // of next pending install. 1139 if (DEBUG_SD_INSTALL) Log.i(TAG, 1140 "Posting MCS_BOUND for next work"); 1141 mHandler.sendEmptyMessage(MCS_BOUND); 1142 } 1143 } 1144 } 1145 } else { 1146 // Should never happen ideally. 1147 Slog.w(TAG, "Empty queue"); 1148 } 1149 break; 1150 } 1151 case MCS_RECONNECT: { 1152 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect"); 1153 if (mPendingInstalls.size() > 0) { 1154 if (mBound) { 1155 disconnectService(); 1156 } 1157 if (!connectToService()) { 1158 Slog.e(TAG, "Failed to bind to media container service"); 1159 for (HandlerParams params : mPendingInstalls) { 1160 // Indicate service bind error 1161 params.serviceError(); 1162 } 1163 mPendingInstalls.clear(); 1164 } 1165 } 1166 break; 1167 } 1168 case MCS_UNBIND: { 1169 // If there is no actual work left, then time to unbind. 1170 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind"); 1171 1172 if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) { 1173 if (mBound) { 1174 if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()"); 1175 1176 disconnectService(); 1177 } 1178 } else if (mPendingInstalls.size() > 0) { 1179 // There are more pending requests in queue. 1180 // Just post MCS_BOUND message to trigger processing 1181 // of next pending install. 1182 mHandler.sendEmptyMessage(MCS_BOUND); 1183 } 1184 1185 break; 1186 } 1187 case MCS_GIVE_UP: { 1188 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries"); 1189 mPendingInstalls.remove(0); 1190 break; 1191 } 1192 case SEND_PENDING_BROADCAST: { 1193 String packages[]; 1194 ArrayList<String> components[]; 1195 int size = 0; 1196 int uids[]; 1197 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1198 synchronized (mPackages) { 1199 if (mPendingBroadcasts == null) { 1200 return; 1201 } 1202 size = mPendingBroadcasts.size(); 1203 if (size <= 0) { 1204 // Nothing to be done. Just return 1205 return; 1206 } 1207 packages = new String[size]; 1208 components = new ArrayList[size]; 1209 uids = new int[size]; 1210 int i = 0; // filling out the above arrays 1211 1212 for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) { 1213 int packageUserId = mPendingBroadcasts.userIdAt(n); 1214 Iterator<Map.Entry<String, ArrayList<String>>> it 1215 = mPendingBroadcasts.packagesForUserId(packageUserId) 1216 .entrySet().iterator(); 1217 while (it.hasNext() && i < size) { 1218 Map.Entry<String, ArrayList<String>> ent = it.next(); 1219 packages[i] = ent.getKey(); 1220 components[i] = ent.getValue(); 1221 PackageSetting ps = mSettings.mPackages.get(ent.getKey()); 1222 uids[i] = (ps != null) 1223 ? UserHandle.getUid(packageUserId, ps.appId) 1224 : -1; 1225 i++; 1226 } 1227 } 1228 size = i; 1229 mPendingBroadcasts.clear(); 1230 } 1231 // Send broadcasts 1232 for (int i = 0; i < size; i++) { 1233 sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]); 1234 } 1235 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1236 break; 1237 } 1238 case START_CLEANING_PACKAGE: { 1239 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1240 final String packageName = (String)msg.obj; 1241 final int userId = msg.arg1; 1242 final boolean andCode = msg.arg2 != 0; 1243 synchronized (mPackages) { 1244 if (userId == UserHandle.USER_ALL) { 1245 int[] users = sUserManager.getUserIds(); 1246 for (int user : users) { 1247 mSettings.addPackageToCleanLPw( 1248 new PackageCleanItem(user, packageName, andCode)); 1249 } 1250 } else { 1251 mSettings.addPackageToCleanLPw( 1252 new PackageCleanItem(userId, packageName, andCode)); 1253 } 1254 } 1255 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1256 startCleaningPackages(); 1257 } break; 1258 case POST_INSTALL: { 1259 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1); 1260 PostInstallData data = mRunningInstalls.get(msg.arg1); 1261 mRunningInstalls.delete(msg.arg1); 1262 boolean deleteOld = false; 1263 1264 if (data != null) { 1265 InstallArgs args = data.args; 1266 PackageInstalledInfo res = data.res; 1267 1268 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 1269 res.removedInfo.sendBroadcast(false, true, false); 1270 Bundle extras = new Bundle(1); 1271 extras.putInt(Intent.EXTRA_UID, res.uid); 1272 1273 // Now that we successfully installed the package, grant runtime 1274 // permissions if requested before broadcasting the install. 1275 if ((args.installFlags 1276 & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0) { 1277 grantRequestedRuntimePermissions(res.pkg, 1278 args.user.getIdentifier()); 1279 } 1280 1281 // Determine the set of users who are adding this 1282 // package for the first time vs. those who are seeing 1283 // an update. 1284 int[] firstUsers; 1285 int[] updateUsers = new int[0]; 1286 if (res.origUsers == null || res.origUsers.length == 0) { 1287 firstUsers = res.newUsers; 1288 } else { 1289 firstUsers = new int[0]; 1290 for (int i=0; i<res.newUsers.length; i++) { 1291 int user = res.newUsers[i]; 1292 boolean isNew = true; 1293 for (int j=0; j<res.origUsers.length; j++) { 1294 if (res.origUsers[j] == user) { 1295 isNew = false; 1296 break; 1297 } 1298 } 1299 if (isNew) { 1300 int[] newFirst = new int[firstUsers.length+1]; 1301 System.arraycopy(firstUsers, 0, newFirst, 0, 1302 firstUsers.length); 1303 newFirst[firstUsers.length] = user; 1304 firstUsers = newFirst; 1305 } else { 1306 int[] newUpdate = new int[updateUsers.length+1]; 1307 System.arraycopy(updateUsers, 0, newUpdate, 0, 1308 updateUsers.length); 1309 newUpdate[updateUsers.length] = user; 1310 updateUsers = newUpdate; 1311 } 1312 } 1313 } 1314 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 1315 res.pkg.applicationInfo.packageName, 1316 extras, null, null, firstUsers); 1317 final boolean update = res.removedInfo.removedPackage != null; 1318 if (update) { 1319 extras.putBoolean(Intent.EXTRA_REPLACING, true); 1320 } 1321 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 1322 res.pkg.applicationInfo.packageName, 1323 extras, null, null, updateUsers); 1324 if (update) { 1325 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 1326 res.pkg.applicationInfo.packageName, 1327 extras, null, null, updateUsers); 1328 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, 1329 null, null, 1330 res.pkg.applicationInfo.packageName, null, updateUsers); 1331 1332 // treat asec-hosted packages like removable media on upgrade 1333 if (res.pkg.isForwardLocked() || isExternal(res.pkg)) { 1334 if (DEBUG_INSTALL) { 1335 Slog.i(TAG, "upgrading pkg " + res.pkg 1336 + " is ASEC-hosted -> AVAILABLE"); 1337 } 1338 int[] uidArray = new int[] { res.pkg.applicationInfo.uid }; 1339 ArrayList<String> pkgList = new ArrayList<String>(1); 1340 pkgList.add(res.pkg.applicationInfo.packageName); 1341 sendResourcesChangedBroadcast(true, true, 1342 pkgList,uidArray, null); 1343 } 1344 } 1345 if (res.removedInfo.args != null) { 1346 // Remove the replaced package's older resources safely now 1347 deleteOld = true; 1348 } 1349 1350 // Log current value of "unknown sources" setting 1351 EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED, 1352 getUnknownSourcesSettings()); 1353 } 1354 // Force a gc to clear up things 1355 Runtime.getRuntime().gc(); 1356 // We delete after a gc for applications on sdcard. 1357 if (deleteOld) { 1358 synchronized (mInstallLock) { 1359 res.removedInfo.args.doPostDeleteLI(true); 1360 } 1361 } 1362 if (args.observer != null) { 1363 try { 1364 Bundle extras = extrasForInstallResult(res); 1365 args.observer.onPackageInstalled(res.name, res.returnCode, 1366 res.returnMsg, extras); 1367 } catch (RemoteException e) { 1368 Slog.i(TAG, "Observer no longer exists."); 1369 } 1370 } 1371 } else { 1372 Slog.e(TAG, "Bogus post-install token " + msg.arg1); 1373 } 1374 } break; 1375 case UPDATED_MEDIA_STATUS: { 1376 if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS"); 1377 boolean reportStatus = msg.arg1 == 1; 1378 boolean doGc = msg.arg2 == 1; 1379 if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc); 1380 if (doGc) { 1381 // Force a gc to clear up stale containers. 1382 Runtime.getRuntime().gc(); 1383 } 1384 if (msg.obj != null) { 1385 @SuppressWarnings("unchecked") 1386 Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj; 1387 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers"); 1388 // Unload containers 1389 unloadAllContainers(args); 1390 } 1391 if (reportStatus) { 1392 try { 1393 if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back"); 1394 PackageHelper.getMountService().finishMediaUpdate(); 1395 } catch (RemoteException e) { 1396 Log.e(TAG, "MountService not running?"); 1397 } 1398 } 1399 } break; 1400 case WRITE_SETTINGS: { 1401 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1402 synchronized (mPackages) { 1403 removeMessages(WRITE_SETTINGS); 1404 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1405 mSettings.writeLPr(); 1406 mDirtyUsers.clear(); 1407 } 1408 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1409 } break; 1410 case WRITE_PACKAGE_RESTRICTIONS: { 1411 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1412 synchronized (mPackages) { 1413 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1414 for (int userId : mDirtyUsers) { 1415 mSettings.writePackageRestrictionsLPr(userId); 1416 } 1417 mDirtyUsers.clear(); 1418 } 1419 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1420 } break; 1421 case CHECK_PENDING_VERIFICATION: { 1422 final int verificationId = msg.arg1; 1423 final PackageVerificationState state = mPendingVerification.get(verificationId); 1424 1425 if ((state != null) && !state.timeoutExtended()) { 1426 final InstallArgs args = state.getInstallArgs(); 1427 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1428 1429 Slog.i(TAG, "Verification timed out for " + originUri); 1430 mPendingVerification.remove(verificationId); 1431 1432 int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1433 1434 if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) { 1435 Slog.i(TAG, "Continuing with installation of " + originUri); 1436 state.setVerifierResponse(Binder.getCallingUid(), 1437 PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT); 1438 broadcastPackageVerified(verificationId, originUri, 1439 PackageManager.VERIFICATION_ALLOW, 1440 state.getInstallArgs().getUser()); 1441 try { 1442 ret = args.copyApk(mContainerService, true); 1443 } catch (RemoteException e) { 1444 Slog.e(TAG, "Could not contact the ContainerService"); 1445 } 1446 } else { 1447 broadcastPackageVerified(verificationId, originUri, 1448 PackageManager.VERIFICATION_REJECT, 1449 state.getInstallArgs().getUser()); 1450 } 1451 1452 processPendingInstall(args, ret); 1453 mHandler.sendEmptyMessage(MCS_UNBIND); 1454 } 1455 break; 1456 } 1457 case PACKAGE_VERIFIED: { 1458 final int verificationId = msg.arg1; 1459 1460 final PackageVerificationState state = mPendingVerification.get(verificationId); 1461 if (state == null) { 1462 Slog.w(TAG, "Invalid verification token " + verificationId + " received"); 1463 break; 1464 } 1465 1466 final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj; 1467 1468 state.setVerifierResponse(response.callerUid, response.code); 1469 1470 if (state.isVerificationComplete()) { 1471 mPendingVerification.remove(verificationId); 1472 1473 final InstallArgs args = state.getInstallArgs(); 1474 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1475 1476 int ret; 1477 if (state.isInstallAllowed()) { 1478 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 1479 broadcastPackageVerified(verificationId, originUri, 1480 response.code, state.getInstallArgs().getUser()); 1481 try { 1482 ret = args.copyApk(mContainerService, true); 1483 } catch (RemoteException e) { 1484 Slog.e(TAG, "Could not contact the ContainerService"); 1485 } 1486 } else { 1487 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1488 } 1489 1490 processPendingInstall(args, ret); 1491 1492 mHandler.sendEmptyMessage(MCS_UNBIND); 1493 } 1494 1495 break; 1496 } 1497 case START_INTENT_FILTER_VERIFICATIONS: { 1498 int userId = msg.arg1; 1499 int verifierUid = msg.arg2; 1500 PackageParser.Package pkg = (PackageParser.Package)msg.obj; 1501 1502 verifyIntentFiltersIfNeeded(userId, verifierUid, pkg); 1503 break; 1504 } 1505 case INTENT_FILTER_VERIFIED: { 1506 final int verificationId = msg.arg1; 1507 1508 final IntentFilterVerificationState state = mIntentFilterVerificationStates.get( 1509 verificationId); 1510 if (state == null) { 1511 Slog.w(TAG, "Invalid IntentFilter verification token " 1512 + verificationId + " received"); 1513 break; 1514 } 1515 1516 final int userId = state.getUserId(); 1517 1518 Slog.d(TAG, "Processing IntentFilter verification with token:" 1519 + verificationId + " and userId:" + userId); 1520 1521 final IntentFilterVerificationResponse response = 1522 (IntentFilterVerificationResponse) msg.obj; 1523 1524 state.setVerifierResponse(response.callerUid, response.code); 1525 1526 Slog.d(TAG, "IntentFilter verification with token:" + verificationId 1527 + " and userId:" + userId 1528 + " is settings verifier response with response code:" 1529 + response.code); 1530 1531 if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) { 1532 Slog.d(TAG, "Domains failing verification: " 1533 + response.getFailedDomainsString()); 1534 } 1535 1536 if (state.isVerificationComplete()) { 1537 mIntentFilterVerifier.receiveVerificationResponse(verificationId); 1538 } else { 1539 Slog.d(TAG, "IntentFilter verification with token:" + verificationId 1540 + " was not said to be complete"); 1541 } 1542 1543 break; 1544 } 1545 } 1546 } 1547 } 1548 1549 private StorageEventListener mStorageListener = new StorageEventListener() { 1550 @Override 1551 public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) { 1552 if (vol.type == VolumeInfo.TYPE_PRIVATE) { 1553 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1554 // TODO: ensure that private directories exist for all active users 1555 // TODO: remove user data whose serial number doesn't match 1556 loadPrivatePackages(vol); 1557 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1558 unloadPrivatePackages(vol); 1559 } 1560 } 1561 1562 if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) { 1563 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1564 updateExternalMediaStatus(true, false); 1565 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1566 updateExternalMediaStatus(false, false); 1567 } 1568 } 1569 } 1570 1571 @Override 1572 public void onVolumeForgotten(String fsUuid) { 1573 // TODO: remove all packages hosted on this uuid 1574 } 1575 }; 1576 1577 private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int userId) { 1578 if (userId >= UserHandle.USER_OWNER) { 1579 grantRequestedRuntimePermissionsForUser(pkg, userId); 1580 } else if (userId == UserHandle.USER_ALL) { 1581 for (int someUserId : UserManagerService.getInstance().getUserIds()) { 1582 grantRequestedRuntimePermissionsForUser(pkg, someUserId); 1583 } 1584 } 1585 } 1586 1587 private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId) { 1588 SettingBase sb = (SettingBase) pkg.mExtras; 1589 if (sb == null) { 1590 return; 1591 } 1592 1593 PermissionsState permissionsState = sb.getPermissionsState(); 1594 1595 for (String permission : pkg.requestedPermissions) { 1596 BasePermission bp = mSettings.mPermissions.get(permission); 1597 if (bp != null && bp.isRuntime()) { 1598 permissionsState.grantRuntimePermission(bp, userId); 1599 } 1600 } 1601 } 1602 1603 Bundle extrasForInstallResult(PackageInstalledInfo res) { 1604 Bundle extras = null; 1605 switch (res.returnCode) { 1606 case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: { 1607 extras = new Bundle(); 1608 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION, 1609 res.origPermission); 1610 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE, 1611 res.origPackage); 1612 break; 1613 } 1614 case PackageManager.INSTALL_SUCCEEDED: { 1615 extras = new Bundle(); 1616 extras.putBoolean(Intent.EXTRA_REPLACING, 1617 res.removedInfo != null && res.removedInfo.removedPackage != null); 1618 break; 1619 } 1620 } 1621 return extras; 1622 } 1623 1624 void scheduleWriteSettingsLocked() { 1625 if (!mHandler.hasMessages(WRITE_SETTINGS)) { 1626 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY); 1627 } 1628 } 1629 1630 void scheduleWritePackageRestrictionsLocked(int userId) { 1631 if (!sUserManager.exists(userId)) return; 1632 mDirtyUsers.add(userId); 1633 if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) { 1634 mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY); 1635 } 1636 } 1637 1638 public static PackageManagerService main(Context context, Installer installer, 1639 boolean factoryTest, boolean onlyCore) { 1640 PackageManagerService m = new PackageManagerService(context, installer, 1641 factoryTest, onlyCore); 1642 ServiceManager.addService("package", m); 1643 return m; 1644 } 1645 1646 static String[] splitString(String str, char sep) { 1647 int count = 1; 1648 int i = 0; 1649 while ((i=str.indexOf(sep, i)) >= 0) { 1650 count++; 1651 i++; 1652 } 1653 1654 String[] res = new String[count]; 1655 i=0; 1656 count = 0; 1657 int lastI=0; 1658 while ((i=str.indexOf(sep, i)) >= 0) { 1659 res[count] = str.substring(lastI, i); 1660 count++; 1661 i++; 1662 lastI = i; 1663 } 1664 res[count] = str.substring(lastI, str.length()); 1665 return res; 1666 } 1667 1668 private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) { 1669 DisplayManager displayManager = (DisplayManager) context.getSystemService( 1670 Context.DISPLAY_SERVICE); 1671 displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics); 1672 } 1673 1674 public PackageManagerService(Context context, Installer installer, 1675 boolean factoryTest, boolean onlyCore) { 1676 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START, 1677 SystemClock.uptimeMillis()); 1678 1679 if (mSdkVersion <= 0) { 1680 Slog.w(TAG, "**** ro.build.version.sdk not set!"); 1681 } 1682 1683 mContext = context; 1684 mFactoryTest = factoryTest; 1685 mOnlyCore = onlyCore; 1686 mLazyDexOpt = "eng".equals(SystemProperties.get("ro.build.type")); 1687 mMetrics = new DisplayMetrics(); 1688 mSettings = new Settings(mPackages); 1689 mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID, 1690 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1691 mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID, 1692 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1693 mSettings.addSharedUserLPw("android.uid.log", LOG_UID, 1694 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1695 mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID, 1696 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1697 mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID, 1698 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1699 mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID, 1700 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1701 1702 // TODO: add a property to control this? 1703 long dexOptLRUThresholdInMinutes; 1704 if (mLazyDexOpt) { 1705 dexOptLRUThresholdInMinutes = 30; // only last 30 minutes of apps for eng builds. 1706 } else { 1707 dexOptLRUThresholdInMinutes = 7 * 24 * 60; // apps used in the 7 days for users. 1708 } 1709 mDexOptLRUThresholdInMills = dexOptLRUThresholdInMinutes * 60 * 1000; 1710 1711 String separateProcesses = SystemProperties.get("debug.separate_processes"); 1712 if (separateProcesses != null && separateProcesses.length() > 0) { 1713 if ("*".equals(separateProcesses)) { 1714 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES; 1715 mSeparateProcesses = null; 1716 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)"); 1717 } else { 1718 mDefParseFlags = 0; 1719 mSeparateProcesses = separateProcesses.split(","); 1720 Slog.w(TAG, "Running with debug.separate_processes: " 1721 + separateProcesses); 1722 } 1723 } else { 1724 mDefParseFlags = 0; 1725 mSeparateProcesses = null; 1726 } 1727 1728 mInstaller = installer; 1729 mPackageDexOptimizer = new PackageDexOptimizer(this); 1730 mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper()); 1731 1732 getDefaultDisplayMetrics(context, mMetrics); 1733 1734 SystemConfig systemConfig = SystemConfig.getInstance(); 1735 mGlobalGids = systemConfig.getGlobalGids(); 1736 mSystemPermissions = systemConfig.getSystemPermissions(); 1737 mAvailableFeatures = systemConfig.getAvailableFeatures(); 1738 1739 synchronized (mInstallLock) { 1740 // writer 1741 synchronized (mPackages) { 1742 mHandlerThread = new ServiceThread(TAG, 1743 Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/); 1744 mHandlerThread.start(); 1745 mHandler = new PackageHandler(mHandlerThread.getLooper()); 1746 Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT); 1747 1748 File dataDir = Environment.getDataDirectory(); 1749 mAppDataDir = new File(dataDir, "data"); 1750 mAppInstallDir = new File(dataDir, "app"); 1751 mAppLib32InstallDir = new File(dataDir, "app-lib"); 1752 mAsecInternalPath = new File(dataDir, "app-asec").getPath(); 1753 mUserAppDataDir = new File(dataDir, "user"); 1754 mDrmAppPrivateInstallDir = new File(dataDir, "app-private"); 1755 1756 sUserManager = new UserManagerService(context, this, 1757 mInstallLock, mPackages); 1758 1759 // Propagate permission configuration in to package manager. 1760 ArrayMap<String, SystemConfig.PermissionEntry> permConfig 1761 = systemConfig.getPermissions(); 1762 for (int i=0; i<permConfig.size(); i++) { 1763 SystemConfig.PermissionEntry perm = permConfig.valueAt(i); 1764 BasePermission bp = mSettings.mPermissions.get(perm.name); 1765 if (bp == null) { 1766 bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN); 1767 mSettings.mPermissions.put(perm.name, bp); 1768 } 1769 if (perm.gids != null) { 1770 bp.setGids(perm.gids, perm.perUser); 1771 } 1772 } 1773 1774 ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries(); 1775 for (int i=0; i<libConfig.size(); i++) { 1776 mSharedLibraries.put(libConfig.keyAt(i), 1777 new SharedLibraryEntry(libConfig.valueAt(i), null)); 1778 } 1779 1780 mFoundPolicyFile = SELinuxMMAC.readInstallPolicy(); 1781 1782 mRestoredSettings = mSettings.readLPw(this, sUserManager.getUsers(false), 1783 mSdkVersion, mOnlyCore); 1784 1785 String customResolverActivity = Resources.getSystem().getString( 1786 R.string.config_customResolverActivity); 1787 if (TextUtils.isEmpty(customResolverActivity)) { 1788 customResolverActivity = null; 1789 } else { 1790 mCustomResolverComponentName = ComponentName.unflattenFromString( 1791 customResolverActivity); 1792 } 1793 1794 long startTime = SystemClock.uptimeMillis(); 1795 1796 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START, 1797 startTime); 1798 1799 // Set flag to monitor and not change apk file paths when 1800 // scanning install directories. 1801 final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING; 1802 1803 final ArraySet<String> alreadyDexOpted = new ArraySet<String>(); 1804 1805 /** 1806 * Add everything in the in the boot class path to the 1807 * list of process files because dexopt will have been run 1808 * if necessary during zygote startup. 1809 */ 1810 final String bootClassPath = System.getenv("BOOTCLASSPATH"); 1811 final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH"); 1812 1813 if (bootClassPath != null) { 1814 String[] bootClassPathElements = splitString(bootClassPath, ':'); 1815 for (String element : bootClassPathElements) { 1816 alreadyDexOpted.add(element); 1817 } 1818 } else { 1819 Slog.w(TAG, "No BOOTCLASSPATH found!"); 1820 } 1821 1822 if (systemServerClassPath != null) { 1823 String[] systemServerClassPathElements = splitString(systemServerClassPath, ':'); 1824 for (String element : systemServerClassPathElements) { 1825 alreadyDexOpted.add(element); 1826 } 1827 } else { 1828 Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!"); 1829 } 1830 1831 final List<String> allInstructionSets = InstructionSets.getAllInstructionSets(); 1832 final String[] dexCodeInstructionSets = 1833 getDexCodeInstructionSets( 1834 allInstructionSets.toArray(new String[allInstructionSets.size()])); 1835 1836 /** 1837 * Ensure all external libraries have had dexopt run on them. 1838 */ 1839 if (mSharedLibraries.size() > 0) { 1840 // NOTE: For now, we're compiling these system "shared libraries" 1841 // (and framework jars) into all available architectures. It's possible 1842 // to compile them only when we come across an app that uses them (there's 1843 // already logic for that in scanPackageLI) but that adds some complexity. 1844 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 1845 for (SharedLibraryEntry libEntry : mSharedLibraries.values()) { 1846 final String lib = libEntry.path; 1847 if (lib == null) { 1848 continue; 1849 } 1850 1851 try { 1852 int dexoptNeeded = DexFile.getDexOptNeeded(lib, null, dexCodeInstructionSet, false); 1853 if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) { 1854 alreadyDexOpted.add(lib); 1855 mInstaller.dexopt(lib, Process.SYSTEM_UID, true, dexCodeInstructionSet, dexoptNeeded); 1856 } 1857 } catch (FileNotFoundException e) { 1858 Slog.w(TAG, "Library not found: " + lib); 1859 } catch (IOException e) { 1860 Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? " 1861 + e.getMessage()); 1862 } 1863 } 1864 } 1865 } 1866 1867 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 1868 1869 // Gross hack for now: we know this file doesn't contain any 1870 // code, so don't dexopt it to avoid the resulting log spew. 1871 alreadyDexOpted.add(frameworkDir.getPath() + "/framework-res.apk"); 1872 1873 // Gross hack for now: we know this file is only part of 1874 // the boot class path for art, so don't dexopt it to 1875 // avoid the resulting log spew. 1876 alreadyDexOpted.add(frameworkDir.getPath() + "/core-libart.jar"); 1877 1878 /** 1879 * And there are a number of commands implemented in Java, which 1880 * we currently need to do the dexopt on so that they can be 1881 * run from a non-root shell. 1882 */ 1883 String[] frameworkFiles = frameworkDir.list(); 1884 if (frameworkFiles != null) { 1885 // TODO: We could compile these only for the most preferred ABI. We should 1886 // first double check that the dex files for these commands are not referenced 1887 // by other system apps. 1888 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 1889 for (int i=0; i<frameworkFiles.length; i++) { 1890 File libPath = new File(frameworkDir, frameworkFiles[i]); 1891 String path = libPath.getPath(); 1892 // Skip the file if we already did it. 1893 if (alreadyDexOpted.contains(path)) { 1894 continue; 1895 } 1896 // Skip the file if it is not a type we want to dexopt. 1897 if (!path.endsWith(".apk") && !path.endsWith(".jar")) { 1898 continue; 1899 } 1900 try { 1901 int dexoptNeeded = DexFile.getDexOptNeeded(path, null, dexCodeInstructionSet, false); 1902 if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) { 1903 mInstaller.dexopt(path, Process.SYSTEM_UID, true, dexCodeInstructionSet, dexoptNeeded); 1904 } 1905 } catch (FileNotFoundException e) { 1906 Slog.w(TAG, "Jar not found: " + path); 1907 } catch (IOException e) { 1908 Slog.w(TAG, "Exception reading jar: " + path, e); 1909 } 1910 } 1911 } 1912 } 1913 1914 // Collect vendor overlay packages. 1915 // (Do this before scanning any apps.) 1916 // For security and version matching reason, only consider 1917 // overlay packages if they reside in VENDOR_OVERLAY_DIR. 1918 File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR); 1919 scanDirLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM 1920 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags | SCAN_TRUSTED_OVERLAY, 0); 1921 1922 // Find base frameworks (resource packages without code). 1923 scanDirLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM 1924 | PackageParser.PARSE_IS_SYSTEM_DIR 1925 | PackageParser.PARSE_IS_PRIVILEGED, 1926 scanFlags | SCAN_NO_DEX, 0); 1927 1928 // Collected privileged system packages. 1929 final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app"); 1930 scanDirLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM 1931 | PackageParser.PARSE_IS_SYSTEM_DIR 1932 | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0); 1933 1934 // Collect ordinary system packages. 1935 final File systemAppDir = new File(Environment.getRootDirectory(), "app"); 1936 scanDirLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM 1937 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 1938 1939 // Collect all vendor packages. 1940 File vendorAppDir = new File("/vendor/app"); 1941 try { 1942 vendorAppDir = vendorAppDir.getCanonicalFile(); 1943 } catch (IOException e) { 1944 // failed to look up canonical path, continue with original one 1945 } 1946 scanDirLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM 1947 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 1948 1949 // Collect all OEM packages. 1950 final File oemAppDir = new File(Environment.getOemDirectory(), "app"); 1951 scanDirLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM 1952 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 1953 1954 if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands"); 1955 mInstaller.moveFiles(); 1956 1957 // Prune any system packages that no longer exist. 1958 final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>(); 1959 final ArrayMap<String, File> expectingBetter = new ArrayMap<>(); 1960 if (!mOnlyCore) { 1961 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 1962 while (psit.hasNext()) { 1963 PackageSetting ps = psit.next(); 1964 1965 /* 1966 * If this is not a system app, it can't be a 1967 * disable system app. 1968 */ 1969 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) { 1970 continue; 1971 } 1972 1973 /* 1974 * If the package is scanned, it's not erased. 1975 */ 1976 final PackageParser.Package scannedPkg = mPackages.get(ps.name); 1977 if (scannedPkg != null) { 1978 /* 1979 * If the system app is both scanned and in the 1980 * disabled packages list, then it must have been 1981 * added via OTA. Remove it from the currently 1982 * scanned package so the previously user-installed 1983 * application can be scanned. 1984 */ 1985 if (mSettings.isDisabledSystemPackageLPr(ps.name)) { 1986 logCriticalInfo(Log.WARN, "Expecting better updated system app for " 1987 + ps.name + "; removing system app. Last known codePath=" 1988 + ps.codePathString + ", installStatus=" + ps.installStatus 1989 + ", versionCode=" + ps.versionCode + "; scanned versionCode=" 1990 + scannedPkg.mVersionCode); 1991 removePackageLI(ps, true); 1992 expectingBetter.put(ps.name, ps.codePath); 1993 } 1994 1995 continue; 1996 } 1997 1998 if (!mSettings.isDisabledSystemPackageLPr(ps.name)) { 1999 psit.remove(); 2000 logCriticalInfo(Log.WARN, "System package " + ps.name 2001 + " no longer exists; wiping its data"); 2002 removeDataDirsLI(null, ps.name); 2003 } else { 2004 final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name); 2005 if (disabledPs.codePath == null || !disabledPs.codePath.exists()) { 2006 possiblyDeletedUpdatedSystemApps.add(ps.name); 2007 } 2008 } 2009 } 2010 } 2011 2012 //look for any incomplete package installations 2013 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr(); 2014 //clean up list 2015 for(int i = 0; i < deletePkgsList.size(); i++) { 2016 //clean up here 2017 cleanupInstallFailedPackage(deletePkgsList.get(i)); 2018 } 2019 //delete tmp files 2020 deleteTempPackageFiles(); 2021 2022 // Remove any shared userIDs that have no associated packages 2023 mSettings.pruneSharedUsersLPw(); 2024 2025 if (!mOnlyCore) { 2026 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START, 2027 SystemClock.uptimeMillis()); 2028 scanDirLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0); 2029 2030 scanDirLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK, 2031 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2032 2033 /** 2034 * Remove disable package settings for any updated system 2035 * apps that were removed via an OTA. If they're not a 2036 * previously-updated app, remove them completely. 2037 * Otherwise, just revoke their system-level permissions. 2038 */ 2039 for (String deletedAppName : possiblyDeletedUpdatedSystemApps) { 2040 PackageParser.Package deletedPkg = mPackages.get(deletedAppName); 2041 mSettings.removeDisabledSystemPackageLPw(deletedAppName); 2042 2043 String msg; 2044 if (deletedPkg == null) { 2045 msg = "Updated system package " + deletedAppName 2046 + " no longer exists; wiping its data"; 2047 removeDataDirsLI(null, deletedAppName); 2048 } else { 2049 msg = "Updated system app + " + deletedAppName 2050 + " no longer present; removing system privileges for " 2051 + deletedAppName; 2052 2053 deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM; 2054 2055 PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName); 2056 deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM; 2057 } 2058 logCriticalInfo(Log.WARN, msg); 2059 } 2060 2061 /** 2062 * Make sure all system apps that we expected to appear on 2063 * the userdata partition actually showed up. If they never 2064 * appeared, crawl back and revive the system version. 2065 */ 2066 for (int i = 0; i < expectingBetter.size(); i++) { 2067 final String packageName = expectingBetter.keyAt(i); 2068 if (!mPackages.containsKey(packageName)) { 2069 final File scanFile = expectingBetter.valueAt(i); 2070 2071 logCriticalInfo(Log.WARN, "Expected better " + packageName 2072 + " but never showed up; reverting to system"); 2073 2074 final int reparseFlags; 2075 if (FileUtils.contains(privilegedAppDir, scanFile)) { 2076 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2077 | PackageParser.PARSE_IS_SYSTEM_DIR 2078 | PackageParser.PARSE_IS_PRIVILEGED; 2079 } else if (FileUtils.contains(systemAppDir, scanFile)) { 2080 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2081 | PackageParser.PARSE_IS_SYSTEM_DIR; 2082 } else if (FileUtils.contains(vendorAppDir, scanFile)) { 2083 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2084 | PackageParser.PARSE_IS_SYSTEM_DIR; 2085 } else if (FileUtils.contains(oemAppDir, scanFile)) { 2086 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2087 | PackageParser.PARSE_IS_SYSTEM_DIR; 2088 } else { 2089 Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile); 2090 continue; 2091 } 2092 2093 mSettings.enableSystemPackageLPw(packageName); 2094 2095 try { 2096 scanPackageLI(scanFile, reparseFlags, scanFlags, 0, null); 2097 } catch (PackageManagerException e) { 2098 Slog.e(TAG, "Failed to parse original system package: " 2099 + e.getMessage()); 2100 } 2101 } 2102 } 2103 } 2104 2105 // Now that we know all of the shared libraries, update all clients to have 2106 // the correct library paths. 2107 updateAllSharedLibrariesLPw(); 2108 2109 for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) { 2110 // NOTE: We ignore potential failures here during a system scan (like 2111 // the rest of the commands above) because there's precious little we 2112 // can do about it. A settings error is reported, though. 2113 adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */, 2114 false /* force dexopt */, false /* defer dexopt */); 2115 } 2116 2117 // Now that we know all the packages we are keeping, 2118 // read and update their last usage times. 2119 mPackageUsage.readLP(); 2120 2121 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END, 2122 SystemClock.uptimeMillis()); 2123 Slog.i(TAG, "Time to scan packages: " 2124 + ((SystemClock.uptimeMillis()-startTime)/1000f) 2125 + " seconds"); 2126 2127 // If the platform SDK has changed since the last time we booted, 2128 // we need to re-grant app permission to catch any new ones that 2129 // appear. This is really a hack, and means that apps can in some 2130 // cases get permissions that the user didn't initially explicitly 2131 // allow... it would be nice to have some better way to handle 2132 // this situation. 2133 final boolean regrantPermissions = mSettings.mInternalSdkPlatform 2134 != mSdkVersion; 2135 if (regrantPermissions) Slog.i(TAG, "Platform changed from " 2136 + mSettings.mInternalSdkPlatform + " to " + mSdkVersion 2137 + "; regranting permissions for internal storage"); 2138 mSettings.mInternalSdkPlatform = mSdkVersion; 2139 2140 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 2141 | (regrantPermissions 2142 ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL) 2143 : 0)); 2144 2145 // If this is the first boot, and it is a normal boot, then 2146 // we need to initialize the default preferred apps. 2147 if (!mRestoredSettings && !onlyCore) { 2148 mSettings.readDefaultPreferredAppsLPw(this, 0); 2149 } 2150 2151 // If this is first boot after an OTA, and a normal boot, then 2152 // we need to clear code cache directories. 2153 mIsUpgrade = !Build.FINGERPRINT.equals(mSettings.mFingerprint); 2154 if (mIsUpgrade && !onlyCore) { 2155 Slog.i(TAG, "Build fingerprint changed; clearing code caches"); 2156 for (int i = 0; i < mSettings.mPackages.size(); i++) { 2157 final PackageSetting ps = mSettings.mPackages.valueAt(i); 2158 deleteCodeCacheDirsLI(ps.volumeUuid, ps.name); 2159 } 2160 mSettings.mFingerprint = Build.FINGERPRINT; 2161 } 2162 2163 primeDomainVerificationsLPw(false); 2164 checkDefaultBrowser(); 2165 2166 // All the changes are done during package scanning. 2167 mSettings.updateInternalDatabaseVersion(); 2168 2169 // can downgrade to reader 2170 mSettings.writeLPr(); 2171 2172 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY, 2173 SystemClock.uptimeMillis()); 2174 2175 mRequiredVerifierPackage = getRequiredVerifierLPr(); 2176 2177 mInstallerService = new PackageInstallerService(context, this); 2178 2179 mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr(); 2180 mIntentFilterVerifier = new IntentVerifierProxy(mContext, 2181 mIntentFilterVerifierComponent); 2182 2183 } // synchronized (mPackages) 2184 } // synchronized (mInstallLock) 2185 2186 // Now after opening every single application zip, make sure they 2187 // are all flushed. Not really needed, but keeps things nice and 2188 // tidy. 2189 Runtime.getRuntime().gc(); 2190 } 2191 2192 @Override 2193 public boolean isFirstBoot() { 2194 return !mRestoredSettings; 2195 } 2196 2197 @Override 2198 public boolean isOnlyCoreApps() { 2199 return mOnlyCore; 2200 } 2201 2202 @Override 2203 public boolean isUpgrade() { 2204 return mIsUpgrade; 2205 } 2206 2207 private String getRequiredVerifierLPr() { 2208 final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 2209 final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE, 2210 PackageManager.GET_DISABLED_COMPONENTS, 0 /* TODO: Which userId? */); 2211 2212 String requiredVerifier = null; 2213 2214 final int N = receivers.size(); 2215 for (int i = 0; i < N; i++) { 2216 final ResolveInfo info = receivers.get(i); 2217 2218 if (info.activityInfo == null) { 2219 continue; 2220 } 2221 2222 final String packageName = info.activityInfo.packageName; 2223 2224 if (checkPermission(android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 2225 packageName, UserHandle.USER_OWNER) != PackageManager.PERMISSION_GRANTED) { 2226 continue; 2227 } 2228 2229 if (requiredVerifier != null) { 2230 throw new RuntimeException("There can be only one required verifier"); 2231 } 2232 2233 requiredVerifier = packageName; 2234 } 2235 2236 return requiredVerifier; 2237 } 2238 2239 private ComponentName getIntentFilterVerifierComponentNameLPr() { 2240 final Intent verification = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 2241 final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE, 2242 PackageManager.GET_DISABLED_COMPONENTS, 0 /* userId */); 2243 2244 ComponentName verifierComponentName = null; 2245 2246 int priority = -1000; 2247 final int N = receivers.size(); 2248 for (int i = 0; i < N; i++) { 2249 final ResolveInfo info = receivers.get(i); 2250 2251 if (info.activityInfo == null) { 2252 continue; 2253 } 2254 2255 final String packageName = info.activityInfo.packageName; 2256 2257 final PackageSetting ps = mSettings.mPackages.get(packageName); 2258 if (ps == null) { 2259 continue; 2260 } 2261 2262 if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 2263 packageName, UserHandle.USER_OWNER) != PackageManager.PERMISSION_GRANTED) { 2264 continue; 2265 } 2266 2267 // Select the IntentFilterVerifier with the highest priority 2268 if (priority < info.priority) { 2269 priority = info.priority; 2270 verifierComponentName = new ComponentName(packageName, info.activityInfo.name); 2271 Slog.d(TAG, "Selecting IntentFilterVerifier: " + verifierComponentName + 2272 " with priority: " + info.priority); 2273 } 2274 } 2275 2276 return verifierComponentName; 2277 } 2278 2279 private void primeDomainVerificationsLPw(boolean logging) { 2280 Slog.d(TAG, "Start priming domain verifications"); 2281 boolean updated = false; 2282 ArraySet<String> allHostsSet = new ArraySet<>(); 2283 for (PackageParser.Package pkg : mPackages.values()) { 2284 final String packageName = pkg.packageName; 2285 if (!hasDomainURLs(pkg)) { 2286 if (logging) { 2287 Slog.d(TAG, "No priming domain verifications for " + 2288 "package with no domain URLs: " + packageName); 2289 } 2290 continue; 2291 } 2292 if (!pkg.isSystemApp()) { 2293 if (logging) { 2294 Slog.d(TAG, "No priming domain verifications for a non system package : " + 2295 packageName); 2296 } 2297 continue; 2298 } 2299 for (PackageParser.Activity a : pkg.activities) { 2300 for (ActivityIntentInfo filter : a.intents) { 2301 if (hasValidDomains(filter, false)) { 2302 allHostsSet.addAll(filter.getHostsList()); 2303 } 2304 } 2305 } 2306 if (allHostsSet.size() == 0) { 2307 allHostsSet.add("*"); 2308 } 2309 ArrayList<String> allHostsList = new ArrayList<>(allHostsSet); 2310 IntentFilterVerificationInfo ivi = 2311 mSettings.createIntentFilterVerificationIfNeededLPw(packageName, allHostsList); 2312 if (ivi != null) { 2313 // We will always log this 2314 Slog.d(TAG, "Priming domain verifications for package: " + packageName + 2315 " with hosts:" + ivi.getDomainsString()); 2316 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS); 2317 updated = true; 2318 } 2319 else { 2320 if (logging) { 2321 Slog.d(TAG, "No priming domain verifications for package: " + packageName); 2322 } 2323 } 2324 allHostsSet.clear(); 2325 } 2326 if (updated) { 2327 if (logging) { 2328 Slog.d(TAG, "Will need to write primed domain verifications"); 2329 } 2330 } 2331 Slog.d(TAG, "End priming domain verifications"); 2332 } 2333 2334 private void checkDefaultBrowser() { 2335 final int myUserId = UserHandle.myUserId(); 2336 final String packageName = getDefaultBrowserPackageName(myUserId); 2337 PackageInfo info = getPackageInfo(packageName, 0, myUserId); 2338 if (info == null) { 2339 Slog.w(TAG, "Clearing default Browser as its package is no more installed: " + 2340 packageName); 2341 setDefaultBrowserPackageName(null, myUserId); 2342 } 2343 } 2344 2345 @Override 2346 public boolean onTransact(int code, Parcel data, Parcel reply, int flags) 2347 throws RemoteException { 2348 try { 2349 return super.onTransact(code, data, reply, flags); 2350 } catch (RuntimeException e) { 2351 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) { 2352 Slog.wtf(TAG, "Package Manager Crash", e); 2353 } 2354 throw e; 2355 } 2356 } 2357 2358 void cleanupInstallFailedPackage(PackageSetting ps) { 2359 logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + ps.name); 2360 2361 removeDataDirsLI(ps.volumeUuid, ps.name); 2362 if (ps.codePath != null) { 2363 if (ps.codePath.isDirectory()) { 2364 mInstaller.rmPackageDir(ps.codePath.getAbsolutePath()); 2365 } else { 2366 ps.codePath.delete(); 2367 } 2368 } 2369 if (ps.resourcePath != null && !ps.resourcePath.equals(ps.codePath)) { 2370 if (ps.resourcePath.isDirectory()) { 2371 FileUtils.deleteContents(ps.resourcePath); 2372 } 2373 ps.resourcePath.delete(); 2374 } 2375 mSettings.removePackageLPw(ps.name); 2376 } 2377 2378 static int[] appendInts(int[] cur, int[] add) { 2379 if (add == null) return cur; 2380 if (cur == null) return add; 2381 final int N = add.length; 2382 for (int i=0; i<N; i++) { 2383 cur = appendInt(cur, add[i]); 2384 } 2385 return cur; 2386 } 2387 2388 PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) { 2389 if (!sUserManager.exists(userId)) return null; 2390 final PackageSetting ps = (PackageSetting) p.mExtras; 2391 if (ps == null) { 2392 return null; 2393 } 2394 2395 final PermissionsState permissionsState = ps.getPermissionsState(); 2396 2397 final int[] gids = permissionsState.computeGids(userId); 2398 final Set<String> permissions = permissionsState.getPermissions(userId); 2399 final PackageUserState state = ps.readUserState(userId); 2400 2401 return PackageParser.generatePackageInfo(p, gids, flags, 2402 ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId); 2403 } 2404 2405 @Override 2406 public boolean isPackageFrozen(String packageName) { 2407 synchronized (mPackages) { 2408 final PackageSetting ps = mSettings.mPackages.get(packageName); 2409 if (ps != null) { 2410 return ps.frozen; 2411 } 2412 } 2413 Slog.w(TAG, "Package " + packageName + " is missing; assuming frozen"); 2414 return true; 2415 } 2416 2417 @Override 2418 public boolean isPackageAvailable(String packageName, int userId) { 2419 if (!sUserManager.exists(userId)) return false; 2420 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "is package available"); 2421 synchronized (mPackages) { 2422 PackageParser.Package p = mPackages.get(packageName); 2423 if (p != null) { 2424 final PackageSetting ps = (PackageSetting) p.mExtras; 2425 if (ps != null) { 2426 final PackageUserState state = ps.readUserState(userId); 2427 if (state != null) { 2428 return PackageParser.isAvailable(state); 2429 } 2430 } 2431 } 2432 } 2433 return false; 2434 } 2435 2436 @Override 2437 public PackageInfo getPackageInfo(String packageName, int flags, int userId) { 2438 if (!sUserManager.exists(userId)) return null; 2439 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package info"); 2440 // reader 2441 synchronized (mPackages) { 2442 PackageParser.Package p = mPackages.get(packageName); 2443 if (DEBUG_PACKAGE_INFO) 2444 Log.v(TAG, "getPackageInfo " + packageName + ": " + p); 2445 if (p != null) { 2446 return generatePackageInfo(p, flags, userId); 2447 } 2448 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 2449 return generatePackageInfoFromSettingsLPw(packageName, flags, userId); 2450 } 2451 } 2452 return null; 2453 } 2454 2455 @Override 2456 public String[] currentToCanonicalPackageNames(String[] names) { 2457 String[] out = new String[names.length]; 2458 // reader 2459 synchronized (mPackages) { 2460 for (int i=names.length-1; i>=0; i--) { 2461 PackageSetting ps = mSettings.mPackages.get(names[i]); 2462 out[i] = ps != null && ps.realName != null ? ps.realName : names[i]; 2463 } 2464 } 2465 return out; 2466 } 2467 2468 @Override 2469 public String[] canonicalToCurrentPackageNames(String[] names) { 2470 String[] out = new String[names.length]; 2471 // reader 2472 synchronized (mPackages) { 2473 for (int i=names.length-1; i>=0; i--) { 2474 String cur = mSettings.mRenamedPackages.get(names[i]); 2475 out[i] = cur != null ? cur : names[i]; 2476 } 2477 } 2478 return out; 2479 } 2480 2481 @Override 2482 public int getPackageUid(String packageName, int userId) { 2483 if (!sUserManager.exists(userId)) return -1; 2484 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package uid"); 2485 2486 // reader 2487 synchronized (mPackages) { 2488 PackageParser.Package p = mPackages.get(packageName); 2489 if(p != null) { 2490 return UserHandle.getUid(userId, p.applicationInfo.uid); 2491 } 2492 PackageSetting ps = mSettings.mPackages.get(packageName); 2493 if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) { 2494 return -1; 2495 } 2496 p = ps.pkg; 2497 return p != null ? UserHandle.getUid(userId, p.applicationInfo.uid) : -1; 2498 } 2499 } 2500 2501 @Override 2502 public int[] getPackageGids(String packageName, int userId) throws RemoteException { 2503 if (!sUserManager.exists(userId)) { 2504 return null; 2505 } 2506 2507 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, 2508 "getPackageGids"); 2509 2510 // reader 2511 synchronized (mPackages) { 2512 PackageParser.Package p = mPackages.get(packageName); 2513 if (DEBUG_PACKAGE_INFO) { 2514 Log.v(TAG, "getPackageGids" + packageName + ": " + p); 2515 } 2516 if (p != null) { 2517 PackageSetting ps = (PackageSetting) p.mExtras; 2518 return ps.getPermissionsState().computeGids(userId); 2519 } 2520 } 2521 2522 return null; 2523 } 2524 2525 static PermissionInfo generatePermissionInfo( 2526 BasePermission bp, int flags) { 2527 if (bp.perm != null) { 2528 return PackageParser.generatePermissionInfo(bp.perm, flags); 2529 } 2530 PermissionInfo pi = new PermissionInfo(); 2531 pi.name = bp.name; 2532 pi.packageName = bp.sourcePackage; 2533 pi.nonLocalizedLabel = bp.name; 2534 pi.protectionLevel = bp.protectionLevel; 2535 return pi; 2536 } 2537 2538 @Override 2539 public PermissionInfo getPermissionInfo(String name, int flags) { 2540 // reader 2541 synchronized (mPackages) { 2542 final BasePermission p = mSettings.mPermissions.get(name); 2543 if (p != null) { 2544 return generatePermissionInfo(p, flags); 2545 } 2546 return null; 2547 } 2548 } 2549 2550 @Override 2551 public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) { 2552 // reader 2553 synchronized (mPackages) { 2554 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10); 2555 for (BasePermission p : mSettings.mPermissions.values()) { 2556 if (group == null) { 2557 if (p.perm == null || p.perm.info.group == null) { 2558 out.add(generatePermissionInfo(p, flags)); 2559 } 2560 } else { 2561 if (p.perm != null && group.equals(p.perm.info.group)) { 2562 out.add(PackageParser.generatePermissionInfo(p.perm, flags)); 2563 } 2564 } 2565 } 2566 2567 if (out.size() > 0) { 2568 return out; 2569 } 2570 return mPermissionGroups.containsKey(group) ? out : null; 2571 } 2572 } 2573 2574 @Override 2575 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) { 2576 // reader 2577 synchronized (mPackages) { 2578 return PackageParser.generatePermissionGroupInfo( 2579 mPermissionGroups.get(name), flags); 2580 } 2581 } 2582 2583 @Override 2584 public List<PermissionGroupInfo> getAllPermissionGroups(int flags) { 2585 // reader 2586 synchronized (mPackages) { 2587 final int N = mPermissionGroups.size(); 2588 ArrayList<PermissionGroupInfo> out 2589 = new ArrayList<PermissionGroupInfo>(N); 2590 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) { 2591 out.add(PackageParser.generatePermissionGroupInfo(pg, flags)); 2592 } 2593 return out; 2594 } 2595 } 2596 2597 private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags, 2598 int userId) { 2599 if (!sUserManager.exists(userId)) return null; 2600 PackageSetting ps = mSettings.mPackages.get(packageName); 2601 if (ps != null) { 2602 if (ps.pkg == null) { 2603 PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName, 2604 flags, userId); 2605 if (pInfo != null) { 2606 return pInfo.applicationInfo; 2607 } 2608 return null; 2609 } 2610 return PackageParser.generateApplicationInfo(ps.pkg, flags, 2611 ps.readUserState(userId), userId); 2612 } 2613 return null; 2614 } 2615 2616 private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags, 2617 int userId) { 2618 if (!sUserManager.exists(userId)) return null; 2619 PackageSetting ps = mSettings.mPackages.get(packageName); 2620 if (ps != null) { 2621 PackageParser.Package pkg = ps.pkg; 2622 if (pkg == null) { 2623 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) == 0) { 2624 return null; 2625 } 2626 // Only data remains, so we aren't worried about code paths 2627 pkg = new PackageParser.Package(packageName); 2628 pkg.applicationInfo.packageName = packageName; 2629 pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY; 2630 pkg.applicationInfo.privateFlags = ps.pkgPrivateFlags; 2631 pkg.applicationInfo.dataDir = PackageManager.getDataDirForUser(ps.volumeUuid, 2632 packageName, userId).getAbsolutePath(); 2633 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 2634 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 2635 } 2636 return generatePackageInfo(pkg, flags, userId); 2637 } 2638 return null; 2639 } 2640 2641 @Override 2642 public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) { 2643 if (!sUserManager.exists(userId)) return null; 2644 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get application info"); 2645 // writer 2646 synchronized (mPackages) { 2647 PackageParser.Package p = mPackages.get(packageName); 2648 if (DEBUG_PACKAGE_INFO) Log.v( 2649 TAG, "getApplicationInfo " + packageName 2650 + ": " + p); 2651 if (p != null) { 2652 PackageSetting ps = mSettings.mPackages.get(packageName); 2653 if (ps == null) return null; 2654 // Note: isEnabledLP() does not apply here - always return info 2655 return PackageParser.generateApplicationInfo( 2656 p, flags, ps.readUserState(userId), userId); 2657 } 2658 if ("android".equals(packageName)||"system".equals(packageName)) { 2659 return mAndroidApplication; 2660 } 2661 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 2662 return generateApplicationInfoFromSettingsLPw(packageName, flags, userId); 2663 } 2664 } 2665 return null; 2666 } 2667 2668 @Override 2669 public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize, 2670 final IPackageDataObserver observer) { 2671 mContext.enforceCallingOrSelfPermission( 2672 android.Manifest.permission.CLEAR_APP_CACHE, null); 2673 // Queue up an async operation since clearing cache may take a little while. 2674 mHandler.post(new Runnable() { 2675 public void run() { 2676 mHandler.removeCallbacks(this); 2677 int retCode = -1; 2678 synchronized (mInstallLock) { 2679 retCode = mInstaller.freeCache(volumeUuid, freeStorageSize); 2680 if (retCode < 0) { 2681 Slog.w(TAG, "Couldn't clear application caches"); 2682 } 2683 } 2684 if (observer != null) { 2685 try { 2686 observer.onRemoveCompleted(null, (retCode >= 0)); 2687 } catch (RemoteException e) { 2688 Slog.w(TAG, "RemoveException when invoking call back"); 2689 } 2690 } 2691 } 2692 }); 2693 } 2694 2695 @Override 2696 public void freeStorage(final String volumeUuid, final long freeStorageSize, 2697 final IntentSender pi) { 2698 mContext.enforceCallingOrSelfPermission( 2699 android.Manifest.permission.CLEAR_APP_CACHE, null); 2700 // Queue up an async operation since clearing cache may take a little while. 2701 mHandler.post(new Runnable() { 2702 public void run() { 2703 mHandler.removeCallbacks(this); 2704 int retCode = -1; 2705 synchronized (mInstallLock) { 2706 retCode = mInstaller.freeCache(volumeUuid, freeStorageSize); 2707 if (retCode < 0) { 2708 Slog.w(TAG, "Couldn't clear application caches"); 2709 } 2710 } 2711 if(pi != null) { 2712 try { 2713 // Callback via pending intent 2714 int code = (retCode >= 0) ? 1 : 0; 2715 pi.sendIntent(null, code, null, 2716 null, null); 2717 } catch (SendIntentException e1) { 2718 Slog.i(TAG, "Failed to send pending intent"); 2719 } 2720 } 2721 } 2722 }); 2723 } 2724 2725 void freeStorage(String volumeUuid, long freeStorageSize) throws IOException { 2726 synchronized (mInstallLock) { 2727 if (mInstaller.freeCache(volumeUuid, freeStorageSize) < 0) { 2728 throw new IOException("Failed to free enough space"); 2729 } 2730 } 2731 } 2732 2733 @Override 2734 public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) { 2735 if (!sUserManager.exists(userId)) return null; 2736 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get activity info"); 2737 synchronized (mPackages) { 2738 PackageParser.Activity a = mActivities.mActivities.get(component); 2739 2740 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a); 2741 if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) { 2742 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2743 if (ps == null) return null; 2744 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 2745 userId); 2746 } 2747 if (mResolveComponentName.equals(component)) { 2748 return PackageParser.generateActivityInfo(mResolveActivity, flags, 2749 new PackageUserState(), userId); 2750 } 2751 } 2752 return null; 2753 } 2754 2755 @Override 2756 public boolean activitySupportsIntent(ComponentName component, Intent intent, 2757 String resolvedType) { 2758 synchronized (mPackages) { 2759 PackageParser.Activity a = mActivities.mActivities.get(component); 2760 if (a == null) { 2761 return false; 2762 } 2763 for (int i=0; i<a.intents.size(); i++) { 2764 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(), 2765 intent.getData(), intent.getCategories(), TAG) >= 0) { 2766 return true; 2767 } 2768 } 2769 return false; 2770 } 2771 } 2772 2773 @Override 2774 public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) { 2775 if (!sUserManager.exists(userId)) return null; 2776 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get receiver info"); 2777 synchronized (mPackages) { 2778 PackageParser.Activity a = mReceivers.mActivities.get(component); 2779 if (DEBUG_PACKAGE_INFO) Log.v( 2780 TAG, "getReceiverInfo " + component + ": " + a); 2781 if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) { 2782 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2783 if (ps == null) return null; 2784 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 2785 userId); 2786 } 2787 } 2788 return null; 2789 } 2790 2791 @Override 2792 public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) { 2793 if (!sUserManager.exists(userId)) return null; 2794 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get service info"); 2795 synchronized (mPackages) { 2796 PackageParser.Service s = mServices.mServices.get(component); 2797 if (DEBUG_PACKAGE_INFO) Log.v( 2798 TAG, "getServiceInfo " + component + ": " + s); 2799 if (s != null && mSettings.isEnabledLPr(s.info, flags, userId)) { 2800 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2801 if (ps == null) return null; 2802 return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId), 2803 userId); 2804 } 2805 } 2806 return null; 2807 } 2808 2809 @Override 2810 public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) { 2811 if (!sUserManager.exists(userId)) return null; 2812 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get provider info"); 2813 synchronized (mPackages) { 2814 PackageParser.Provider p = mProviders.mProviders.get(component); 2815 if (DEBUG_PACKAGE_INFO) Log.v( 2816 TAG, "getProviderInfo " + component + ": " + p); 2817 if (p != null && mSettings.isEnabledLPr(p.info, flags, userId)) { 2818 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2819 if (ps == null) return null; 2820 return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId), 2821 userId); 2822 } 2823 } 2824 return null; 2825 } 2826 2827 @Override 2828 public String[] getSystemSharedLibraryNames() { 2829 Set<String> libSet; 2830 synchronized (mPackages) { 2831 libSet = mSharedLibraries.keySet(); 2832 int size = libSet.size(); 2833 if (size > 0) { 2834 String[] libs = new String[size]; 2835 libSet.toArray(libs); 2836 return libs; 2837 } 2838 } 2839 return null; 2840 } 2841 2842 /** 2843 * @hide 2844 */ 2845 PackageParser.Package findSharedNonSystemLibrary(String libName) { 2846 synchronized (mPackages) { 2847 PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName); 2848 if (lib != null && lib.apk != null) { 2849 return mPackages.get(lib.apk); 2850 } 2851 } 2852 return null; 2853 } 2854 2855 @Override 2856 public FeatureInfo[] getSystemAvailableFeatures() { 2857 Collection<FeatureInfo> featSet; 2858 synchronized (mPackages) { 2859 featSet = mAvailableFeatures.values(); 2860 int size = featSet.size(); 2861 if (size > 0) { 2862 FeatureInfo[] features = new FeatureInfo[size+1]; 2863 featSet.toArray(features); 2864 FeatureInfo fi = new FeatureInfo(); 2865 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version", 2866 FeatureInfo.GL_ES_VERSION_UNDEFINED); 2867 features[size] = fi; 2868 return features; 2869 } 2870 } 2871 return null; 2872 } 2873 2874 @Override 2875 public boolean hasSystemFeature(String name) { 2876 synchronized (mPackages) { 2877 return mAvailableFeatures.containsKey(name); 2878 } 2879 } 2880 2881 private void checkValidCaller(int uid, int userId) { 2882 if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0) 2883 return; 2884 2885 throw new SecurityException("Caller uid=" + uid 2886 + " is not privileged to communicate with user=" + userId); 2887 } 2888 2889 @Override 2890 public int checkPermission(String permName, String pkgName, int userId) { 2891 if (!sUserManager.exists(userId)) { 2892 return PackageManager.PERMISSION_DENIED; 2893 } 2894 2895 synchronized (mPackages) { 2896 final PackageParser.Package p = mPackages.get(pkgName); 2897 if (p != null && p.mExtras != null) { 2898 final PackageSetting ps = (PackageSetting) p.mExtras; 2899 if (ps.getPermissionsState().hasPermission(permName, userId)) { 2900 return PackageManager.PERMISSION_GRANTED; 2901 } 2902 } 2903 } 2904 2905 return PackageManager.PERMISSION_DENIED; 2906 } 2907 2908 @Override 2909 public int checkUidPermission(String permName, int uid) { 2910 final int userId = UserHandle.getUserId(uid); 2911 2912 if (!sUserManager.exists(userId)) { 2913 return PackageManager.PERMISSION_DENIED; 2914 } 2915 2916 synchronized (mPackages) { 2917 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 2918 if (obj != null) { 2919 final SettingBase ps = (SettingBase) obj; 2920 if (ps.getPermissionsState().hasPermission(permName, userId)) { 2921 return PackageManager.PERMISSION_GRANTED; 2922 } 2923 } else { 2924 ArraySet<String> perms = mSystemPermissions.get(uid); 2925 if (perms != null && perms.contains(permName)) { 2926 return PackageManager.PERMISSION_GRANTED; 2927 } 2928 } 2929 } 2930 2931 return PackageManager.PERMISSION_DENIED; 2932 } 2933 2934 /** 2935 * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS 2936 * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller. 2937 * @param checkShell TODO(yamasani): 2938 * @param message the message to log on security exception 2939 */ 2940 void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission, 2941 boolean checkShell, String message) { 2942 if (userId < 0) { 2943 throw new IllegalArgumentException("Invalid userId " + userId); 2944 } 2945 if (checkShell) { 2946 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId); 2947 } 2948 if (userId == UserHandle.getUserId(callingUid)) return; 2949 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 2950 if (requireFullPermission) { 2951 mContext.enforceCallingOrSelfPermission( 2952 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 2953 } else { 2954 try { 2955 mContext.enforceCallingOrSelfPermission( 2956 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 2957 } catch (SecurityException se) { 2958 mContext.enforceCallingOrSelfPermission( 2959 android.Manifest.permission.INTERACT_ACROSS_USERS, message); 2960 } 2961 } 2962 } 2963 } 2964 2965 void enforceShellRestriction(String restriction, int callingUid, int userHandle) { 2966 if (callingUid == Process.SHELL_UID) { 2967 if (userHandle >= 0 2968 && sUserManager.hasUserRestriction(restriction, userHandle)) { 2969 throw new SecurityException("Shell does not have permission to access user " 2970 + userHandle); 2971 } else if (userHandle < 0) { 2972 Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t" 2973 + Debug.getCallers(3)); 2974 } 2975 } 2976 } 2977 2978 private BasePermission findPermissionTreeLP(String permName) { 2979 for(BasePermission bp : mSettings.mPermissionTrees.values()) { 2980 if (permName.startsWith(bp.name) && 2981 permName.length() > bp.name.length() && 2982 permName.charAt(bp.name.length()) == '.') { 2983 return bp; 2984 } 2985 } 2986 return null; 2987 } 2988 2989 private BasePermission checkPermissionTreeLP(String permName) { 2990 if (permName != null) { 2991 BasePermission bp = findPermissionTreeLP(permName); 2992 if (bp != null) { 2993 if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) { 2994 return bp; 2995 } 2996 throw new SecurityException("Calling uid " 2997 + Binder.getCallingUid() 2998 + " is not allowed to add to permission tree " 2999 + bp.name + " owned by uid " + bp.uid); 3000 } 3001 } 3002 throw new SecurityException("No permission tree found for " + permName); 3003 } 3004 3005 static boolean compareStrings(CharSequence s1, CharSequence s2) { 3006 if (s1 == null) { 3007 return s2 == null; 3008 } 3009 if (s2 == null) { 3010 return false; 3011 } 3012 if (s1.getClass() != s2.getClass()) { 3013 return false; 3014 } 3015 return s1.equals(s2); 3016 } 3017 3018 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) { 3019 if (pi1.icon != pi2.icon) return false; 3020 if (pi1.logo != pi2.logo) return false; 3021 if (pi1.protectionLevel != pi2.protectionLevel) return false; 3022 if (!compareStrings(pi1.name, pi2.name)) return false; 3023 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false; 3024 // We'll take care of setting this one. 3025 if (!compareStrings(pi1.packageName, pi2.packageName)) return false; 3026 // These are not currently stored in settings. 3027 //if (!compareStrings(pi1.group, pi2.group)) return false; 3028 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false; 3029 //if (pi1.labelRes != pi2.labelRes) return false; 3030 //if (pi1.descriptionRes != pi2.descriptionRes) return false; 3031 return true; 3032 } 3033 3034 int permissionInfoFootprint(PermissionInfo info) { 3035 int size = info.name.length(); 3036 if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length(); 3037 if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length(); 3038 return size; 3039 } 3040 3041 int calculateCurrentPermissionFootprintLocked(BasePermission tree) { 3042 int size = 0; 3043 for (BasePermission perm : mSettings.mPermissions.values()) { 3044 if (perm.uid == tree.uid) { 3045 size += perm.name.length() + permissionInfoFootprint(perm.perm.info); 3046 } 3047 } 3048 return size; 3049 } 3050 3051 void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) { 3052 // We calculate the max size of permissions defined by this uid and throw 3053 // if that plus the size of 'info' would exceed our stated maximum. 3054 if (tree.uid != Process.SYSTEM_UID) { 3055 final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree); 3056 if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) { 3057 throw new SecurityException("Permission tree size cap exceeded"); 3058 } 3059 } 3060 } 3061 3062 boolean addPermissionLocked(PermissionInfo info, boolean async) { 3063 if (info.labelRes == 0 && info.nonLocalizedLabel == null) { 3064 throw new SecurityException("Label must be specified in permission"); 3065 } 3066 BasePermission tree = checkPermissionTreeLP(info.name); 3067 BasePermission bp = mSettings.mPermissions.get(info.name); 3068 boolean added = bp == null; 3069 boolean changed = true; 3070 int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel); 3071 if (added) { 3072 enforcePermissionCapLocked(info, tree); 3073 bp = new BasePermission(info.name, tree.sourcePackage, 3074 BasePermission.TYPE_DYNAMIC); 3075 } else if (bp.type != BasePermission.TYPE_DYNAMIC) { 3076 throw new SecurityException( 3077 "Not allowed to modify non-dynamic permission " 3078 + info.name); 3079 } else { 3080 if (bp.protectionLevel == fixedLevel 3081 && bp.perm.owner.equals(tree.perm.owner) 3082 && bp.uid == tree.uid 3083 && comparePermissionInfos(bp.perm.info, info)) { 3084 changed = false; 3085 } 3086 } 3087 bp.protectionLevel = fixedLevel; 3088 info = new PermissionInfo(info); 3089 info.protectionLevel = fixedLevel; 3090 bp.perm = new PackageParser.Permission(tree.perm.owner, info); 3091 bp.perm.info.packageName = tree.perm.info.packageName; 3092 bp.uid = tree.uid; 3093 if (added) { 3094 mSettings.mPermissions.put(info.name, bp); 3095 } 3096 if (changed) { 3097 if (!async) { 3098 mSettings.writeLPr(); 3099 } else { 3100 scheduleWriteSettingsLocked(); 3101 } 3102 } 3103 return added; 3104 } 3105 3106 @Override 3107 public boolean addPermission(PermissionInfo info) { 3108 synchronized (mPackages) { 3109 return addPermissionLocked(info, false); 3110 } 3111 } 3112 3113 @Override 3114 public boolean addPermissionAsync(PermissionInfo info) { 3115 synchronized (mPackages) { 3116 return addPermissionLocked(info, true); 3117 } 3118 } 3119 3120 @Override 3121 public void removePermission(String name) { 3122 synchronized (mPackages) { 3123 checkPermissionTreeLP(name); 3124 BasePermission bp = mSettings.mPermissions.get(name); 3125 if (bp != null) { 3126 if (bp.type != BasePermission.TYPE_DYNAMIC) { 3127 throw new SecurityException( 3128 "Not allowed to modify non-dynamic permission " 3129 + name); 3130 } 3131 mSettings.mPermissions.remove(name); 3132 mSettings.writeLPr(); 3133 } 3134 } 3135 } 3136 3137 private static void enforceDeclaredAsUsedAndRuntimePermission(PackageParser.Package pkg, 3138 BasePermission bp) { 3139 int index = pkg.requestedPermissions.indexOf(bp.name); 3140 if (index == -1) { 3141 throw new SecurityException("Package " + pkg.packageName 3142 + " has not requested permission " + bp.name); 3143 } 3144 if (!bp.isRuntime()) { 3145 throw new SecurityException("Permission " + bp.name 3146 + " is not a changeable permission type"); 3147 } 3148 } 3149 3150 @Override 3151 public void grantRuntimePermission(String packageName, String name, int userId) { 3152 if (!sUserManager.exists(userId)) { 3153 Log.e(TAG, "No such user:" + userId); 3154 return; 3155 } 3156 3157 mContext.enforceCallingOrSelfPermission( 3158 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, 3159 "grantRuntimePermission"); 3160 3161 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3162 "grantRuntimePermission"); 3163 3164 boolean gidsChanged = false; 3165 final SettingBase sb; 3166 3167 synchronized (mPackages) { 3168 final PackageParser.Package pkg = mPackages.get(packageName); 3169 if (pkg == null) { 3170 throw new IllegalArgumentException("Unknown package: " + packageName); 3171 } 3172 3173 final BasePermission bp = mSettings.mPermissions.get(name); 3174 if (bp == null) { 3175 throw new IllegalArgumentException("Unknown permission: " + name); 3176 } 3177 3178 enforceDeclaredAsUsedAndRuntimePermission(pkg, bp); 3179 3180 sb = (SettingBase) pkg.mExtras; 3181 if (sb == null) { 3182 throw new IllegalArgumentException("Unknown package: " + packageName); 3183 } 3184 3185 final PermissionsState permissionsState = sb.getPermissionsState(); 3186 3187 final int flags = permissionsState.getPermissionFlags(name, userId); 3188 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 3189 throw new SecurityException("Cannot grant system fixed permission: " 3190 + name + " for package: " + packageName); 3191 } 3192 3193 final int result = permissionsState.grantRuntimePermission(bp, userId); 3194 switch (result) { 3195 case PermissionsState.PERMISSION_OPERATION_FAILURE: { 3196 return; 3197 } 3198 3199 case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 3200 gidsChanged = true; 3201 } 3202 break; 3203 } 3204 3205 // Not critical if that is lost - app has to request again. 3206 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 3207 } 3208 3209 if (gidsChanged) { 3210 killSettingPackagesForUser(sb, userId, KILL_APP_REASON_GIDS_CHANGED); 3211 } 3212 } 3213 3214 @Override 3215 public void revokeRuntimePermission(String packageName, String name, int userId) { 3216 if (!sUserManager.exists(userId)) { 3217 Log.e(TAG, "No such user:" + userId); 3218 return; 3219 } 3220 3221 mContext.enforceCallingOrSelfPermission( 3222 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, 3223 "revokeRuntimePermission"); 3224 3225 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3226 "revokeRuntimePermission"); 3227 3228 final SettingBase sb; 3229 3230 synchronized (mPackages) { 3231 final PackageParser.Package pkg = mPackages.get(packageName); 3232 if (pkg == null) { 3233 throw new IllegalArgumentException("Unknown package: " + packageName); 3234 } 3235 3236 final BasePermission bp = mSettings.mPermissions.get(name); 3237 if (bp == null) { 3238 throw new IllegalArgumentException("Unknown permission: " + name); 3239 } 3240 3241 enforceDeclaredAsUsedAndRuntimePermission(pkg, bp); 3242 3243 sb = (SettingBase) pkg.mExtras; 3244 if (sb == null) { 3245 throw new IllegalArgumentException("Unknown package: " + packageName); 3246 } 3247 3248 final PermissionsState permissionsState = sb.getPermissionsState(); 3249 3250 final int flags = permissionsState.getPermissionFlags(name, userId); 3251 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 3252 throw new SecurityException("Cannot revoke system fixed permission: " 3253 + name + " for package: " + packageName); 3254 } 3255 3256 if (permissionsState.revokeRuntimePermission(bp, userId) == 3257 PermissionsState.PERMISSION_OPERATION_FAILURE) { 3258 return; 3259 } 3260 3261 // Critical, after this call app should never have the permission. 3262 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 3263 } 3264 3265 killSettingPackagesForUser(sb, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 3266 } 3267 3268 @Override 3269 public int getPermissionFlags(String name, String packageName, int userId) { 3270 if (!sUserManager.exists(userId)) { 3271 return 0; 3272 } 3273 3274 mContext.enforceCallingOrSelfPermission( 3275 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, 3276 "getPermissionFlags"); 3277 3278 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3279 "getPermissionFlags"); 3280 3281 synchronized (mPackages) { 3282 final PackageParser.Package pkg = mPackages.get(packageName); 3283 if (pkg == null) { 3284 throw new IllegalArgumentException("Unknown package: " + packageName); 3285 } 3286 3287 final BasePermission bp = mSettings.mPermissions.get(name); 3288 if (bp == null) { 3289 throw new IllegalArgumentException("Unknown permission: " + name); 3290 } 3291 3292 SettingBase sb = (SettingBase) pkg.mExtras; 3293 if (sb == null) { 3294 throw new IllegalArgumentException("Unknown package: " + packageName); 3295 } 3296 3297 PermissionsState permissionsState = sb.getPermissionsState(); 3298 return permissionsState.getPermissionFlags(name, userId); 3299 } 3300 } 3301 3302 @Override 3303 public void updatePermissionFlags(String name, String packageName, int flagMask, 3304 int flagValues, int userId) { 3305 if (!sUserManager.exists(userId)) { 3306 return; 3307 } 3308 3309 mContext.enforceCallingOrSelfPermission( 3310 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, 3311 "updatePermissionFlags"); 3312 3313 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3314 "updatePermissionFlags"); 3315 3316 // Only the system can change policy flags. 3317 if (getCallingUid() != Process.SYSTEM_UID) { 3318 flagMask &= ~PackageManager.FLAG_PERMISSION_POLICY_FIXED; 3319 flagValues &= ~PackageManager.FLAG_PERMISSION_POLICY_FIXED; 3320 } 3321 3322 // Only the package manager can change system flags. 3323 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 3324 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 3325 3326 synchronized (mPackages) { 3327 final PackageParser.Package pkg = mPackages.get(packageName); 3328 if (pkg == null) { 3329 throw new IllegalArgumentException("Unknown package: " + packageName); 3330 } 3331 3332 final BasePermission bp = mSettings.mPermissions.get(name); 3333 if (bp == null) { 3334 throw new IllegalArgumentException("Unknown permission: " + name); 3335 } 3336 3337 SettingBase sb = (SettingBase) pkg.mExtras; 3338 if (sb == null) { 3339 throw new IllegalArgumentException("Unknown package: " + packageName); 3340 } 3341 3342 PermissionsState permissionsState = sb.getPermissionsState(); 3343 3344 // Only the package manager can change flags for system component permissions. 3345 final int flags = permissionsState.getPermissionFlags(bp.name, userId); 3346 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 3347 return; 3348 } 3349 3350 if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) { 3351 // Install and runtime permissions are stored in different places, 3352 // so figure out what permission changed and persist the change. 3353 if (permissionsState.getInstallPermissionState(name) != null) { 3354 scheduleWriteSettingsLocked(); 3355 } else if (permissionsState.getRuntimePermissionState(name, userId) != null) { 3356 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 3357 } 3358 } 3359 } 3360 } 3361 3362 @Override 3363 public boolean shouldShowRequestPermissionRationale(String permissionName, 3364 String packageName, int userId) { 3365 if (UserHandle.getCallingUserId() != userId) { 3366 mContext.enforceCallingPermission( 3367 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 3368 "canShowRequestPermissionRationale for user " + userId); 3369 } 3370 3371 final int uid = getPackageUid(packageName, userId); 3372 if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) { 3373 return false; 3374 } 3375 3376 if (checkPermission(permissionName, packageName, userId) 3377 == PackageManager.PERMISSION_GRANTED) { 3378 return false; 3379 } 3380 3381 final int flags; 3382 3383 final long identity = Binder.clearCallingIdentity(); 3384 try { 3385 flags = getPermissionFlags(permissionName, 3386 packageName, userId); 3387 } finally { 3388 Binder.restoreCallingIdentity(identity); 3389 } 3390 3391 final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 3392 | PackageManager.FLAG_PERMISSION_POLICY_FIXED 3393 | PackageManager.FLAG_PERMISSION_USER_FIXED; 3394 3395 if ((flags & fixedFlags) != 0) { 3396 return false; 3397 } 3398 3399 return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0; 3400 } 3401 3402 @Override 3403 public boolean isProtectedBroadcast(String actionName) { 3404 synchronized (mPackages) { 3405 return mProtectedBroadcasts.contains(actionName); 3406 } 3407 } 3408 3409 @Override 3410 public int checkSignatures(String pkg1, String pkg2) { 3411 synchronized (mPackages) { 3412 final PackageParser.Package p1 = mPackages.get(pkg1); 3413 final PackageParser.Package p2 = mPackages.get(pkg2); 3414 if (p1 == null || p1.mExtras == null 3415 || p2 == null || p2.mExtras == null) { 3416 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3417 } 3418 return compareSignatures(p1.mSignatures, p2.mSignatures); 3419 } 3420 } 3421 3422 @Override 3423 public int checkUidSignatures(int uid1, int uid2) { 3424 // Map to base uids. 3425 uid1 = UserHandle.getAppId(uid1); 3426 uid2 = UserHandle.getAppId(uid2); 3427 // reader 3428 synchronized (mPackages) { 3429 Signature[] s1; 3430 Signature[] s2; 3431 Object obj = mSettings.getUserIdLPr(uid1); 3432 if (obj != null) { 3433 if (obj instanceof SharedUserSetting) { 3434 s1 = ((SharedUserSetting)obj).signatures.mSignatures; 3435 } else if (obj instanceof PackageSetting) { 3436 s1 = ((PackageSetting)obj).signatures.mSignatures; 3437 } else { 3438 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3439 } 3440 } else { 3441 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3442 } 3443 obj = mSettings.getUserIdLPr(uid2); 3444 if (obj != null) { 3445 if (obj instanceof SharedUserSetting) { 3446 s2 = ((SharedUserSetting)obj).signatures.mSignatures; 3447 } else if (obj instanceof PackageSetting) { 3448 s2 = ((PackageSetting)obj).signatures.mSignatures; 3449 } else { 3450 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3451 } 3452 } else { 3453 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3454 } 3455 return compareSignatures(s1, s2); 3456 } 3457 } 3458 3459 private void killSettingPackagesForUser(SettingBase sb, int userId, String reason) { 3460 final long identity = Binder.clearCallingIdentity(); 3461 try { 3462 if (sb instanceof SharedUserSetting) { 3463 SharedUserSetting sus = (SharedUserSetting) sb; 3464 final int packageCount = sus.packages.size(); 3465 for (int i = 0; i < packageCount; i++) { 3466 PackageSetting susPs = sus.packages.valueAt(i); 3467 if (userId == UserHandle.USER_ALL) { 3468 killApplication(susPs.pkg.packageName, susPs.appId, reason); 3469 } else { 3470 final int uid = UserHandle.getUid(userId, susPs.appId); 3471 killUid(uid, reason); 3472 } 3473 } 3474 } else if (sb instanceof PackageSetting) { 3475 PackageSetting ps = (PackageSetting) sb; 3476 if (userId == UserHandle.USER_ALL) { 3477 killApplication(ps.pkg.packageName, ps.appId, reason); 3478 } else { 3479 final int uid = UserHandle.getUid(userId, ps.appId); 3480 killUid(uid, reason); 3481 } 3482 } 3483 } finally { 3484 Binder.restoreCallingIdentity(identity); 3485 } 3486 } 3487 3488 private static void killUid(int uid, String reason) { 3489 IActivityManager am = ActivityManagerNative.getDefault(); 3490 if (am != null) { 3491 try { 3492 am.killUid(uid, reason); 3493 } catch (RemoteException e) { 3494 /* ignore - same process */ 3495 } 3496 } 3497 } 3498 3499 /** 3500 * Compares two sets of signatures. Returns: 3501 * <br /> 3502 * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null, 3503 * <br /> 3504 * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null, 3505 * <br /> 3506 * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null, 3507 * <br /> 3508 * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical, 3509 * <br /> 3510 * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ. 3511 */ 3512 static int compareSignatures(Signature[] s1, Signature[] s2) { 3513 if (s1 == null) { 3514 return s2 == null 3515 ? PackageManager.SIGNATURE_NEITHER_SIGNED 3516 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED; 3517 } 3518 3519 if (s2 == null) { 3520 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED; 3521 } 3522 3523 if (s1.length != s2.length) { 3524 return PackageManager.SIGNATURE_NO_MATCH; 3525 } 3526 3527 // Since both signature sets are of size 1, we can compare without HashSets. 3528 if (s1.length == 1) { 3529 return s1[0].equals(s2[0]) ? 3530 PackageManager.SIGNATURE_MATCH : 3531 PackageManager.SIGNATURE_NO_MATCH; 3532 } 3533 3534 ArraySet<Signature> set1 = new ArraySet<Signature>(); 3535 for (Signature sig : s1) { 3536 set1.add(sig); 3537 } 3538 ArraySet<Signature> set2 = new ArraySet<Signature>(); 3539 for (Signature sig : s2) { 3540 set2.add(sig); 3541 } 3542 // Make sure s2 contains all signatures in s1. 3543 if (set1.equals(set2)) { 3544 return PackageManager.SIGNATURE_MATCH; 3545 } 3546 return PackageManager.SIGNATURE_NO_MATCH; 3547 } 3548 3549 /** 3550 * If the database version for this type of package (internal storage or 3551 * external storage) is less than the version where package signatures 3552 * were updated, return true. 3553 */ 3554 private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 3555 return (isExternal(scannedPkg) && mSettings.isExternalDatabaseVersionOlderThan( 3556 DatabaseVersion.SIGNATURE_END_ENTITY)) 3557 || (!isExternal(scannedPkg) && mSettings.isInternalDatabaseVersionOlderThan( 3558 DatabaseVersion.SIGNATURE_END_ENTITY)); 3559 } 3560 3561 /** 3562 * Used for backward compatibility to make sure any packages with 3563 * certificate chains get upgraded to the new style. {@code existingSigs} 3564 * will be in the old format (since they were stored on disk from before the 3565 * system upgrade) and {@code scannedSigs} will be in the newer format. 3566 */ 3567 private int compareSignaturesCompat(PackageSignatures existingSigs, 3568 PackageParser.Package scannedPkg) { 3569 if (!isCompatSignatureUpdateNeeded(scannedPkg)) { 3570 return PackageManager.SIGNATURE_NO_MATCH; 3571 } 3572 3573 ArraySet<Signature> existingSet = new ArraySet<Signature>(); 3574 for (Signature sig : existingSigs.mSignatures) { 3575 existingSet.add(sig); 3576 } 3577 ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>(); 3578 for (Signature sig : scannedPkg.mSignatures) { 3579 try { 3580 Signature[] chainSignatures = sig.getChainSignatures(); 3581 for (Signature chainSig : chainSignatures) { 3582 scannedCompatSet.add(chainSig); 3583 } 3584 } catch (CertificateEncodingException e) { 3585 scannedCompatSet.add(sig); 3586 } 3587 } 3588 /* 3589 * Make sure the expanded scanned set contains all signatures in the 3590 * existing one. 3591 */ 3592 if (scannedCompatSet.equals(existingSet)) { 3593 // Migrate the old signatures to the new scheme. 3594 existingSigs.assignSignatures(scannedPkg.mSignatures); 3595 // The new KeySets will be re-added later in the scanning process. 3596 synchronized (mPackages) { 3597 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName); 3598 } 3599 return PackageManager.SIGNATURE_MATCH; 3600 } 3601 return PackageManager.SIGNATURE_NO_MATCH; 3602 } 3603 3604 private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 3605 if (isExternal(scannedPkg)) { 3606 return mSettings.isExternalDatabaseVersionOlderThan( 3607 DatabaseVersion.SIGNATURE_MALFORMED_RECOVER); 3608 } else { 3609 return mSettings.isInternalDatabaseVersionOlderThan( 3610 DatabaseVersion.SIGNATURE_MALFORMED_RECOVER); 3611 } 3612 } 3613 3614 private int compareSignaturesRecover(PackageSignatures existingSigs, 3615 PackageParser.Package scannedPkg) { 3616 if (!isRecoverSignatureUpdateNeeded(scannedPkg)) { 3617 return PackageManager.SIGNATURE_NO_MATCH; 3618 } 3619 3620 String msg = null; 3621 try { 3622 if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) { 3623 logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for " 3624 + scannedPkg.packageName); 3625 return PackageManager.SIGNATURE_MATCH; 3626 } 3627 } catch (CertificateException e) { 3628 msg = e.getMessage(); 3629 } 3630 3631 logCriticalInfo(Log.INFO, 3632 "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg); 3633 return PackageManager.SIGNATURE_NO_MATCH; 3634 } 3635 3636 @Override 3637 public String[] getPackagesForUid(int uid) { 3638 uid = UserHandle.getAppId(uid); 3639 // reader 3640 synchronized (mPackages) { 3641 Object obj = mSettings.getUserIdLPr(uid); 3642 if (obj instanceof SharedUserSetting) { 3643 final SharedUserSetting sus = (SharedUserSetting) obj; 3644 final int N = sus.packages.size(); 3645 final String[] res = new String[N]; 3646 final Iterator<PackageSetting> it = sus.packages.iterator(); 3647 int i = 0; 3648 while (it.hasNext()) { 3649 res[i++] = it.next().name; 3650 } 3651 return res; 3652 } else if (obj instanceof PackageSetting) { 3653 final PackageSetting ps = (PackageSetting) obj; 3654 return new String[] { ps.name }; 3655 } 3656 } 3657 return null; 3658 } 3659 3660 @Override 3661 public String getNameForUid(int uid) { 3662 // reader 3663 synchronized (mPackages) { 3664 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3665 if (obj instanceof SharedUserSetting) { 3666 final SharedUserSetting sus = (SharedUserSetting) obj; 3667 return sus.name + ":" + sus.userId; 3668 } else if (obj instanceof PackageSetting) { 3669 final PackageSetting ps = (PackageSetting) obj; 3670 return ps.name; 3671 } 3672 } 3673 return null; 3674 } 3675 3676 @Override 3677 public int getUidForSharedUser(String sharedUserName) { 3678 if(sharedUserName == null) { 3679 return -1; 3680 } 3681 // reader 3682 synchronized (mPackages) { 3683 final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false); 3684 if (suid == null) { 3685 return -1; 3686 } 3687 return suid.userId; 3688 } 3689 } 3690 3691 @Override 3692 public int getFlagsForUid(int uid) { 3693 synchronized (mPackages) { 3694 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3695 if (obj instanceof SharedUserSetting) { 3696 final SharedUserSetting sus = (SharedUserSetting) obj; 3697 return sus.pkgFlags; 3698 } else if (obj instanceof PackageSetting) { 3699 final PackageSetting ps = (PackageSetting) obj; 3700 return ps.pkgFlags; 3701 } 3702 } 3703 return 0; 3704 } 3705 3706 @Override 3707 public int getPrivateFlagsForUid(int uid) { 3708 synchronized (mPackages) { 3709 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3710 if (obj instanceof SharedUserSetting) { 3711 final SharedUserSetting sus = (SharedUserSetting) obj; 3712 return sus.pkgPrivateFlags; 3713 } else if (obj instanceof PackageSetting) { 3714 final PackageSetting ps = (PackageSetting) obj; 3715 return ps.pkgPrivateFlags; 3716 } 3717 } 3718 return 0; 3719 } 3720 3721 @Override 3722 public boolean isUidPrivileged(int uid) { 3723 uid = UserHandle.getAppId(uid); 3724 // reader 3725 synchronized (mPackages) { 3726 Object obj = mSettings.getUserIdLPr(uid); 3727 if (obj instanceof SharedUserSetting) { 3728 final SharedUserSetting sus = (SharedUserSetting) obj; 3729 final Iterator<PackageSetting> it = sus.packages.iterator(); 3730 while (it.hasNext()) { 3731 if (it.next().isPrivileged()) { 3732 return true; 3733 } 3734 } 3735 } else if (obj instanceof PackageSetting) { 3736 final PackageSetting ps = (PackageSetting) obj; 3737 return ps.isPrivileged(); 3738 } 3739 } 3740 return false; 3741 } 3742 3743 @Override 3744 public String[] getAppOpPermissionPackages(String permissionName) { 3745 synchronized (mPackages) { 3746 ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName); 3747 if (pkgs == null) { 3748 return null; 3749 } 3750 return pkgs.toArray(new String[pkgs.size()]); 3751 } 3752 } 3753 3754 @Override 3755 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 3756 int flags, int userId) { 3757 if (!sUserManager.exists(userId)) return null; 3758 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "resolve intent"); 3759 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 3760 return chooseBestActivity(intent, resolvedType, flags, query, userId); 3761 } 3762 3763 @Override 3764 public void setLastChosenActivity(Intent intent, String resolvedType, int flags, 3765 IntentFilter filter, int match, ComponentName activity) { 3766 final int userId = UserHandle.getCallingUserId(); 3767 if (DEBUG_PREFERRED) { 3768 Log.v(TAG, "setLastChosenActivity intent=" + intent 3769 + " resolvedType=" + resolvedType 3770 + " flags=" + flags 3771 + " filter=" + filter 3772 + " match=" + match 3773 + " activity=" + activity); 3774 filter.dump(new PrintStreamPrinter(System.out), " "); 3775 } 3776 intent.setComponent(null); 3777 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 3778 // Find any earlier preferred or last chosen entries and nuke them 3779 findPreferredActivity(intent, resolvedType, 3780 flags, query, 0, false, true, false, userId); 3781 // Add the new activity as the last chosen for this filter 3782 addPreferredActivityInternal(filter, match, null, activity, false, userId, 3783 "Setting last chosen"); 3784 } 3785 3786 @Override 3787 public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) { 3788 final int userId = UserHandle.getCallingUserId(); 3789 if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent); 3790 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 3791 return findPreferredActivity(intent, resolvedType, flags, query, 0, 3792 false, false, false, userId); 3793 } 3794 3795 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType, 3796 int flags, List<ResolveInfo> query, int userId) { 3797 if (query != null) { 3798 final int N = query.size(); 3799 if (N == 1) { 3800 return query.get(0); 3801 } else if (N > 1) { 3802 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0); 3803 // If there is more than one activity with the same priority, 3804 // then let the user decide between them. 3805 ResolveInfo r0 = query.get(0); 3806 ResolveInfo r1 = query.get(1); 3807 if (DEBUG_INTENT_MATCHING || debug) { 3808 Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs " 3809 + r1.activityInfo.name + "=" + r1.priority); 3810 } 3811 // If the first activity has a higher priority, or a different 3812 // default, then it is always desireable to pick it. 3813 if (r0.priority != r1.priority 3814 || r0.preferredOrder != r1.preferredOrder 3815 || r0.isDefault != r1.isDefault) { 3816 return query.get(0); 3817 } 3818 // If we have saved a preference for a preferred activity for 3819 // this Intent, use that. 3820 ResolveInfo ri = findPreferredActivity(intent, resolvedType, 3821 flags, query, r0.priority, true, false, debug, userId); 3822 if (ri != null) { 3823 return ri; 3824 } 3825 if (userId != 0) { 3826 ri = new ResolveInfo(mResolveInfo); 3827 ri.activityInfo = new ActivityInfo(ri.activityInfo); 3828 ri.activityInfo.applicationInfo = new ApplicationInfo( 3829 ri.activityInfo.applicationInfo); 3830 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId, 3831 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid)); 3832 return ri; 3833 } 3834 return mResolveInfo; 3835 } 3836 } 3837 return null; 3838 } 3839 3840 private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType, 3841 int flags, List<ResolveInfo> query, boolean debug, int userId) { 3842 final int N = query.size(); 3843 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 3844 .get(userId); 3845 // Get the list of persistent preferred activities that handle the intent 3846 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities..."); 3847 List<PersistentPreferredActivity> pprefs = ppir != null 3848 ? ppir.queryIntent(intent, resolvedType, 3849 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 3850 : null; 3851 if (pprefs != null && pprefs.size() > 0) { 3852 final int M = pprefs.size(); 3853 for (int i=0; i<M; i++) { 3854 final PersistentPreferredActivity ppa = pprefs.get(i); 3855 if (DEBUG_PREFERRED || debug) { 3856 Slog.v(TAG, "Checking PersistentPreferredActivity ds=" 3857 + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>") 3858 + "\n component=" + ppa.mComponent); 3859 ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3860 } 3861 final ActivityInfo ai = getActivityInfo(ppa.mComponent, 3862 flags | PackageManager.GET_DISABLED_COMPONENTS, userId); 3863 if (DEBUG_PREFERRED || debug) { 3864 Slog.v(TAG, "Found persistent preferred activity:"); 3865 if (ai != null) { 3866 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3867 } else { 3868 Slog.v(TAG, " null"); 3869 } 3870 } 3871 if (ai == null) { 3872 // This previously registered persistent preferred activity 3873 // component is no longer known. Ignore it and do NOT remove it. 3874 continue; 3875 } 3876 for (int j=0; j<N; j++) { 3877 final ResolveInfo ri = query.get(j); 3878 if (!ri.activityInfo.applicationInfo.packageName 3879 .equals(ai.applicationInfo.packageName)) { 3880 continue; 3881 } 3882 if (!ri.activityInfo.name.equals(ai.name)) { 3883 continue; 3884 } 3885 // Found a persistent preference that can handle the intent. 3886 if (DEBUG_PREFERRED || debug) { 3887 Slog.v(TAG, "Returning persistent preferred activity: " + 3888 ri.activityInfo.packageName + "/" + ri.activityInfo.name); 3889 } 3890 return ri; 3891 } 3892 } 3893 } 3894 return null; 3895 } 3896 3897 ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags, 3898 List<ResolveInfo> query, int priority, boolean always, 3899 boolean removeMatches, boolean debug, int userId) { 3900 if (!sUserManager.exists(userId)) return null; 3901 // writer 3902 synchronized (mPackages) { 3903 if (intent.getSelector() != null) { 3904 intent = intent.getSelector(); 3905 } 3906 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION); 3907 3908 // Try to find a matching persistent preferred activity. 3909 ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query, 3910 debug, userId); 3911 3912 // If a persistent preferred activity matched, use it. 3913 if (pri != null) { 3914 return pri; 3915 } 3916 3917 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 3918 // Get the list of preferred activities that handle the intent 3919 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities..."); 3920 List<PreferredActivity> prefs = pir != null 3921 ? pir.queryIntent(intent, resolvedType, 3922 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 3923 : null; 3924 if (prefs != null && prefs.size() > 0) { 3925 boolean changed = false; 3926 try { 3927 // First figure out how good the original match set is. 3928 // We will only allow preferred activities that came 3929 // from the same match quality. 3930 int match = 0; 3931 3932 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match..."); 3933 3934 final int N = query.size(); 3935 for (int j=0; j<N; j++) { 3936 final ResolveInfo ri = query.get(j); 3937 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo 3938 + ": 0x" + Integer.toHexString(match)); 3939 if (ri.match > match) { 3940 match = ri.match; 3941 } 3942 } 3943 3944 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x" 3945 + Integer.toHexString(match)); 3946 3947 match &= IntentFilter.MATCH_CATEGORY_MASK; 3948 final int M = prefs.size(); 3949 for (int i=0; i<M; i++) { 3950 final PreferredActivity pa = prefs.get(i); 3951 if (DEBUG_PREFERRED || debug) { 3952 Slog.v(TAG, "Checking PreferredActivity ds=" 3953 + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>") 3954 + "\n component=" + pa.mPref.mComponent); 3955 pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3956 } 3957 if (pa.mPref.mMatch != match) { 3958 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match " 3959 + Integer.toHexString(pa.mPref.mMatch)); 3960 continue; 3961 } 3962 // If it's not an "always" type preferred activity and that's what we're 3963 // looking for, skip it. 3964 if (always && !pa.mPref.mAlways) { 3965 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry"); 3966 continue; 3967 } 3968 final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent, 3969 flags | PackageManager.GET_DISABLED_COMPONENTS, userId); 3970 if (DEBUG_PREFERRED || debug) { 3971 Slog.v(TAG, "Found preferred activity:"); 3972 if (ai != null) { 3973 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3974 } else { 3975 Slog.v(TAG, " null"); 3976 } 3977 } 3978 if (ai == null) { 3979 // This previously registered preferred activity 3980 // component is no longer known. Most likely an update 3981 // to the app was installed and in the new version this 3982 // component no longer exists. Clean it up by removing 3983 // it from the preferred activities list, and skip it. 3984 Slog.w(TAG, "Removing dangling preferred activity: " 3985 + pa.mPref.mComponent); 3986 pir.removeFilter(pa); 3987 changed = true; 3988 continue; 3989 } 3990 for (int j=0; j<N; j++) { 3991 final ResolveInfo ri = query.get(j); 3992 if (!ri.activityInfo.applicationInfo.packageName 3993 .equals(ai.applicationInfo.packageName)) { 3994 continue; 3995 } 3996 if (!ri.activityInfo.name.equals(ai.name)) { 3997 continue; 3998 } 3999 4000 if (removeMatches) { 4001 pir.removeFilter(pa); 4002 changed = true; 4003 if (DEBUG_PREFERRED) { 4004 Slog.v(TAG, "Removing match " + pa.mPref.mComponent); 4005 } 4006 break; 4007 } 4008 4009 // Okay we found a previously set preferred or last chosen app. 4010 // If the result set is different from when this 4011 // was created, we need to clear it and re-ask the 4012 // user their preference, if we're looking for an "always" type entry. 4013 if (always && !pa.mPref.sameSet(query)) { 4014 Slog.i(TAG, "Result set changed, dropping preferred activity for " 4015 + intent + " type " + resolvedType); 4016 if (DEBUG_PREFERRED) { 4017 Slog.v(TAG, "Removing preferred activity since set changed " 4018 + pa.mPref.mComponent); 4019 } 4020 pir.removeFilter(pa); 4021 // Re-add the filter as a "last chosen" entry (!always) 4022 PreferredActivity lastChosen = new PreferredActivity( 4023 pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false); 4024 pir.addFilter(lastChosen); 4025 changed = true; 4026 return null; 4027 } 4028 4029 // Yay! Either the set matched or we're looking for the last chosen 4030 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: " 4031 + ri.activityInfo.packageName + "/" + ri.activityInfo.name); 4032 return ri; 4033 } 4034 } 4035 } finally { 4036 if (changed) { 4037 if (DEBUG_PREFERRED) { 4038 Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions"); 4039 } 4040 scheduleWritePackageRestrictionsLocked(userId); 4041 } 4042 } 4043 } 4044 } 4045 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return"); 4046 return null; 4047 } 4048 4049 /* 4050 * Returns if intent can be forwarded from the sourceUserId to the targetUserId 4051 */ 4052 @Override 4053 public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId, 4054 int targetUserId) { 4055 mContext.enforceCallingOrSelfPermission( 4056 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 4057 List<CrossProfileIntentFilter> matches = 4058 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId); 4059 if (matches != null) { 4060 int size = matches.size(); 4061 for (int i = 0; i < size; i++) { 4062 if (matches.get(i).getTargetUserId() == targetUserId) return true; 4063 } 4064 } 4065 return false; 4066 } 4067 4068 private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent, 4069 String resolvedType, int userId) { 4070 CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId); 4071 if (resolver != null) { 4072 return resolver.queryIntent(intent, resolvedType, false, userId); 4073 } 4074 return null; 4075 } 4076 4077 @Override 4078 public List<ResolveInfo> queryIntentActivities(Intent intent, 4079 String resolvedType, int flags, int userId) { 4080 if (!sUserManager.exists(userId)) return Collections.emptyList(); 4081 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "query intent activities"); 4082 ComponentName comp = intent.getComponent(); 4083 if (comp == null) { 4084 if (intent.getSelector() != null) { 4085 intent = intent.getSelector(); 4086 comp = intent.getComponent(); 4087 } 4088 } 4089 4090 if (comp != null) { 4091 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 4092 final ActivityInfo ai = getActivityInfo(comp, flags, userId); 4093 if (ai != null) { 4094 final ResolveInfo ri = new ResolveInfo(); 4095 ri.activityInfo = ai; 4096 list.add(ri); 4097 } 4098 return list; 4099 } 4100 4101 // reader 4102 synchronized (mPackages) { 4103 final String pkgName = intent.getPackage(); 4104 if (pkgName == null) { 4105 List<CrossProfileIntentFilter> matchingFilters = 4106 getMatchingCrossProfileIntentFilters(intent, resolvedType, userId); 4107 // Check for results that need to skip the current profile. 4108 ResolveInfo resolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent, 4109 resolvedType, flags, userId); 4110 if (resolveInfo != null && isUserEnabled(resolveInfo.targetUserId)) { 4111 List<ResolveInfo> result = new ArrayList<ResolveInfo>(1); 4112 result.add(resolveInfo); 4113 return filterIfNotPrimaryUser(result, userId); 4114 } 4115 4116 // Check for results in the current profile. 4117 List<ResolveInfo> result = mActivities.queryIntent( 4118 intent, resolvedType, flags, userId); 4119 4120 // Check for cross profile results. 4121 resolveInfo = queryCrossProfileIntents( 4122 matchingFilters, intent, resolvedType, flags, userId); 4123 if (resolveInfo != null && isUserEnabled(resolveInfo.targetUserId)) { 4124 result.add(resolveInfo); 4125 Collections.sort(result, mResolvePrioritySorter); 4126 } 4127 result = filterIfNotPrimaryUser(result, userId); 4128 if (result.size() > 1 && hasWebURI(intent)) { 4129 return filterCandidatesWithDomainPreferedActivitiesLPr(flags, result); 4130 } 4131 return result; 4132 } 4133 final PackageParser.Package pkg = mPackages.get(pkgName); 4134 if (pkg != null) { 4135 return filterIfNotPrimaryUser( 4136 mActivities.queryIntentForPackage( 4137 intent, resolvedType, flags, pkg.activities, userId), 4138 userId); 4139 } 4140 return new ArrayList<ResolveInfo>(); 4141 } 4142 } 4143 4144 private boolean isUserEnabled(int userId) { 4145 long callingId = Binder.clearCallingIdentity(); 4146 try { 4147 UserInfo userInfo = sUserManager.getUserInfo(userId); 4148 return userInfo != null && userInfo.isEnabled(); 4149 } finally { 4150 Binder.restoreCallingIdentity(callingId); 4151 } 4152 } 4153 4154 /** 4155 * Filter out activities with primaryUserOnly flag set, when current user is not the owner. 4156 * 4157 * @return filtered list 4158 */ 4159 private List<ResolveInfo> filterIfNotPrimaryUser(List<ResolveInfo> resolveInfos, int userId) { 4160 if (userId == UserHandle.USER_OWNER) { 4161 return resolveInfos; 4162 } 4163 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 4164 ResolveInfo info = resolveInfos.get(i); 4165 if ((info.activityInfo.flags & ActivityInfo.FLAG_PRIMARY_USER_ONLY) != 0) { 4166 resolveInfos.remove(i); 4167 } 4168 } 4169 return resolveInfos; 4170 } 4171 4172 private static boolean hasWebURI(Intent intent) { 4173 if (intent.getData() == null) { 4174 return false; 4175 } 4176 final String scheme = intent.getScheme(); 4177 if (TextUtils.isEmpty(scheme)) { 4178 return false; 4179 } 4180 return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS); 4181 } 4182 4183 private List<ResolveInfo> filterCandidatesWithDomainPreferedActivitiesLPr( 4184 int flags, List<ResolveInfo> candidates) { 4185 if (DEBUG_PREFERRED) { 4186 Slog.v("TAG", "Filtering results with prefered activities. Candidates count: " + 4187 candidates.size()); 4188 } 4189 4190 final int userId = UserHandle.getCallingUserId(); 4191 ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>(); 4192 ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>(); 4193 ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>(); 4194 ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>(); 4195 ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>(); 4196 4197 synchronized (mPackages) { 4198 final int count = candidates.size(); 4199 // First, try to use the domain prefered App. Partition the candidates into four lists: 4200 // one for the final results, one for the "do not use ever", one for "undefined status" 4201 // and finally one for "Browser App type". 4202 for (int n=0; n<count; n++) { 4203 ResolveInfo info = candidates.get(n); 4204 String packageName = info.activityInfo.packageName; 4205 PackageSetting ps = mSettings.mPackages.get(packageName); 4206 if (ps != null) { 4207 // Add to the special match all list (Browser use case) 4208 if (info.handleAllWebDataURI) { 4209 matchAllList.add(info); 4210 continue; 4211 } 4212 // Try to get the status from User settings first 4213 int status = getDomainVerificationStatusLPr(ps, userId); 4214 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) { 4215 alwaysList.add(info); 4216 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 4217 neverList.add(info); 4218 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED || 4219 status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) { 4220 undefinedList.add(info); 4221 } 4222 } 4223 } 4224 // First try to add the "always" if there is any 4225 if (alwaysList.size() > 0) { 4226 result.addAll(alwaysList); 4227 } else { 4228 // Add all undefined Apps as we want them to appear in the Disambiguation dialog. 4229 result.addAll(undefinedList); 4230 // Also add Browsers (all of them or only the default one) 4231 if ((flags & MATCH_ALL) != 0) { 4232 result.addAll(matchAllList); 4233 } else { 4234 // Try to add the Default Browser if we can 4235 final String defaultBrowserPackageName = getDefaultBrowserPackageName( 4236 UserHandle.myUserId()); 4237 if (!TextUtils.isEmpty(defaultBrowserPackageName)) { 4238 boolean defaultBrowserFound = false; 4239 final int browserCount = matchAllList.size(); 4240 for (int n=0; n<browserCount; n++) { 4241 ResolveInfo browser = matchAllList.get(n); 4242 if (browser.activityInfo.packageName.equals(defaultBrowserPackageName)) { 4243 result.add(browser); 4244 defaultBrowserFound = true; 4245 break; 4246 } 4247 } 4248 if (!defaultBrowserFound) { 4249 result.addAll(matchAllList); 4250 } 4251 } else { 4252 result.addAll(matchAllList); 4253 } 4254 } 4255 4256 // If there is nothing selected, add all candidates and remove the ones that the User 4257 // has explicitely put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state 4258 if (result.size() == 0) { 4259 result.addAll(candidates); 4260 result.removeAll(neverList); 4261 } 4262 } 4263 } 4264 if (DEBUG_PREFERRED) { 4265 Slog.v("TAG", "Filtered results with prefered activities. New candidates count: " + 4266 result.size()); 4267 } 4268 return result; 4269 } 4270 4271 private int getDomainVerificationStatusLPr(PackageSetting ps, int userId) { 4272 int status = ps.getDomainVerificationStatusForUser(userId); 4273 // if none available, get the master status 4274 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 4275 if (ps.getIntentFilterVerificationInfo() != null) { 4276 status = ps.getIntentFilterVerificationInfo().getStatus(); 4277 } 4278 } 4279 return status; 4280 } 4281 4282 private ResolveInfo querySkipCurrentProfileIntents( 4283 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 4284 int flags, int sourceUserId) { 4285 if (matchingFilters != null) { 4286 int size = matchingFilters.size(); 4287 for (int i = 0; i < size; i ++) { 4288 CrossProfileIntentFilter filter = matchingFilters.get(i); 4289 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) { 4290 // Checking if there are activities in the target user that can handle the 4291 // intent. 4292 ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType, 4293 flags, sourceUserId); 4294 if (resolveInfo != null) { 4295 return resolveInfo; 4296 } 4297 } 4298 } 4299 } 4300 return null; 4301 } 4302 4303 // Return matching ResolveInfo if any for skip current profile intent filters. 4304 private ResolveInfo queryCrossProfileIntents( 4305 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 4306 int flags, int sourceUserId) { 4307 if (matchingFilters != null) { 4308 // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and 4309 // match the same intent. For performance reasons, it is better not to 4310 // run queryIntent twice for the same userId 4311 SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray(); 4312 int size = matchingFilters.size(); 4313 for (int i = 0; i < size; i++) { 4314 CrossProfileIntentFilter filter = matchingFilters.get(i); 4315 int targetUserId = filter.getTargetUserId(); 4316 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) == 0 4317 && !alreadyTriedUserIds.get(targetUserId)) { 4318 // Checking if there are activities in the target user that can handle the 4319 // intent. 4320 ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType, 4321 flags, sourceUserId); 4322 if (resolveInfo != null) return resolveInfo; 4323 alreadyTriedUserIds.put(targetUserId, true); 4324 } 4325 } 4326 } 4327 return null; 4328 } 4329 4330 private ResolveInfo checkTargetCanHandle(CrossProfileIntentFilter filter, Intent intent, 4331 String resolvedType, int flags, int sourceUserId) { 4332 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 4333 resolvedType, flags, filter.getTargetUserId()); 4334 if (resultTargetUser != null && !resultTargetUser.isEmpty()) { 4335 return createForwardingResolveInfo(filter, sourceUserId, filter.getTargetUserId()); 4336 } 4337 return null; 4338 } 4339 4340 private ResolveInfo createForwardingResolveInfo(IntentFilter filter, 4341 int sourceUserId, int targetUserId) { 4342 ResolveInfo forwardingResolveInfo = new ResolveInfo(); 4343 String className; 4344 if (targetUserId == UserHandle.USER_OWNER) { 4345 className = FORWARD_INTENT_TO_USER_OWNER; 4346 } else { 4347 className = FORWARD_INTENT_TO_MANAGED_PROFILE; 4348 } 4349 ComponentName forwardingActivityComponentName = new ComponentName( 4350 mAndroidApplication.packageName, className); 4351 ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0, 4352 sourceUserId); 4353 if (targetUserId == UserHandle.USER_OWNER) { 4354 forwardingActivityInfo.showUserIcon = UserHandle.USER_OWNER; 4355 forwardingResolveInfo.noResourceId = true; 4356 } 4357 forwardingResolveInfo.activityInfo = forwardingActivityInfo; 4358 forwardingResolveInfo.priority = 0; 4359 forwardingResolveInfo.preferredOrder = 0; 4360 forwardingResolveInfo.match = 0; 4361 forwardingResolveInfo.isDefault = true; 4362 forwardingResolveInfo.filter = filter; 4363 forwardingResolveInfo.targetUserId = targetUserId; 4364 return forwardingResolveInfo; 4365 } 4366 4367 @Override 4368 public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller, 4369 Intent[] specifics, String[] specificTypes, Intent intent, 4370 String resolvedType, int flags, int userId) { 4371 if (!sUserManager.exists(userId)) return Collections.emptyList(); 4372 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, 4373 false, "query intent activity options"); 4374 final String resultsAction = intent.getAction(); 4375 4376 List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags 4377 | PackageManager.GET_RESOLVED_FILTER, userId); 4378 4379 if (DEBUG_INTENT_MATCHING) { 4380 Log.v(TAG, "Query " + intent + ": " + results); 4381 } 4382 4383 int specificsPos = 0; 4384 int N; 4385 4386 // todo: note that the algorithm used here is O(N^2). This 4387 // isn't a problem in our current environment, but if we start running 4388 // into situations where we have more than 5 or 10 matches then this 4389 // should probably be changed to something smarter... 4390 4391 // First we go through and resolve each of the specific items 4392 // that were supplied, taking care of removing any corresponding 4393 // duplicate items in the generic resolve list. 4394 if (specifics != null) { 4395 for (int i=0; i<specifics.length; i++) { 4396 final Intent sintent = specifics[i]; 4397 if (sintent == null) { 4398 continue; 4399 } 4400 4401 if (DEBUG_INTENT_MATCHING) { 4402 Log.v(TAG, "Specific #" + i + ": " + sintent); 4403 } 4404 4405 String action = sintent.getAction(); 4406 if (resultsAction != null && resultsAction.equals(action)) { 4407 // If this action was explicitly requested, then don't 4408 // remove things that have it. 4409 action = null; 4410 } 4411 4412 ResolveInfo ri = null; 4413 ActivityInfo ai = null; 4414 4415 ComponentName comp = sintent.getComponent(); 4416 if (comp == null) { 4417 ri = resolveIntent( 4418 sintent, 4419 specificTypes != null ? specificTypes[i] : null, 4420 flags, userId); 4421 if (ri == null) { 4422 continue; 4423 } 4424 if (ri == mResolveInfo) { 4425 // ACK! Must do something better with this. 4426 } 4427 ai = ri.activityInfo; 4428 comp = new ComponentName(ai.applicationInfo.packageName, 4429 ai.name); 4430 } else { 4431 ai = getActivityInfo(comp, flags, userId); 4432 if (ai == null) { 4433 continue; 4434 } 4435 } 4436 4437 // Look for any generic query activities that are duplicates 4438 // of this specific one, and remove them from the results. 4439 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai); 4440 N = results.size(); 4441 int j; 4442 for (j=specificsPos; j<N; j++) { 4443 ResolveInfo sri = results.get(j); 4444 if ((sri.activityInfo.name.equals(comp.getClassName()) 4445 && sri.activityInfo.applicationInfo.packageName.equals( 4446 comp.getPackageName())) 4447 || (action != null && sri.filter.matchAction(action))) { 4448 results.remove(j); 4449 if (DEBUG_INTENT_MATCHING) Log.v( 4450 TAG, "Removing duplicate item from " + j 4451 + " due to specific " + specificsPos); 4452 if (ri == null) { 4453 ri = sri; 4454 } 4455 j--; 4456 N--; 4457 } 4458 } 4459 4460 // Add this specific item to its proper place. 4461 if (ri == null) { 4462 ri = new ResolveInfo(); 4463 ri.activityInfo = ai; 4464 } 4465 results.add(specificsPos, ri); 4466 ri.specificIndex = i; 4467 specificsPos++; 4468 } 4469 } 4470 4471 // Now we go through the remaining generic results and remove any 4472 // duplicate actions that are found here. 4473 N = results.size(); 4474 for (int i=specificsPos; i<N-1; i++) { 4475 final ResolveInfo rii = results.get(i); 4476 if (rii.filter == null) { 4477 continue; 4478 } 4479 4480 // Iterate over all of the actions of this result's intent 4481 // filter... typically this should be just one. 4482 final Iterator<String> it = rii.filter.actionsIterator(); 4483 if (it == null) { 4484 continue; 4485 } 4486 while (it.hasNext()) { 4487 final String action = it.next(); 4488 if (resultsAction != null && resultsAction.equals(action)) { 4489 // If this action was explicitly requested, then don't 4490 // remove things that have it. 4491 continue; 4492 } 4493 for (int j=i+1; j<N; j++) { 4494 final ResolveInfo rij = results.get(j); 4495 if (rij.filter != null && rij.filter.hasAction(action)) { 4496 results.remove(j); 4497 if (DEBUG_INTENT_MATCHING) Log.v( 4498 TAG, "Removing duplicate item from " + j 4499 + " due to action " + action + " at " + i); 4500 j--; 4501 N--; 4502 } 4503 } 4504 } 4505 4506 // If the caller didn't request filter information, drop it now 4507 // so we don't have to marshall/unmarshall it. 4508 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 4509 rii.filter = null; 4510 } 4511 } 4512 4513 // Filter out the caller activity if so requested. 4514 if (caller != null) { 4515 N = results.size(); 4516 for (int i=0; i<N; i++) { 4517 ActivityInfo ainfo = results.get(i).activityInfo; 4518 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName) 4519 && caller.getClassName().equals(ainfo.name)) { 4520 results.remove(i); 4521 break; 4522 } 4523 } 4524 } 4525 4526 // If the caller didn't request filter information, 4527 // drop them now so we don't have to 4528 // marshall/unmarshall it. 4529 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 4530 N = results.size(); 4531 for (int i=0; i<N; i++) { 4532 results.get(i).filter = null; 4533 } 4534 } 4535 4536 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results); 4537 return results; 4538 } 4539 4540 @Override 4541 public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags, 4542 int userId) { 4543 if (!sUserManager.exists(userId)) return Collections.emptyList(); 4544 ComponentName comp = intent.getComponent(); 4545 if (comp == null) { 4546 if (intent.getSelector() != null) { 4547 intent = intent.getSelector(); 4548 comp = intent.getComponent(); 4549 } 4550 } 4551 if (comp != null) { 4552 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 4553 ActivityInfo ai = getReceiverInfo(comp, flags, userId); 4554 if (ai != null) { 4555 ResolveInfo ri = new ResolveInfo(); 4556 ri.activityInfo = ai; 4557 list.add(ri); 4558 } 4559 return list; 4560 } 4561 4562 // reader 4563 synchronized (mPackages) { 4564 String pkgName = intent.getPackage(); 4565 if (pkgName == null) { 4566 return mReceivers.queryIntent(intent, resolvedType, flags, userId); 4567 } 4568 final PackageParser.Package pkg = mPackages.get(pkgName); 4569 if (pkg != null) { 4570 return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers, 4571 userId); 4572 } 4573 return null; 4574 } 4575 } 4576 4577 @Override 4578 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) { 4579 List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId); 4580 if (!sUserManager.exists(userId)) return null; 4581 if (query != null) { 4582 if (query.size() >= 1) { 4583 // If there is more than one service with the same priority, 4584 // just arbitrarily pick the first one. 4585 return query.get(0); 4586 } 4587 } 4588 return null; 4589 } 4590 4591 @Override 4592 public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags, 4593 int userId) { 4594 if (!sUserManager.exists(userId)) return Collections.emptyList(); 4595 ComponentName comp = intent.getComponent(); 4596 if (comp == null) { 4597 if (intent.getSelector() != null) { 4598 intent = intent.getSelector(); 4599 comp = intent.getComponent(); 4600 } 4601 } 4602 if (comp != null) { 4603 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 4604 final ServiceInfo si = getServiceInfo(comp, flags, userId); 4605 if (si != null) { 4606 final ResolveInfo ri = new ResolveInfo(); 4607 ri.serviceInfo = si; 4608 list.add(ri); 4609 } 4610 return list; 4611 } 4612 4613 // reader 4614 synchronized (mPackages) { 4615 String pkgName = intent.getPackage(); 4616 if (pkgName == null) { 4617 return mServices.queryIntent(intent, resolvedType, flags, userId); 4618 } 4619 final PackageParser.Package pkg = mPackages.get(pkgName); 4620 if (pkg != null) { 4621 return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services, 4622 userId); 4623 } 4624 return null; 4625 } 4626 } 4627 4628 @Override 4629 public List<ResolveInfo> queryIntentContentProviders( 4630 Intent intent, String resolvedType, int flags, int userId) { 4631 if (!sUserManager.exists(userId)) return Collections.emptyList(); 4632 ComponentName comp = intent.getComponent(); 4633 if (comp == null) { 4634 if (intent.getSelector() != null) { 4635 intent = intent.getSelector(); 4636 comp = intent.getComponent(); 4637 } 4638 } 4639 if (comp != null) { 4640 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 4641 final ProviderInfo pi = getProviderInfo(comp, flags, userId); 4642 if (pi != null) { 4643 final ResolveInfo ri = new ResolveInfo(); 4644 ri.providerInfo = pi; 4645 list.add(ri); 4646 } 4647 return list; 4648 } 4649 4650 // reader 4651 synchronized (mPackages) { 4652 String pkgName = intent.getPackage(); 4653 if (pkgName == null) { 4654 return mProviders.queryIntent(intent, resolvedType, flags, userId); 4655 } 4656 final PackageParser.Package pkg = mPackages.get(pkgName); 4657 if (pkg != null) { 4658 return mProviders.queryIntentForPackage( 4659 intent, resolvedType, flags, pkg.providers, userId); 4660 } 4661 return null; 4662 } 4663 } 4664 4665 @Override 4666 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) { 4667 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 4668 4669 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "get installed packages"); 4670 4671 // writer 4672 synchronized (mPackages) { 4673 ArrayList<PackageInfo> list; 4674 if (listUninstalled) { 4675 list = new ArrayList<PackageInfo>(mSettings.mPackages.size()); 4676 for (PackageSetting ps : mSettings.mPackages.values()) { 4677 PackageInfo pi; 4678 if (ps.pkg != null) { 4679 pi = generatePackageInfo(ps.pkg, flags, userId); 4680 } else { 4681 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 4682 } 4683 if (pi != null) { 4684 list.add(pi); 4685 } 4686 } 4687 } else { 4688 list = new ArrayList<PackageInfo>(mPackages.size()); 4689 for (PackageParser.Package p : mPackages.values()) { 4690 PackageInfo pi = generatePackageInfo(p, flags, userId); 4691 if (pi != null) { 4692 list.add(pi); 4693 } 4694 } 4695 } 4696 4697 return new ParceledListSlice<PackageInfo>(list); 4698 } 4699 } 4700 4701 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps, 4702 String[] permissions, boolean[] tmp, int flags, int userId) { 4703 int numMatch = 0; 4704 final PermissionsState permissionsState = ps.getPermissionsState(); 4705 for (int i=0; i<permissions.length; i++) { 4706 final String permission = permissions[i]; 4707 if (permissionsState.hasPermission(permission, userId)) { 4708 tmp[i] = true; 4709 numMatch++; 4710 } else { 4711 tmp[i] = false; 4712 } 4713 } 4714 if (numMatch == 0) { 4715 return; 4716 } 4717 PackageInfo pi; 4718 if (ps.pkg != null) { 4719 pi = generatePackageInfo(ps.pkg, flags, userId); 4720 } else { 4721 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 4722 } 4723 // The above might return null in cases of uninstalled apps or install-state 4724 // skew across users/profiles. 4725 if (pi != null) { 4726 if ((flags&PackageManager.GET_PERMISSIONS) == 0) { 4727 if (numMatch == permissions.length) { 4728 pi.requestedPermissions = permissions; 4729 } else { 4730 pi.requestedPermissions = new String[numMatch]; 4731 numMatch = 0; 4732 for (int i=0; i<permissions.length; i++) { 4733 if (tmp[i]) { 4734 pi.requestedPermissions[numMatch] = permissions[i]; 4735 numMatch++; 4736 } 4737 } 4738 } 4739 } 4740 list.add(pi); 4741 } 4742 } 4743 4744 @Override 4745 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions( 4746 String[] permissions, int flags, int userId) { 4747 if (!sUserManager.exists(userId)) return null; 4748 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 4749 4750 // writer 4751 synchronized (mPackages) { 4752 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>(); 4753 boolean[] tmpBools = new boolean[permissions.length]; 4754 if (listUninstalled) { 4755 for (PackageSetting ps : mSettings.mPackages.values()) { 4756 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId); 4757 } 4758 } else { 4759 for (PackageParser.Package pkg : mPackages.values()) { 4760 PackageSetting ps = (PackageSetting)pkg.mExtras; 4761 if (ps != null) { 4762 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 4763 userId); 4764 } 4765 } 4766 } 4767 4768 return new ParceledListSlice<PackageInfo>(list); 4769 } 4770 } 4771 4772 @Override 4773 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) { 4774 if (!sUserManager.exists(userId)) return null; 4775 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 4776 4777 // writer 4778 synchronized (mPackages) { 4779 ArrayList<ApplicationInfo> list; 4780 if (listUninstalled) { 4781 list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size()); 4782 for (PackageSetting ps : mSettings.mPackages.values()) { 4783 ApplicationInfo ai; 4784 if (ps.pkg != null) { 4785 ai = PackageParser.generateApplicationInfo(ps.pkg, flags, 4786 ps.readUserState(userId), userId); 4787 } else { 4788 ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId); 4789 } 4790 if (ai != null) { 4791 list.add(ai); 4792 } 4793 } 4794 } else { 4795 list = new ArrayList<ApplicationInfo>(mPackages.size()); 4796 for (PackageParser.Package p : mPackages.values()) { 4797 if (p.mExtras != null) { 4798 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 4799 ((PackageSetting)p.mExtras).readUserState(userId), userId); 4800 if (ai != null) { 4801 list.add(ai); 4802 } 4803 } 4804 } 4805 } 4806 4807 return new ParceledListSlice<ApplicationInfo>(list); 4808 } 4809 } 4810 4811 public List<ApplicationInfo> getPersistentApplications(int flags) { 4812 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>(); 4813 4814 // reader 4815 synchronized (mPackages) { 4816 final Iterator<PackageParser.Package> i = mPackages.values().iterator(); 4817 final int userId = UserHandle.getCallingUserId(); 4818 while (i.hasNext()) { 4819 final PackageParser.Package p = i.next(); 4820 if (p.applicationInfo != null 4821 && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0 4822 && (!mSafeMode || isSystemApp(p))) { 4823 PackageSetting ps = mSettings.mPackages.get(p.packageName); 4824 if (ps != null) { 4825 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 4826 ps.readUserState(userId), userId); 4827 if (ai != null) { 4828 finalList.add(ai); 4829 } 4830 } 4831 } 4832 } 4833 } 4834 4835 return finalList; 4836 } 4837 4838 @Override 4839 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 4840 if (!sUserManager.exists(userId)) return null; 4841 // reader 4842 synchronized (mPackages) { 4843 final PackageParser.Provider provider = mProvidersByAuthority.get(name); 4844 PackageSetting ps = provider != null 4845 ? mSettings.mPackages.get(provider.owner.packageName) 4846 : null; 4847 return ps != null 4848 && mSettings.isEnabledLPr(provider.info, flags, userId) 4849 && (!mSafeMode || (provider.info.applicationInfo.flags 4850 &ApplicationInfo.FLAG_SYSTEM) != 0) 4851 ? PackageParser.generateProviderInfo(provider, flags, 4852 ps.readUserState(userId), userId) 4853 : null; 4854 } 4855 } 4856 4857 /** 4858 * @deprecated 4859 */ 4860 @Deprecated 4861 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) { 4862 // reader 4863 synchronized (mPackages) { 4864 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority 4865 .entrySet().iterator(); 4866 final int userId = UserHandle.getCallingUserId(); 4867 while (i.hasNext()) { 4868 Map.Entry<String, PackageParser.Provider> entry = i.next(); 4869 PackageParser.Provider p = entry.getValue(); 4870 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 4871 4872 if (ps != null && p.syncable 4873 && (!mSafeMode || (p.info.applicationInfo.flags 4874 &ApplicationInfo.FLAG_SYSTEM) != 0)) { 4875 ProviderInfo info = PackageParser.generateProviderInfo(p, 0, 4876 ps.readUserState(userId), userId); 4877 if (info != null) { 4878 outNames.add(entry.getKey()); 4879 outInfo.add(info); 4880 } 4881 } 4882 } 4883 } 4884 } 4885 4886 @Override 4887 public List<ProviderInfo> queryContentProviders(String processName, 4888 int uid, int flags) { 4889 ArrayList<ProviderInfo> finalList = null; 4890 // reader 4891 synchronized (mPackages) { 4892 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator(); 4893 final int userId = processName != null ? 4894 UserHandle.getUserId(uid) : UserHandle.getCallingUserId(); 4895 while (i.hasNext()) { 4896 final PackageParser.Provider p = i.next(); 4897 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 4898 if (ps != null && p.info.authority != null 4899 && (processName == null 4900 || (p.info.processName.equals(processName) 4901 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid))) 4902 && mSettings.isEnabledLPr(p.info, flags, userId) 4903 && (!mSafeMode 4904 || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) { 4905 if (finalList == null) { 4906 finalList = new ArrayList<ProviderInfo>(3); 4907 } 4908 ProviderInfo info = PackageParser.generateProviderInfo(p, flags, 4909 ps.readUserState(userId), userId); 4910 if (info != null) { 4911 finalList.add(info); 4912 } 4913 } 4914 } 4915 } 4916 4917 if (finalList != null) { 4918 Collections.sort(finalList, mProviderInitOrderSorter); 4919 } 4920 4921 return finalList; 4922 } 4923 4924 @Override 4925 public InstrumentationInfo getInstrumentationInfo(ComponentName name, 4926 int flags) { 4927 // reader 4928 synchronized (mPackages) { 4929 final PackageParser.Instrumentation i = mInstrumentation.get(name); 4930 return PackageParser.generateInstrumentationInfo(i, flags); 4931 } 4932 } 4933 4934 @Override 4935 public List<InstrumentationInfo> queryInstrumentation(String targetPackage, 4936 int flags) { 4937 ArrayList<InstrumentationInfo> finalList = 4938 new ArrayList<InstrumentationInfo>(); 4939 4940 // reader 4941 synchronized (mPackages) { 4942 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator(); 4943 while (i.hasNext()) { 4944 final PackageParser.Instrumentation p = i.next(); 4945 if (targetPackage == null 4946 || targetPackage.equals(p.info.targetPackage)) { 4947 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p, 4948 flags); 4949 if (ii != null) { 4950 finalList.add(ii); 4951 } 4952 } 4953 } 4954 } 4955 4956 return finalList; 4957 } 4958 4959 private void createIdmapsForPackageLI(PackageParser.Package pkg) { 4960 ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName); 4961 if (overlays == null) { 4962 Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages"); 4963 return; 4964 } 4965 for (PackageParser.Package opkg : overlays.values()) { 4966 // Not much to do if idmap fails: we already logged the error 4967 // and we certainly don't want to abort installation of pkg simply 4968 // because an overlay didn't fit properly. For these reasons, 4969 // ignore the return value of createIdmapForPackagePairLI. 4970 createIdmapForPackagePairLI(pkg, opkg); 4971 } 4972 } 4973 4974 private boolean createIdmapForPackagePairLI(PackageParser.Package pkg, 4975 PackageParser.Package opkg) { 4976 if (!opkg.mTrustedOverlay) { 4977 Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " + 4978 opkg.baseCodePath + ": overlay not trusted"); 4979 return false; 4980 } 4981 ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName); 4982 if (overlaySet == null) { 4983 Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " + 4984 opkg.baseCodePath + " but target package has no known overlays"); 4985 return false; 4986 } 4987 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 4988 // TODO: generate idmap for split APKs 4989 if (mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid) != 0) { 4990 Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and " 4991 + opkg.baseCodePath); 4992 return false; 4993 } 4994 PackageParser.Package[] overlayArray = 4995 overlaySet.values().toArray(new PackageParser.Package[0]); 4996 Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() { 4997 public int compare(PackageParser.Package p1, PackageParser.Package p2) { 4998 return p1.mOverlayPriority - p2.mOverlayPriority; 4999 } 5000 }; 5001 Arrays.sort(overlayArray, cmp); 5002 5003 pkg.applicationInfo.resourceDirs = new String[overlayArray.length]; 5004 int i = 0; 5005 for (PackageParser.Package p : overlayArray) { 5006 pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath; 5007 } 5008 return true; 5009 } 5010 5011 private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) { 5012 final File[] files = dir.listFiles(); 5013 if (ArrayUtils.isEmpty(files)) { 5014 Log.d(TAG, "No files in app dir " + dir); 5015 return; 5016 } 5017 5018 if (DEBUG_PACKAGE_SCANNING) { 5019 Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags 5020 + " flags=0x" + Integer.toHexString(parseFlags)); 5021 } 5022 5023 for (File file : files) { 5024 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 5025 && !PackageInstallerService.isStageName(file.getName()); 5026 if (!isPackage) { 5027 // Ignore entries which are not packages 5028 continue; 5029 } 5030 try { 5031 scanPackageLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK, 5032 scanFlags, currentTime, null); 5033 } catch (PackageManagerException e) { 5034 Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage(), e); 5035 5036 // Delete invalid userdata apps 5037 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 && 5038 e.error == PackageManager.INSTALL_FAILED_INVALID_APK) { 5039 logCriticalInfo(Log.WARN, "Deleting invalid package at " + file); 5040 if (file.isDirectory()) { 5041 mInstaller.rmPackageDir(file.getAbsolutePath()); 5042 } else { 5043 file.delete(); 5044 } 5045 } 5046 } 5047 } 5048 } 5049 5050 private static File getSettingsProblemFile() { 5051 File dataDir = Environment.getDataDirectory(); 5052 File systemDir = new File(dataDir, "system"); 5053 File fname = new File(systemDir, "uiderrors.txt"); 5054 return fname; 5055 } 5056 5057 static void reportSettingsProblem(int priority, String msg) { 5058 logCriticalInfo(priority, msg); 5059 } 5060 5061 static void logCriticalInfo(int priority, String msg) { 5062 Slog.println(priority, TAG, msg); 5063 EventLogTags.writePmCriticalInfo(msg); 5064 try { 5065 File fname = getSettingsProblemFile(); 5066 FileOutputStream out = new FileOutputStream(fname, true); 5067 PrintWriter pw = new FastPrintWriter(out); 5068 SimpleDateFormat formatter = new SimpleDateFormat(); 5069 String dateString = formatter.format(new Date(System.currentTimeMillis())); 5070 pw.println(dateString + ": " + msg); 5071 pw.close(); 5072 FileUtils.setPermissions( 5073 fname.toString(), 5074 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH, 5075 -1, -1); 5076 } catch (java.io.IOException e) { 5077 } 5078 } 5079 5080 private void collectCertificatesLI(PackageParser pp, PackageSetting ps, 5081 PackageParser.Package pkg, File srcFile, int parseFlags) 5082 throws PackageManagerException { 5083 if (ps != null 5084 && ps.codePath.equals(srcFile) 5085 && ps.timeStamp == srcFile.lastModified() 5086 && !isCompatSignatureUpdateNeeded(pkg) 5087 && !isRecoverSignatureUpdateNeeded(pkg)) { 5088 long mSigningKeySetId = ps.keySetData.getProperSigningKeySet(); 5089 if (ps.signatures.mSignatures != null 5090 && ps.signatures.mSignatures.length != 0 5091 && mSigningKeySetId != PackageKeySetData.KEYSET_UNASSIGNED) { 5092 // Optimization: reuse the existing cached certificates 5093 // if the package appears to be unchanged. 5094 pkg.mSignatures = ps.signatures.mSignatures; 5095 KeySetManagerService ksms = mSettings.mKeySetManagerService; 5096 synchronized (mPackages) { 5097 pkg.mSigningKeys = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId); 5098 } 5099 return; 5100 } 5101 5102 Slog.w(TAG, "PackageSetting for " + ps.name 5103 + " is missing signatures. Collecting certs again to recover them."); 5104 } else { 5105 Log.i(TAG, srcFile.toString() + " changed; collecting certs"); 5106 } 5107 5108 try { 5109 pp.collectCertificates(pkg, parseFlags); 5110 pp.collectManifestDigest(pkg); 5111 } catch (PackageParserException e) { 5112 throw PackageManagerException.from(e); 5113 } 5114 } 5115 5116 /* 5117 * Scan a package and return the newly parsed package. 5118 * Returns null in case of errors and the error code is stored in mLastScanError 5119 */ 5120 private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags, 5121 long currentTime, UserHandle user) throws PackageManagerException { 5122 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile); 5123 parseFlags |= mDefParseFlags; 5124 PackageParser pp = new PackageParser(); 5125 pp.setSeparateProcesses(mSeparateProcesses); 5126 pp.setOnlyCoreApps(mOnlyCore); 5127 pp.setDisplayMetrics(mMetrics); 5128 5129 if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) { 5130 parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY; 5131 } 5132 5133 final PackageParser.Package pkg; 5134 try { 5135 pkg = pp.parsePackage(scanFile, parseFlags); 5136 } catch (PackageParserException e) { 5137 throw PackageManagerException.from(e); 5138 } 5139 5140 PackageSetting ps = null; 5141 PackageSetting updatedPkg; 5142 // reader 5143 synchronized (mPackages) { 5144 // Look to see if we already know about this package. 5145 String oldName = mSettings.mRenamedPackages.get(pkg.packageName); 5146 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) { 5147 // This package has been renamed to its original name. Let's 5148 // use that. 5149 ps = mSettings.peekPackageLPr(oldName); 5150 } 5151 // If there was no original package, see one for the real package name. 5152 if (ps == null) { 5153 ps = mSettings.peekPackageLPr(pkg.packageName); 5154 } 5155 // Check to see if this package could be hiding/updating a system 5156 // package. Must look for it either under the original or real 5157 // package name depending on our state. 5158 updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName); 5159 if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg); 5160 } 5161 boolean updatedPkgBetter = false; 5162 // First check if this is a system package that may involve an update 5163 if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 5164 // If new package is not located in "/system/priv-app" (e.g. due to an OTA), 5165 // it needs to drop FLAG_PRIVILEGED. 5166 if (locationIsPrivileged(scanFile)) { 5167 updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 5168 } else { 5169 updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 5170 } 5171 5172 if (ps != null && !ps.codePath.equals(scanFile)) { 5173 // The path has changed from what was last scanned... check the 5174 // version of the new path against what we have stored to determine 5175 // what to do. 5176 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath); 5177 if (pkg.mVersionCode <= ps.versionCode) { 5178 // The system package has been updated and the code path does not match 5179 // Ignore entry. Skip it. 5180 Slog.i(TAG, "Package " + ps.name + " at " + scanFile 5181 + " ignored: updated version " + ps.versionCode 5182 + " better than this " + pkg.mVersionCode); 5183 if (!updatedPkg.codePath.equals(scanFile)) { 5184 Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : " 5185 + ps.name + " changing from " + updatedPkg.codePathString 5186 + " to " + scanFile); 5187 updatedPkg.codePath = scanFile; 5188 updatedPkg.codePathString = scanFile.toString(); 5189 updatedPkg.resourcePath = scanFile; 5190 updatedPkg.resourcePathString = scanFile.toString(); 5191 } 5192 updatedPkg.pkg = pkg; 5193 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, null); 5194 } else { 5195 // The current app on the system partition is better than 5196 // what we have updated to on the data partition; switch 5197 // back to the system partition version. 5198 // At this point, its safely assumed that package installation for 5199 // apps in system partition will go through. If not there won't be a working 5200 // version of the app 5201 // writer 5202 synchronized (mPackages) { 5203 // Just remove the loaded entries from package lists. 5204 mPackages.remove(ps.name); 5205 } 5206 5207 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 5208 + " reverting from " + ps.codePathString 5209 + ": new version " + pkg.mVersionCode 5210 + " better than installed " + ps.versionCode); 5211 5212 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 5213 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 5214 synchronized (mInstallLock) { 5215 args.cleanUpResourcesLI(); 5216 } 5217 synchronized (mPackages) { 5218 mSettings.enableSystemPackageLPw(ps.name); 5219 } 5220 updatedPkgBetter = true; 5221 } 5222 } 5223 } 5224 5225 if (updatedPkg != null) { 5226 // An updated system app will not have the PARSE_IS_SYSTEM flag set 5227 // initially 5228 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 5229 5230 // An updated privileged app will not have the PARSE_IS_PRIVILEGED 5231 // flag set initially 5232 if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) { 5233 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 5234 } 5235 } 5236 5237 // Verify certificates against what was last scanned 5238 collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags); 5239 5240 /* 5241 * A new system app appeared, but we already had a non-system one of the 5242 * same name installed earlier. 5243 */ 5244 boolean shouldHideSystemApp = false; 5245 if (updatedPkg == null && ps != null 5246 && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) { 5247 /* 5248 * Check to make sure the signatures match first. If they don't, 5249 * wipe the installed application and its data. 5250 */ 5251 if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures) 5252 != PackageManager.SIGNATURE_MATCH) { 5253 logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but" 5254 + " signatures don't match existing userdata copy; removing"); 5255 deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false); 5256 ps = null; 5257 } else { 5258 /* 5259 * If the newly-added system app is an older version than the 5260 * already installed version, hide it. It will be scanned later 5261 * and re-added like an update. 5262 */ 5263 if (pkg.mVersionCode <= ps.versionCode) { 5264 shouldHideSystemApp = true; 5265 logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile 5266 + " but new version " + pkg.mVersionCode + " better than installed " 5267 + ps.versionCode + "; hiding system"); 5268 } else { 5269 /* 5270 * The newly found system app is a newer version that the 5271 * one previously installed. Simply remove the 5272 * already-installed application and replace it with our own 5273 * while keeping the application data. 5274 */ 5275 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 5276 + " reverting from " + ps.codePathString + ": new version " 5277 + pkg.mVersionCode + " better than installed " + ps.versionCode); 5278 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 5279 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 5280 synchronized (mInstallLock) { 5281 args.cleanUpResourcesLI(); 5282 } 5283 } 5284 } 5285 } 5286 5287 // The apk is forward locked (not public) if its code and resources 5288 // are kept in different files. (except for app in either system or 5289 // vendor path). 5290 // TODO grab this value from PackageSettings 5291 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 5292 if (ps != null && !ps.codePath.equals(ps.resourcePath)) { 5293 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 5294 } 5295 } 5296 5297 // TODO: extend to support forward-locked splits 5298 String resourcePath = null; 5299 String baseResourcePath = null; 5300 if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) { 5301 if (ps != null && ps.resourcePathString != null) { 5302 resourcePath = ps.resourcePathString; 5303 baseResourcePath = ps.resourcePathString; 5304 } else { 5305 // Should not happen at all. Just log an error. 5306 Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName); 5307 } 5308 } else { 5309 resourcePath = pkg.codePath; 5310 baseResourcePath = pkg.baseCodePath; 5311 } 5312 5313 // Set application objects path explicitly. 5314 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 5315 pkg.applicationInfo.setCodePath(pkg.codePath); 5316 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 5317 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 5318 pkg.applicationInfo.setResourcePath(resourcePath); 5319 pkg.applicationInfo.setBaseResourcePath(baseResourcePath); 5320 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 5321 5322 // Note that we invoke the following method only if we are about to unpack an application 5323 PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags 5324 | SCAN_UPDATE_SIGNATURE, currentTime, user); 5325 5326 /* 5327 * If the system app should be overridden by a previously installed 5328 * data, hide the system app now and let the /data/app scan pick it up 5329 * again. 5330 */ 5331 if (shouldHideSystemApp) { 5332 synchronized (mPackages) { 5333 /* 5334 * We have to grant systems permissions before we hide, because 5335 * grantPermissions will assume the package update is trying to 5336 * expand its permissions. 5337 */ 5338 grantPermissionsLPw(pkg, true, pkg.packageName); 5339 mSettings.disableSystemPackageLPw(pkg.packageName); 5340 } 5341 } 5342 5343 return scannedPkg; 5344 } 5345 5346 private static String fixProcessName(String defProcessName, 5347 String processName, int uid) { 5348 if (processName == null) { 5349 return defProcessName; 5350 } 5351 return processName; 5352 } 5353 5354 private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg) 5355 throws PackageManagerException { 5356 if (pkgSetting.signatures.mSignatures != null) { 5357 // Already existing package. Make sure signatures match 5358 boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures) 5359 == PackageManager.SIGNATURE_MATCH; 5360 if (!match) { 5361 match = compareSignaturesCompat(pkgSetting.signatures, pkg) 5362 == PackageManager.SIGNATURE_MATCH; 5363 } 5364 if (!match) { 5365 match = compareSignaturesRecover(pkgSetting.signatures, pkg) 5366 == PackageManager.SIGNATURE_MATCH; 5367 } 5368 if (!match) { 5369 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 5370 + pkg.packageName + " signatures do not match the " 5371 + "previously installed version; ignoring!"); 5372 } 5373 } 5374 5375 // Check for shared user signatures 5376 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) { 5377 // Already existing package. Make sure signatures match 5378 boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 5379 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 5380 if (!match) { 5381 match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg) 5382 == PackageManager.SIGNATURE_MATCH; 5383 } 5384 if (!match) { 5385 match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg) 5386 == PackageManager.SIGNATURE_MATCH; 5387 } 5388 if (!match) { 5389 throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 5390 "Package " + pkg.packageName 5391 + " has no signatures that match those in shared user " 5392 + pkgSetting.sharedUser.name + "; ignoring!"); 5393 } 5394 } 5395 } 5396 5397 /** 5398 * Enforces that only the system UID or root's UID can call a method exposed 5399 * via Binder. 5400 * 5401 * @param message used as message if SecurityException is thrown 5402 * @throws SecurityException if the caller is not system or root 5403 */ 5404 private static final void enforceSystemOrRoot(String message) { 5405 final int uid = Binder.getCallingUid(); 5406 if (uid != Process.SYSTEM_UID && uid != 0) { 5407 throw new SecurityException(message); 5408 } 5409 } 5410 5411 @Override 5412 public void performBootDexOpt() { 5413 enforceSystemOrRoot("Only the system can request dexopt be performed"); 5414 5415 // Before everything else, see whether we need to fstrim. 5416 try { 5417 IMountService ms = PackageHelper.getMountService(); 5418 if (ms != null) { 5419 final boolean isUpgrade = isUpgrade(); 5420 boolean doTrim = isUpgrade; 5421 if (doTrim) { 5422 Slog.w(TAG, "Running disk maintenance immediately due to system update"); 5423 } else { 5424 final long interval = android.provider.Settings.Global.getLong( 5425 mContext.getContentResolver(), 5426 android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL, 5427 DEFAULT_MANDATORY_FSTRIM_INTERVAL); 5428 if (interval > 0) { 5429 final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance(); 5430 if (timeSinceLast > interval) { 5431 doTrim = true; 5432 Slog.w(TAG, "No disk maintenance in " + timeSinceLast 5433 + "; running immediately"); 5434 } 5435 } 5436 } 5437 if (doTrim) { 5438 if (!isFirstBoot()) { 5439 try { 5440 ActivityManagerNative.getDefault().showBootMessage( 5441 mContext.getResources().getString( 5442 R.string.android_upgrading_fstrim), true); 5443 } catch (RemoteException e) { 5444 } 5445 } 5446 ms.runMaintenance(); 5447 } 5448 } else { 5449 Slog.e(TAG, "Mount service unavailable!"); 5450 } 5451 } catch (RemoteException e) { 5452 // Can't happen; MountService is local 5453 } 5454 5455 final ArraySet<PackageParser.Package> pkgs; 5456 synchronized (mPackages) { 5457 pkgs = mPackageDexOptimizer.clearDeferredDexOptPackages(); 5458 } 5459 5460 if (pkgs != null) { 5461 // Sort apps by importance for dexopt ordering. Important apps are given more priority 5462 // in case the device runs out of space. 5463 ArrayList<PackageParser.Package> sortedPkgs = new ArrayList<PackageParser.Package>(); 5464 // Give priority to core apps. 5465 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 5466 PackageParser.Package pkg = it.next(); 5467 if (pkg.coreApp) { 5468 if (DEBUG_DEXOPT) { 5469 Log.i(TAG, "Adding core app " + sortedPkgs.size() + ": " + pkg.packageName); 5470 } 5471 sortedPkgs.add(pkg); 5472 it.remove(); 5473 } 5474 } 5475 // Give priority to system apps that listen for pre boot complete. 5476 Intent intent = new Intent(Intent.ACTION_PRE_BOOT_COMPLETED); 5477 ArraySet<String> pkgNames = getPackageNamesForIntent(intent); 5478 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 5479 PackageParser.Package pkg = it.next(); 5480 if (pkgNames.contains(pkg.packageName)) { 5481 if (DEBUG_DEXOPT) { 5482 Log.i(TAG, "Adding pre boot system app " + sortedPkgs.size() + ": " + pkg.packageName); 5483 } 5484 sortedPkgs.add(pkg); 5485 it.remove(); 5486 } 5487 } 5488 // Give priority to system apps. 5489 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 5490 PackageParser.Package pkg = it.next(); 5491 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) { 5492 if (DEBUG_DEXOPT) { 5493 Log.i(TAG, "Adding system app " + sortedPkgs.size() + ": " + pkg.packageName); 5494 } 5495 sortedPkgs.add(pkg); 5496 it.remove(); 5497 } 5498 } 5499 // Give priority to updated system apps. 5500 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 5501 PackageParser.Package pkg = it.next(); 5502 if (pkg.isUpdatedSystemApp()) { 5503 if (DEBUG_DEXOPT) { 5504 Log.i(TAG, "Adding updated system app " + sortedPkgs.size() + ": " + pkg.packageName); 5505 } 5506 sortedPkgs.add(pkg); 5507 it.remove(); 5508 } 5509 } 5510 // Give priority to apps that listen for boot complete. 5511 intent = new Intent(Intent.ACTION_BOOT_COMPLETED); 5512 pkgNames = getPackageNamesForIntent(intent); 5513 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 5514 PackageParser.Package pkg = it.next(); 5515 if (pkgNames.contains(pkg.packageName)) { 5516 if (DEBUG_DEXOPT) { 5517 Log.i(TAG, "Adding boot app " + sortedPkgs.size() + ": " + pkg.packageName); 5518 } 5519 sortedPkgs.add(pkg); 5520 it.remove(); 5521 } 5522 } 5523 // Filter out packages that aren't recently used. 5524 filterRecentlyUsedApps(pkgs); 5525 // Add all remaining apps. 5526 for (PackageParser.Package pkg : pkgs) { 5527 if (DEBUG_DEXOPT) { 5528 Log.i(TAG, "Adding app " + sortedPkgs.size() + ": " + pkg.packageName); 5529 } 5530 sortedPkgs.add(pkg); 5531 } 5532 5533 // If we want to be lazy, filter everything that wasn't recently used. 5534 if (mLazyDexOpt) { 5535 filterRecentlyUsedApps(sortedPkgs); 5536 } 5537 5538 int i = 0; 5539 int total = sortedPkgs.size(); 5540 File dataDir = Environment.getDataDirectory(); 5541 long lowThreshold = StorageManager.from(mContext).getStorageLowBytes(dataDir); 5542 if (lowThreshold == 0) { 5543 throw new IllegalStateException("Invalid low memory threshold"); 5544 } 5545 for (PackageParser.Package pkg : sortedPkgs) { 5546 long usableSpace = dataDir.getUsableSpace(); 5547 if (usableSpace < lowThreshold) { 5548 Log.w(TAG, "Not running dexopt on remaining apps due to low memory: " + usableSpace); 5549 break; 5550 } 5551 performBootDexOpt(pkg, ++i, total); 5552 } 5553 } 5554 } 5555 5556 private void filterRecentlyUsedApps(Collection<PackageParser.Package> pkgs) { 5557 // Filter out packages that aren't recently used. 5558 // 5559 // The exception is first boot of a non-eng device (aka !mLazyDexOpt), which 5560 // should do a full dexopt. 5561 if (mLazyDexOpt || (!isFirstBoot() && mPackageUsage.isHistoricalPackageUsageAvailable())) { 5562 int total = pkgs.size(); 5563 int skipped = 0; 5564 long now = System.currentTimeMillis(); 5565 for (Iterator<PackageParser.Package> i = pkgs.iterator(); i.hasNext();) { 5566 PackageParser.Package pkg = i.next(); 5567 long then = pkg.mLastPackageUsageTimeInMills; 5568 if (then + mDexOptLRUThresholdInMills < now) { 5569 if (DEBUG_DEXOPT) { 5570 Log.i(TAG, "Skipping dexopt of " + pkg.packageName + " last resumed: " + 5571 ((then == 0) ? "never" : new Date(then))); 5572 } 5573 i.remove(); 5574 skipped++; 5575 } 5576 } 5577 if (DEBUG_DEXOPT) { 5578 Log.i(TAG, "Skipped optimizing " + skipped + " of " + total); 5579 } 5580 } 5581 } 5582 5583 private ArraySet<String> getPackageNamesForIntent(Intent intent) { 5584 List<ResolveInfo> ris = null; 5585 try { 5586 ris = AppGlobals.getPackageManager().queryIntentReceivers( 5587 intent, null, 0, UserHandle.USER_OWNER); 5588 } catch (RemoteException e) { 5589 } 5590 ArraySet<String> pkgNames = new ArraySet<String>(); 5591 if (ris != null) { 5592 for (ResolveInfo ri : ris) { 5593 pkgNames.add(ri.activityInfo.packageName); 5594 } 5595 } 5596 return pkgNames; 5597 } 5598 5599 private void performBootDexOpt(PackageParser.Package pkg, int curr, int total) { 5600 if (DEBUG_DEXOPT) { 5601 Log.i(TAG, "Optimizing app " + curr + " of " + total + ": " + pkg.packageName); 5602 } 5603 if (!isFirstBoot()) { 5604 try { 5605 ActivityManagerNative.getDefault().showBootMessage( 5606 mContext.getResources().getString(R.string.android_upgrading_apk, 5607 curr, total), true); 5608 } catch (RemoteException e) { 5609 } 5610 } 5611 PackageParser.Package p = pkg; 5612 synchronized (mInstallLock) { 5613 mPackageDexOptimizer.performDexOpt(p, null /* instruction sets */, 5614 false /* force dex */, false /* defer */, true /* include dependencies */); 5615 } 5616 } 5617 5618 @Override 5619 public boolean performDexOptIfNeeded(String packageName, String instructionSet) { 5620 return performDexOpt(packageName, instructionSet, false); 5621 } 5622 5623 public boolean performDexOpt(String packageName, String instructionSet, boolean backgroundDexopt) { 5624 boolean dexopt = mLazyDexOpt || backgroundDexopt; 5625 boolean updateUsage = !backgroundDexopt; // Don't update usage if this is just a backgroundDexopt 5626 if (!dexopt && !updateUsage) { 5627 // We aren't going to dexopt or update usage, so bail early. 5628 return false; 5629 } 5630 PackageParser.Package p; 5631 final String targetInstructionSet; 5632 synchronized (mPackages) { 5633 p = mPackages.get(packageName); 5634 if (p == null) { 5635 return false; 5636 } 5637 if (updateUsage) { 5638 p.mLastPackageUsageTimeInMills = System.currentTimeMillis(); 5639 } 5640 mPackageUsage.write(false); 5641 if (!dexopt) { 5642 // We aren't going to dexopt, so bail early. 5643 return false; 5644 } 5645 5646 targetInstructionSet = instructionSet != null ? instructionSet : 5647 getPrimaryInstructionSet(p.applicationInfo); 5648 if (p.mDexOptPerformed.contains(targetInstructionSet)) { 5649 return false; 5650 } 5651 } 5652 5653 synchronized (mInstallLock) { 5654 final String[] instructionSets = new String[] { targetInstructionSet }; 5655 int result = mPackageDexOptimizer.performDexOpt(p, instructionSets, 5656 false /* forceDex */, false /* defer */, true /* inclDependencies */); 5657 return result == PackageDexOptimizer.DEX_OPT_PERFORMED; 5658 } 5659 } 5660 5661 public ArraySet<String> getPackagesThatNeedDexOpt() { 5662 ArraySet<String> pkgs = null; 5663 synchronized (mPackages) { 5664 for (PackageParser.Package p : mPackages.values()) { 5665 if (DEBUG_DEXOPT) { 5666 Log.i(TAG, p.packageName + " mDexOptPerformed=" + p.mDexOptPerformed.toArray()); 5667 } 5668 if (!p.mDexOptPerformed.isEmpty()) { 5669 continue; 5670 } 5671 if (pkgs == null) { 5672 pkgs = new ArraySet<String>(); 5673 } 5674 pkgs.add(p.packageName); 5675 } 5676 } 5677 return pkgs; 5678 } 5679 5680 public void shutdown() { 5681 mPackageUsage.write(true); 5682 } 5683 5684 @Override 5685 public void forceDexOpt(String packageName) { 5686 enforceSystemOrRoot("forceDexOpt"); 5687 5688 PackageParser.Package pkg; 5689 synchronized (mPackages) { 5690 pkg = mPackages.get(packageName); 5691 if (pkg == null) { 5692 throw new IllegalArgumentException("Missing package: " + packageName); 5693 } 5694 } 5695 5696 synchronized (mInstallLock) { 5697 final String[] instructionSets = new String[] { 5698 getPrimaryInstructionSet(pkg.applicationInfo) }; 5699 final int res = mPackageDexOptimizer.performDexOpt(pkg, instructionSets, 5700 true /*forceDex*/, false /* defer */, true /* inclDependencies */); 5701 if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) { 5702 throw new IllegalStateException("Failed to dexopt: " + res); 5703 } 5704 } 5705 } 5706 5707 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 5708 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 5709 Slog.w(TAG, "Unable to update from " + oldPkg.name 5710 + " to " + newPkg.packageName 5711 + ": old package not in system partition"); 5712 return false; 5713 } else if (mPackages.get(oldPkg.name) != null) { 5714 Slog.w(TAG, "Unable to update from " + oldPkg.name 5715 + " to " + newPkg.packageName 5716 + ": old package still exists"); 5717 return false; 5718 } 5719 return true; 5720 } 5721 5722 private int createDataDirsLI(String volumeUuid, String packageName, int uid, String seinfo) { 5723 int[] users = sUserManager.getUserIds(); 5724 int res = mInstaller.install(volumeUuid, packageName, uid, uid, seinfo); 5725 if (res < 0) { 5726 return res; 5727 } 5728 for (int user : users) { 5729 if (user != 0) { 5730 res = mInstaller.createUserData(volumeUuid, packageName, 5731 UserHandle.getUid(user, uid), user, seinfo); 5732 if (res < 0) { 5733 return res; 5734 } 5735 } 5736 } 5737 return res; 5738 } 5739 5740 private int removeDataDirsLI(String volumeUuid, String packageName) { 5741 int[] users = sUserManager.getUserIds(); 5742 int res = 0; 5743 for (int user : users) { 5744 int resInner = mInstaller.remove(volumeUuid, packageName, user); 5745 if (resInner < 0) { 5746 res = resInner; 5747 } 5748 } 5749 5750 return res; 5751 } 5752 5753 private int deleteCodeCacheDirsLI(String volumeUuid, String packageName) { 5754 int[] users = sUserManager.getUserIds(); 5755 int res = 0; 5756 for (int user : users) { 5757 int resInner = mInstaller.deleteCodeCacheFiles(volumeUuid, packageName, user); 5758 if (resInner < 0) { 5759 res = resInner; 5760 } 5761 } 5762 return res; 5763 } 5764 5765 private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file, 5766 PackageParser.Package changingLib) { 5767 if (file.path != null) { 5768 usesLibraryFiles.add(file.path); 5769 return; 5770 } 5771 PackageParser.Package p = mPackages.get(file.apk); 5772 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 5773 // If we are doing this while in the middle of updating a library apk, 5774 // then we need to make sure to use that new apk for determining the 5775 // dependencies here. (We haven't yet finished committing the new apk 5776 // to the package manager state.) 5777 if (p == null || p.packageName.equals(changingLib.packageName)) { 5778 p = changingLib; 5779 } 5780 } 5781 if (p != null) { 5782 usesLibraryFiles.addAll(p.getAllCodePaths()); 5783 } 5784 } 5785 5786 private void updateSharedLibrariesLPw(PackageParser.Package pkg, 5787 PackageParser.Package changingLib) throws PackageManagerException { 5788 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) { 5789 final ArraySet<String> usesLibraryFiles = new ArraySet<>(); 5790 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0; 5791 for (int i=0; i<N; i++) { 5792 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i)); 5793 if (file == null) { 5794 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 5795 "Package " + pkg.packageName + " requires unavailable shared library " 5796 + pkg.usesLibraries.get(i) + "; failing!"); 5797 } 5798 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 5799 } 5800 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0; 5801 for (int i=0; i<N; i++) { 5802 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i)); 5803 if (file == null) { 5804 Slog.w(TAG, "Package " + pkg.packageName 5805 + " desires unavailable shared library " 5806 + pkg.usesOptionalLibraries.get(i) + "; ignoring!"); 5807 } else { 5808 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 5809 } 5810 } 5811 N = usesLibraryFiles.size(); 5812 if (N > 0) { 5813 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]); 5814 } else { 5815 pkg.usesLibraryFiles = null; 5816 } 5817 } 5818 } 5819 5820 private static boolean hasString(List<String> list, List<String> which) { 5821 if (list == null) { 5822 return false; 5823 } 5824 for (int i=list.size()-1; i>=0; i--) { 5825 for (int j=which.size()-1; j>=0; j--) { 5826 if (which.get(j).equals(list.get(i))) { 5827 return true; 5828 } 5829 } 5830 } 5831 return false; 5832 } 5833 5834 private void updateAllSharedLibrariesLPw() { 5835 for (PackageParser.Package pkg : mPackages.values()) { 5836 try { 5837 updateSharedLibrariesLPw(pkg, null); 5838 } catch (PackageManagerException e) { 5839 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 5840 } 5841 } 5842 } 5843 5844 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 5845 PackageParser.Package changingPkg) { 5846 ArrayList<PackageParser.Package> res = null; 5847 for (PackageParser.Package pkg : mPackages.values()) { 5848 if (hasString(pkg.usesLibraries, changingPkg.libraryNames) 5849 || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) { 5850 if (res == null) { 5851 res = new ArrayList<PackageParser.Package>(); 5852 } 5853 res.add(pkg); 5854 try { 5855 updateSharedLibrariesLPw(pkg, changingPkg); 5856 } catch (PackageManagerException e) { 5857 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 5858 } 5859 } 5860 } 5861 return res; 5862 } 5863 5864 /** 5865 * Derive the value of the {@code cpuAbiOverride} based on the provided 5866 * value and an optional stored value from the package settings. 5867 */ 5868 private static String deriveAbiOverride(String abiOverride, PackageSetting settings) { 5869 String cpuAbiOverride = null; 5870 5871 if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) { 5872 cpuAbiOverride = null; 5873 } else if (abiOverride != null) { 5874 cpuAbiOverride = abiOverride; 5875 } else if (settings != null) { 5876 cpuAbiOverride = settings.cpuAbiOverrideString; 5877 } 5878 5879 return cpuAbiOverride; 5880 } 5881 5882 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags, 5883 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 5884 boolean success = false; 5885 try { 5886 final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags, 5887 currentTime, user); 5888 success = true; 5889 return res; 5890 } finally { 5891 if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 5892 removeDataDirsLI(pkg.volumeUuid, pkg.packageName); 5893 } 5894 } 5895 } 5896 5897 private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags, 5898 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 5899 final File scanFile = new File(pkg.codePath); 5900 if (pkg.applicationInfo.getCodePath() == null || 5901 pkg.applicationInfo.getResourcePath() == null) { 5902 // Bail out. The resource and code paths haven't been set. 5903 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 5904 "Code and resource paths haven't been set correctly"); 5905 } 5906 5907 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 5908 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 5909 } else { 5910 // Only allow system apps to be flagged as core apps. 5911 pkg.coreApp = false; 5912 } 5913 5914 if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) { 5915 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 5916 } 5917 5918 if (mCustomResolverComponentName != null && 5919 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 5920 setUpCustomResolverActivity(pkg); 5921 } 5922 5923 if (pkg.packageName.equals("android")) { 5924 synchronized (mPackages) { 5925 if (mAndroidApplication != null) { 5926 Slog.w(TAG, "*************************************************"); 5927 Slog.w(TAG, "Core android package being redefined. Skipping."); 5928 Slog.w(TAG, " file=" + scanFile); 5929 Slog.w(TAG, "*************************************************"); 5930 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 5931 "Core android package being redefined. Skipping."); 5932 } 5933 5934 // Set up information for our fall-back user intent resolution activity. 5935 mPlatformPackage = pkg; 5936 pkg.mVersionCode = mSdkVersion; 5937 mAndroidApplication = pkg.applicationInfo; 5938 5939 if (!mResolverReplaced) { 5940 mResolveActivity.applicationInfo = mAndroidApplication; 5941 mResolveActivity.name = ResolverActivity.class.getName(); 5942 mResolveActivity.packageName = mAndroidApplication.packageName; 5943 mResolveActivity.processName = "system:ui"; 5944 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 5945 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 5946 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 5947 mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert; 5948 mResolveActivity.exported = true; 5949 mResolveActivity.enabled = true; 5950 mResolveInfo.activityInfo = mResolveActivity; 5951 mResolveInfo.priority = 0; 5952 mResolveInfo.preferredOrder = 0; 5953 mResolveInfo.match = 0; 5954 mResolveComponentName = new ComponentName( 5955 mAndroidApplication.packageName, mResolveActivity.name); 5956 } 5957 } 5958 } 5959 5960 if (DEBUG_PACKAGE_SCANNING) { 5961 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 5962 Log.d(TAG, "Scanning package " + pkg.packageName); 5963 } 5964 5965 if (mPackages.containsKey(pkg.packageName) 5966 || mSharedLibraries.containsKey(pkg.packageName)) { 5967 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 5968 "Application package " + pkg.packageName 5969 + " already installed. Skipping duplicate."); 5970 } 5971 5972 // If we're only installing presumed-existing packages, require that the 5973 // scanned APK is both already known and at the path previously established 5974 // for it. Previously unknown packages we pick up normally, but if we have an 5975 // a priori expectation about this package's install presence, enforce it. 5976 if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) { 5977 PackageSetting known = mSettings.peekPackageLPr(pkg.packageName); 5978 if (known != null) { 5979 if (DEBUG_PACKAGE_SCANNING) { 5980 Log.d(TAG, "Examining " + pkg.codePath 5981 + " and requiring known paths " + known.codePathString 5982 + " & " + known.resourcePathString); 5983 } 5984 if (!pkg.applicationInfo.getCodePath().equals(known.codePathString) 5985 || !pkg.applicationInfo.getResourcePath().equals(known.resourcePathString)) { 5986 throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED, 5987 "Application package " + pkg.packageName 5988 + " found at " + pkg.applicationInfo.getCodePath() 5989 + " but expected at " + known.codePathString + "; ignoring."); 5990 } 5991 } 5992 } 5993 5994 // Initialize package source and resource directories 5995 File destCodeFile = new File(pkg.applicationInfo.getCodePath()); 5996 File destResourceFile = new File(pkg.applicationInfo.getResourcePath()); 5997 5998 SharedUserSetting suid = null; 5999 PackageSetting pkgSetting = null; 6000 6001 if (!isSystemApp(pkg)) { 6002 // Only system apps can use these features. 6003 pkg.mOriginalPackages = null; 6004 pkg.mRealPackage = null; 6005 pkg.mAdoptPermissions = null; 6006 } 6007 6008 // writer 6009 synchronized (mPackages) { 6010 if (pkg.mSharedUserId != null) { 6011 suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true); 6012 if (suid == null) { 6013 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 6014 "Creating application package " + pkg.packageName 6015 + " for shared user failed"); 6016 } 6017 if (DEBUG_PACKAGE_SCANNING) { 6018 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 6019 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId 6020 + "): packages=" + suid.packages); 6021 } 6022 } 6023 6024 // Check if we are renaming from an original package name. 6025 PackageSetting origPackage = null; 6026 String realName = null; 6027 if (pkg.mOriginalPackages != null) { 6028 // This package may need to be renamed to a previously 6029 // installed name. Let's check on that... 6030 final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage); 6031 if (pkg.mOriginalPackages.contains(renamed)) { 6032 // This package had originally been installed as the 6033 // original name, and we have already taken care of 6034 // transitioning to the new one. Just update the new 6035 // one to continue using the old name. 6036 realName = pkg.mRealPackage; 6037 if (!pkg.packageName.equals(renamed)) { 6038 // Callers into this function may have already taken 6039 // care of renaming the package; only do it here if 6040 // it is not already done. 6041 pkg.setPackageName(renamed); 6042 } 6043 6044 } else { 6045 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) { 6046 if ((origPackage = mSettings.peekPackageLPr( 6047 pkg.mOriginalPackages.get(i))) != null) { 6048 // We do have the package already installed under its 6049 // original name... should we use it? 6050 if (!verifyPackageUpdateLPr(origPackage, pkg)) { 6051 // New package is not compatible with original. 6052 origPackage = null; 6053 continue; 6054 } else if (origPackage.sharedUser != null) { 6055 // Make sure uid is compatible between packages. 6056 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) { 6057 Slog.w(TAG, "Unable to migrate data from " + origPackage.name 6058 + " to " + pkg.packageName + ": old uid " 6059 + origPackage.sharedUser.name 6060 + " differs from " + pkg.mSharedUserId); 6061 origPackage = null; 6062 continue; 6063 } 6064 } else { 6065 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 6066 + pkg.packageName + " to old name " + origPackage.name); 6067 } 6068 break; 6069 } 6070 } 6071 } 6072 } 6073 6074 if (mTransferedPackages.contains(pkg.packageName)) { 6075 Slog.w(TAG, "Package " + pkg.packageName 6076 + " was transferred to another, but its .apk remains"); 6077 } 6078 6079 // Just create the setting, don't add it yet. For already existing packages 6080 // the PkgSetting exists already and doesn't have to be created. 6081 pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile, 6082 destResourceFile, pkg.applicationInfo.nativeLibraryRootDir, 6083 pkg.applicationInfo.primaryCpuAbi, 6084 pkg.applicationInfo.secondaryCpuAbi, 6085 pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, 6086 user, false); 6087 if (pkgSetting == null) { 6088 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 6089 "Creating application package " + pkg.packageName + " failed"); 6090 } 6091 6092 if (pkgSetting.origPackage != null) { 6093 // If we are first transitioning from an original package, 6094 // fix up the new package's name now. We need to do this after 6095 // looking up the package under its new name, so getPackageLP 6096 // can take care of fiddling things correctly. 6097 pkg.setPackageName(origPackage.name); 6098 6099 // File a report about this. 6100 String msg = "New package " + pkgSetting.realName 6101 + " renamed to replace old package " + pkgSetting.name; 6102 reportSettingsProblem(Log.WARN, msg); 6103 6104 // Make a note of it. 6105 mTransferedPackages.add(origPackage.name); 6106 6107 // No longer need to retain this. 6108 pkgSetting.origPackage = null; 6109 } 6110 6111 if (realName != null) { 6112 // Make a note of it. 6113 mTransferedPackages.add(pkg.packageName); 6114 } 6115 6116 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) { 6117 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 6118 } 6119 6120 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 6121 // Check all shared libraries and map to their actual file path. 6122 // We only do this here for apps not on a system dir, because those 6123 // are the only ones that can fail an install due to this. We 6124 // will take care of the system apps by updating all of their 6125 // library paths after the scan is done. 6126 updateSharedLibrariesLPw(pkg, null); 6127 } 6128 6129 if (mFoundPolicyFile) { 6130 SELinuxMMAC.assignSeinfoValue(pkg); 6131 } 6132 6133 pkg.applicationInfo.uid = pkgSetting.appId; 6134 pkg.mExtras = pkgSetting; 6135 if (!pkgSetting.keySetData.isUsingUpgradeKeySets() || pkgSetting.sharedUser != null) { 6136 try { 6137 verifySignaturesLP(pkgSetting, pkg); 6138 // We just determined the app is signed correctly, so bring 6139 // over the latest parsed certs. 6140 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6141 } catch (PackageManagerException e) { 6142 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 6143 throw e; 6144 } 6145 // The signature has changed, but this package is in the system 6146 // image... let's recover! 6147 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6148 // However... if this package is part of a shared user, but it 6149 // doesn't match the signature of the shared user, let's fail. 6150 // What this means is that you can't change the signatures 6151 // associated with an overall shared user, which doesn't seem all 6152 // that unreasonable. 6153 if (pkgSetting.sharedUser != null) { 6154 if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 6155 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 6156 throw new PackageManagerException( 6157 INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 6158 "Signature mismatch for shared user : " 6159 + pkgSetting.sharedUser); 6160 } 6161 } 6162 // File a report about this. 6163 String msg = "System package " + pkg.packageName 6164 + " signature changed; retaining data."; 6165 reportSettingsProblem(Log.WARN, msg); 6166 } 6167 } else { 6168 if (!checkUpgradeKeySetLP(pkgSetting, pkg)) { 6169 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 6170 + pkg.packageName + " upgrade keys do not match the " 6171 + "previously installed version"); 6172 } else { 6173 // We just determined the app is signed correctly, so bring 6174 // over the latest parsed certs. 6175 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6176 } 6177 } 6178 // Verify that this new package doesn't have any content providers 6179 // that conflict with existing packages. Only do this if the 6180 // package isn't already installed, since we don't want to break 6181 // things that are installed. 6182 if ((scanFlags & SCAN_NEW_INSTALL) != 0) { 6183 final int N = pkg.providers.size(); 6184 int i; 6185 for (i=0; i<N; i++) { 6186 PackageParser.Provider p = pkg.providers.get(i); 6187 if (p.info.authority != null) { 6188 String names[] = p.info.authority.split(";"); 6189 for (int j = 0; j < names.length; j++) { 6190 if (mProvidersByAuthority.containsKey(names[j])) { 6191 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 6192 final String otherPackageName = 6193 ((other != null && other.getComponentName() != null) ? 6194 other.getComponentName().getPackageName() : "?"); 6195 throw new PackageManagerException( 6196 INSTALL_FAILED_CONFLICTING_PROVIDER, 6197 "Can't install because provider name " + names[j] 6198 + " (in package " + pkg.applicationInfo.packageName 6199 + ") is already used by " + otherPackageName); 6200 } 6201 } 6202 } 6203 } 6204 } 6205 6206 if (pkg.mAdoptPermissions != null) { 6207 // This package wants to adopt ownership of permissions from 6208 // another package. 6209 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 6210 final String origName = pkg.mAdoptPermissions.get(i); 6211 final PackageSetting orig = mSettings.peekPackageLPr(origName); 6212 if (orig != null) { 6213 if (verifyPackageUpdateLPr(orig, pkg)) { 6214 Slog.i(TAG, "Adopting permissions from " + origName + " to " 6215 + pkg.packageName); 6216 mSettings.transferPermissionsLPw(origName, pkg.packageName); 6217 } 6218 } 6219 } 6220 } 6221 } 6222 6223 final String pkgName = pkg.packageName; 6224 6225 final long scanFileTime = scanFile.lastModified(); 6226 final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0; 6227 pkg.applicationInfo.processName = fixProcessName( 6228 pkg.applicationInfo.packageName, 6229 pkg.applicationInfo.processName, 6230 pkg.applicationInfo.uid); 6231 6232 File dataPath; 6233 if (mPlatformPackage == pkg) { 6234 // The system package is special. 6235 dataPath = new File(Environment.getDataDirectory(), "system"); 6236 6237 pkg.applicationInfo.dataDir = dataPath.getPath(); 6238 6239 } else { 6240 // This is a normal package, need to make its data directory. 6241 dataPath = PackageManager.getDataDirForUser(pkg.volumeUuid, pkg.packageName, 6242 UserHandle.USER_OWNER); 6243 6244 boolean uidError = false; 6245 if (dataPath.exists()) { 6246 int currentUid = 0; 6247 try { 6248 StructStat stat = Os.stat(dataPath.getPath()); 6249 currentUid = stat.st_uid; 6250 } catch (ErrnoException e) { 6251 Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e); 6252 } 6253 6254 // If we have mismatched owners for the data path, we have a problem. 6255 if (currentUid != pkg.applicationInfo.uid) { 6256 boolean recovered = false; 6257 if (currentUid == 0) { 6258 // The directory somehow became owned by root. Wow. 6259 // This is probably because the system was stopped while 6260 // installd was in the middle of messing with its libs 6261 // directory. Ask installd to fix that. 6262 int ret = mInstaller.fixUid(pkg.volumeUuid, pkgName, 6263 pkg.applicationInfo.uid, pkg.applicationInfo.uid); 6264 if (ret >= 0) { 6265 recovered = true; 6266 String msg = "Package " + pkg.packageName 6267 + " unexpectedly changed to uid 0; recovered to " + 6268 + pkg.applicationInfo.uid; 6269 reportSettingsProblem(Log.WARN, msg); 6270 } 6271 } 6272 if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 6273 || (scanFlags&SCAN_BOOTING) != 0)) { 6274 // If this is a system app, we can at least delete its 6275 // current data so the application will still work. 6276 int ret = removeDataDirsLI(pkg.volumeUuid, pkgName); 6277 if (ret >= 0) { 6278 // TODO: Kill the processes first 6279 // Old data gone! 6280 String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 6281 ? "System package " : "Third party package "; 6282 String msg = prefix + pkg.packageName 6283 + " has changed from uid: " 6284 + currentUid + " to " 6285 + pkg.applicationInfo.uid + "; old data erased"; 6286 reportSettingsProblem(Log.WARN, msg); 6287 recovered = true; 6288 6289 // And now re-install the app. 6290 ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid, 6291 pkg.applicationInfo.seinfo); 6292 if (ret == -1) { 6293 // Ack should not happen! 6294 msg = prefix + pkg.packageName 6295 + " could not have data directory re-created after delete."; 6296 reportSettingsProblem(Log.WARN, msg); 6297 throw new PackageManagerException( 6298 INSTALL_FAILED_INSUFFICIENT_STORAGE, msg); 6299 } 6300 } 6301 if (!recovered) { 6302 mHasSystemUidErrors = true; 6303 } 6304 } else if (!recovered) { 6305 // If we allow this install to proceed, we will be broken. 6306 // Abort, abort! 6307 throw new PackageManagerException(INSTALL_FAILED_UID_CHANGED, 6308 "scanPackageLI"); 6309 } 6310 if (!recovered) { 6311 pkg.applicationInfo.dataDir = "/mismatched_uid/settings_" 6312 + pkg.applicationInfo.uid + "/fs_" 6313 + currentUid; 6314 pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir; 6315 pkg.applicationInfo.nativeLibraryRootDir = pkg.applicationInfo.dataDir; 6316 String msg = "Package " + pkg.packageName 6317 + " has mismatched uid: " 6318 + currentUid + " on disk, " 6319 + pkg.applicationInfo.uid + " in settings"; 6320 // writer 6321 synchronized (mPackages) { 6322 mSettings.mReadMessages.append(msg); 6323 mSettings.mReadMessages.append('\n'); 6324 uidError = true; 6325 if (!pkgSetting.uidError) { 6326 reportSettingsProblem(Log.ERROR, msg); 6327 } 6328 } 6329 } 6330 } 6331 pkg.applicationInfo.dataDir = dataPath.getPath(); 6332 if (mShouldRestoreconData) { 6333 Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued."); 6334 mInstaller.restoreconData(pkg.volumeUuid, pkg.packageName, 6335 pkg.applicationInfo.seinfo, pkg.applicationInfo.uid); 6336 } 6337 } else { 6338 if (DEBUG_PACKAGE_SCANNING) { 6339 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 6340 Log.v(TAG, "Want this data dir: " + dataPath); 6341 } 6342 //invoke installer to do the actual installation 6343 int ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid, 6344 pkg.applicationInfo.seinfo); 6345 if (ret < 0) { 6346 // Error from installer 6347 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 6348 "Unable to create data dirs [errorCode=" + ret + "]"); 6349 } 6350 6351 if (dataPath.exists()) { 6352 pkg.applicationInfo.dataDir = dataPath.getPath(); 6353 } else { 6354 Slog.w(TAG, "Unable to create data directory: " + dataPath); 6355 pkg.applicationInfo.dataDir = null; 6356 } 6357 } 6358 6359 pkgSetting.uidError = uidError; 6360 } 6361 6362 final String path = scanFile.getPath(); 6363 final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting); 6364 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) { 6365 setBundledAppAbisAndRoots(pkg, pkgSetting); 6366 6367 // If we haven't found any native libraries for the app, check if it has 6368 // renderscript code. We'll need to force the app to 32 bit if it has 6369 // renderscript bitcode. 6370 if (pkg.applicationInfo.primaryCpuAbi == null 6371 && pkg.applicationInfo.secondaryCpuAbi == null 6372 && Build.SUPPORTED_64_BIT_ABIS.length > 0) { 6373 NativeLibraryHelper.Handle handle = null; 6374 try { 6375 handle = NativeLibraryHelper.Handle.create(scanFile); 6376 if (NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 6377 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 6378 } 6379 } catch (IOException ioe) { 6380 Slog.w(TAG, "Error scanning system app : " + ioe); 6381 } finally { 6382 IoUtils.closeQuietly(handle); 6383 } 6384 } 6385 6386 setNativeLibraryPaths(pkg); 6387 } else { 6388 if ((scanFlags & SCAN_NEW_INSTALL) == 0) { 6389 deriveNonSystemPackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */); 6390 } else { 6391 if ((scanFlags & SCAN_MOVE) != 0) { 6392 // We haven't run dex-opt for this move (since we've moved the compiled output too) 6393 // but we already have this packages package info in the PackageSetting. We just 6394 // use that and derive the native library path based on the new codepath. 6395 pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString; 6396 pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString; 6397 } 6398 6399 // Set native library paths again. For moves, the path will be updated based on the 6400 // ABIs we've determined above. For non-moves, the path will be updated based on the 6401 // ABIs we determined during compilation, but the path will depend on the final 6402 // package path (after the rename away from the stage path). 6403 setNativeLibraryPaths(pkg); 6404 } 6405 6406 if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path); 6407 final int[] userIds = sUserManager.getUserIds(); 6408 synchronized (mInstallLock) { 6409 // Create a native library symlink only if we have native libraries 6410 // and if the native libraries are 32 bit libraries. We do not provide 6411 // this symlink for 64 bit libraries. 6412 if (pkg.applicationInfo.primaryCpuAbi != null && 6413 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 6414 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 6415 for (int userId : userIds) { 6416 if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName, 6417 nativeLibPath, userId) < 0) { 6418 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 6419 "Failed linking native library dir (user=" + userId + ")"); 6420 } 6421 } 6422 } 6423 } 6424 } 6425 6426 // This is a special case for the "system" package, where the ABI is 6427 // dictated by the zygote configuration (and init.rc). We should keep track 6428 // of this ABI so that we can deal with "normal" applications that run under 6429 // the same UID correctly. 6430 if (mPlatformPackage == pkg) { 6431 pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ? 6432 Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0]; 6433 } 6434 6435 // If there's a mismatch between the abi-override in the package setting 6436 // and the abiOverride specified for the install. Warn about this because we 6437 // would've already compiled the app without taking the package setting into 6438 // account. 6439 if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) { 6440 if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) { 6441 Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride + 6442 " for package: " + pkg.packageName); 6443 } 6444 } 6445 6446 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 6447 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 6448 pkgSetting.cpuAbiOverrideString = cpuAbiOverride; 6449 6450 // Copy the derived override back to the parsed package, so that we can 6451 // update the package settings accordingly. 6452 pkg.cpuAbiOverride = cpuAbiOverride; 6453 6454 if (DEBUG_ABI_SELECTION) { 6455 Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName 6456 + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa=" 6457 + pkg.applicationInfo.nativeLibraryRootRequiresIsa); 6458 } 6459 6460 // Push the derived path down into PackageSettings so we know what to 6461 // clean up at uninstall time. 6462 pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir; 6463 6464 if (DEBUG_ABI_SELECTION) { 6465 Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" + 6466 " primary=" + pkg.applicationInfo.primaryCpuAbi + 6467 " secondary=" + pkg.applicationInfo.secondaryCpuAbi); 6468 } 6469 6470 if ((scanFlags&SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 6471 // We don't do this here during boot because we can do it all 6472 // at once after scanning all existing packages. 6473 // 6474 // We also do this *before* we perform dexopt on this package, so that 6475 // we can avoid redundant dexopts, and also to make sure we've got the 6476 // code and package path correct. 6477 adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, 6478 pkg, forceDex, (scanFlags & SCAN_DEFER_DEX) != 0); 6479 } 6480 6481 if ((scanFlags & SCAN_NO_DEX) == 0) { 6482 int result = mPackageDexOptimizer.performDexOpt(pkg, null /* instruction sets */, 6483 forceDex, (scanFlags & SCAN_DEFER_DEX) != 0, false /* inclDependencies */); 6484 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 6485 throw new PackageManagerException(INSTALL_FAILED_DEXOPT, "scanPackageLI"); 6486 } 6487 } 6488 if (mFactoryTest && pkg.requestedPermissions.contains( 6489 android.Manifest.permission.FACTORY_TEST)) { 6490 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 6491 } 6492 6493 ArrayList<PackageParser.Package> clientLibPkgs = null; 6494 6495 // writer 6496 synchronized (mPackages) { 6497 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 6498 // Only system apps can add new shared libraries. 6499 if (pkg.libraryNames != null) { 6500 for (int i=0; i<pkg.libraryNames.size(); i++) { 6501 String name = pkg.libraryNames.get(i); 6502 boolean allowed = false; 6503 if (pkg.isUpdatedSystemApp()) { 6504 // New library entries can only be added through the 6505 // system image. This is important to get rid of a lot 6506 // of nasty edge cases: for example if we allowed a non- 6507 // system update of the app to add a library, then uninstalling 6508 // the update would make the library go away, and assumptions 6509 // we made such as through app install filtering would now 6510 // have allowed apps on the device which aren't compatible 6511 // with it. Better to just have the restriction here, be 6512 // conservative, and create many fewer cases that can negatively 6513 // impact the user experience. 6514 final PackageSetting sysPs = mSettings 6515 .getDisabledSystemPkgLPr(pkg.packageName); 6516 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 6517 for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) { 6518 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 6519 allowed = true; 6520 allowed = true; 6521 break; 6522 } 6523 } 6524 } 6525 } else { 6526 allowed = true; 6527 } 6528 if (allowed) { 6529 if (!mSharedLibraries.containsKey(name)) { 6530 mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName)); 6531 } else if (!name.equals(pkg.packageName)) { 6532 Slog.w(TAG, "Package " + pkg.packageName + " library " 6533 + name + " already exists; skipping"); 6534 } 6535 } else { 6536 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 6537 + name + " that is not declared on system image; skipping"); 6538 } 6539 } 6540 if ((scanFlags&SCAN_BOOTING) == 0) { 6541 // If we are not booting, we need to update any applications 6542 // that are clients of our shared library. If we are booting, 6543 // this will all be done once the scan is complete. 6544 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 6545 } 6546 } 6547 } 6548 } 6549 6550 // We also need to dexopt any apps that are dependent on this library. Note that 6551 // if these fail, we should abort the install since installing the library will 6552 // result in some apps being broken. 6553 if (clientLibPkgs != null) { 6554 if ((scanFlags & SCAN_NO_DEX) == 0) { 6555 for (int i = 0; i < clientLibPkgs.size(); i++) { 6556 PackageParser.Package clientPkg = clientLibPkgs.get(i); 6557 int result = mPackageDexOptimizer.performDexOpt(clientPkg, 6558 null /* instruction sets */, forceDex, 6559 (scanFlags & SCAN_DEFER_DEX) != 0, false); 6560 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 6561 throw new PackageManagerException(INSTALL_FAILED_DEXOPT, 6562 "scanPackageLI failed to dexopt clientLibPkgs"); 6563 } 6564 } 6565 } 6566 } 6567 6568 // Also need to kill any apps that are dependent on the library. 6569 if (clientLibPkgs != null) { 6570 for (int i=0; i<clientLibPkgs.size(); i++) { 6571 PackageParser.Package clientPkg = clientLibPkgs.get(i); 6572 killApplication(clientPkg.applicationInfo.packageName, 6573 clientPkg.applicationInfo.uid, "update lib"); 6574 } 6575 } 6576 6577 // writer 6578 synchronized (mPackages) { 6579 // We don't expect installation to fail beyond this point 6580 6581 // Add the new setting to mSettings 6582 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 6583 // Add the new setting to mPackages 6584 mPackages.put(pkg.applicationInfo.packageName, pkg); 6585 // Make sure we don't accidentally delete its data. 6586 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 6587 while (iter.hasNext()) { 6588 PackageCleanItem item = iter.next(); 6589 if (pkgName.equals(item.packageName)) { 6590 iter.remove(); 6591 } 6592 } 6593 6594 // Take care of first install / last update times. 6595 if (currentTime != 0) { 6596 if (pkgSetting.firstInstallTime == 0) { 6597 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 6598 } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) { 6599 pkgSetting.lastUpdateTime = currentTime; 6600 } 6601 } else if (pkgSetting.firstInstallTime == 0) { 6602 // We need *something*. Take time time stamp of the file. 6603 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 6604 } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 6605 if (scanFileTime != pkgSetting.timeStamp) { 6606 // A package on the system image has changed; consider this 6607 // to be an update. 6608 pkgSetting.lastUpdateTime = scanFileTime; 6609 } 6610 } 6611 6612 // Add the package's KeySets to the global KeySetManagerService 6613 KeySetManagerService ksms = mSettings.mKeySetManagerService; 6614 try { 6615 ksms.addSigningKeySetToPackageLPw(pkg.packageName, pkg.mSigningKeys); 6616 if (pkg.mKeySetMapping != null) { 6617 ksms.addDefinedKeySetsToPackageLPw(pkg.packageName, pkg.mKeySetMapping); 6618 if (pkg.mUpgradeKeySets != null) { 6619 ksms.addUpgradeKeySetsToPackageLPw(pkg.packageName, pkg.mUpgradeKeySets); 6620 } 6621 } 6622 } catch (NullPointerException e) { 6623 Slog.e(TAG, "Could not add KeySet to " + pkg.packageName, e); 6624 } catch (IllegalArgumentException e) { 6625 Slog.e(TAG, "Could not add KeySet to malformed package" + pkg.packageName, e); 6626 } 6627 6628 int N = pkg.providers.size(); 6629 StringBuilder r = null; 6630 int i; 6631 for (i=0; i<N; i++) { 6632 PackageParser.Provider p = pkg.providers.get(i); 6633 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 6634 p.info.processName, pkg.applicationInfo.uid); 6635 mProviders.addProvider(p); 6636 p.syncable = p.info.isSyncable; 6637 if (p.info.authority != null) { 6638 String names[] = p.info.authority.split(";"); 6639 p.info.authority = null; 6640 for (int j = 0; j < names.length; j++) { 6641 if (j == 1 && p.syncable) { 6642 // We only want the first authority for a provider to possibly be 6643 // syncable, so if we already added this provider using a different 6644 // authority clear the syncable flag. We copy the provider before 6645 // changing it because the mProviders object contains a reference 6646 // to a provider that we don't want to change. 6647 // Only do this for the second authority since the resulting provider 6648 // object can be the same for all future authorities for this provider. 6649 p = new PackageParser.Provider(p); 6650 p.syncable = false; 6651 } 6652 if (!mProvidersByAuthority.containsKey(names[j])) { 6653 mProvidersByAuthority.put(names[j], p); 6654 if (p.info.authority == null) { 6655 p.info.authority = names[j]; 6656 } else { 6657 p.info.authority = p.info.authority + ";" + names[j]; 6658 } 6659 if (DEBUG_PACKAGE_SCANNING) { 6660 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 6661 Log.d(TAG, "Registered content provider: " + names[j] 6662 + ", className = " + p.info.name + ", isSyncable = " 6663 + p.info.isSyncable); 6664 } 6665 } else { 6666 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 6667 Slog.w(TAG, "Skipping provider name " + names[j] + 6668 " (in package " + pkg.applicationInfo.packageName + 6669 "): name already used by " 6670 + ((other != null && other.getComponentName() != null) 6671 ? other.getComponentName().getPackageName() : "?")); 6672 } 6673 } 6674 } 6675 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6676 if (r == null) { 6677 r = new StringBuilder(256); 6678 } else { 6679 r.append(' '); 6680 } 6681 r.append(p.info.name); 6682 } 6683 } 6684 if (r != null) { 6685 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 6686 } 6687 6688 N = pkg.services.size(); 6689 r = null; 6690 for (i=0; i<N; i++) { 6691 PackageParser.Service s = pkg.services.get(i); 6692 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 6693 s.info.processName, pkg.applicationInfo.uid); 6694 mServices.addService(s); 6695 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6696 if (r == null) { 6697 r = new StringBuilder(256); 6698 } else { 6699 r.append(' '); 6700 } 6701 r.append(s.info.name); 6702 } 6703 } 6704 if (r != null) { 6705 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 6706 } 6707 6708 N = pkg.receivers.size(); 6709 r = null; 6710 for (i=0; i<N; i++) { 6711 PackageParser.Activity a = pkg.receivers.get(i); 6712 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 6713 a.info.processName, pkg.applicationInfo.uid); 6714 mReceivers.addActivity(a, "receiver"); 6715 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6716 if (r == null) { 6717 r = new StringBuilder(256); 6718 } else { 6719 r.append(' '); 6720 } 6721 r.append(a.info.name); 6722 } 6723 } 6724 if (r != null) { 6725 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 6726 } 6727 6728 N = pkg.activities.size(); 6729 r = null; 6730 for (i=0; i<N; i++) { 6731 PackageParser.Activity a = pkg.activities.get(i); 6732 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 6733 a.info.processName, pkg.applicationInfo.uid); 6734 mActivities.addActivity(a, "activity"); 6735 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6736 if (r == null) { 6737 r = new StringBuilder(256); 6738 } else { 6739 r.append(' '); 6740 } 6741 r.append(a.info.name); 6742 } 6743 } 6744 if (r != null) { 6745 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 6746 } 6747 6748 N = pkg.permissionGroups.size(); 6749 r = null; 6750 for (i=0; i<N; i++) { 6751 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i); 6752 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name); 6753 if (cur == null) { 6754 mPermissionGroups.put(pg.info.name, pg); 6755 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6756 if (r == null) { 6757 r = new StringBuilder(256); 6758 } else { 6759 r.append(' '); 6760 } 6761 r.append(pg.info.name); 6762 } 6763 } else { 6764 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 6765 + pg.info.packageName + " ignored: original from " 6766 + cur.info.packageName); 6767 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6768 if (r == null) { 6769 r = new StringBuilder(256); 6770 } else { 6771 r.append(' '); 6772 } 6773 r.append("DUP:"); 6774 r.append(pg.info.name); 6775 } 6776 } 6777 } 6778 if (r != null) { 6779 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r); 6780 } 6781 6782 N = pkg.permissions.size(); 6783 r = null; 6784 for (i=0; i<N; i++) { 6785 PackageParser.Permission p = pkg.permissions.get(i); 6786 6787 // Now that permission groups have a special meaning, we ignore permission 6788 // groups for legacy apps to prevent unexpected behavior. In particular, 6789 // permissions for one app being granted to someone just becuase they happen 6790 // to be in a group defined by another app (before this had no implications). 6791 if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) { 6792 p.group = mPermissionGroups.get(p.info.group); 6793 // Warn for a permission in an unknown group. 6794 if (p.info.group != null && p.group == null) { 6795 Slog.w(TAG, "Permission " + p.info.name + " from package " 6796 + p.info.packageName + " in an unknown group " + p.info.group); 6797 } 6798 } 6799 6800 ArrayMap<String, BasePermission> permissionMap = 6801 p.tree ? mSettings.mPermissionTrees 6802 : mSettings.mPermissions; 6803 BasePermission bp = permissionMap.get(p.info.name); 6804 6805 // Allow system apps to redefine non-system permissions 6806 if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) { 6807 final boolean currentOwnerIsSystem = (bp.perm != null 6808 && isSystemApp(bp.perm.owner)); 6809 if (isSystemApp(p.owner)) { 6810 if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) { 6811 // It's a built-in permission and no owner, take ownership now 6812 bp.packageSetting = pkgSetting; 6813 bp.perm = p; 6814 bp.uid = pkg.applicationInfo.uid; 6815 bp.sourcePackage = p.info.packageName; 6816 } else if (!currentOwnerIsSystem) { 6817 String msg = "New decl " + p.owner + " of permission " 6818 + p.info.name + " is system; overriding " + bp.sourcePackage; 6819 reportSettingsProblem(Log.WARN, msg); 6820 bp = null; 6821 } 6822 } 6823 } 6824 6825 if (bp == null) { 6826 bp = new BasePermission(p.info.name, p.info.packageName, 6827 BasePermission.TYPE_NORMAL); 6828 permissionMap.put(p.info.name, bp); 6829 } 6830 6831 if (bp.perm == null) { 6832 if (bp.sourcePackage == null 6833 || bp.sourcePackage.equals(p.info.packageName)) { 6834 BasePermission tree = findPermissionTreeLP(p.info.name); 6835 if (tree == null 6836 || tree.sourcePackage.equals(p.info.packageName)) { 6837 bp.packageSetting = pkgSetting; 6838 bp.perm = p; 6839 bp.uid = pkg.applicationInfo.uid; 6840 bp.sourcePackage = p.info.packageName; 6841 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6842 if (r == null) { 6843 r = new StringBuilder(256); 6844 } else { 6845 r.append(' '); 6846 } 6847 r.append(p.info.name); 6848 } 6849 } else { 6850 Slog.w(TAG, "Permission " + p.info.name + " from package " 6851 + p.info.packageName + " ignored: base tree " 6852 + tree.name + " is from package " 6853 + tree.sourcePackage); 6854 } 6855 } else { 6856 Slog.w(TAG, "Permission " + p.info.name + " from package " 6857 + p.info.packageName + " ignored: original from " 6858 + bp.sourcePackage); 6859 } 6860 } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6861 if (r == null) { 6862 r = new StringBuilder(256); 6863 } else { 6864 r.append(' '); 6865 } 6866 r.append("DUP:"); 6867 r.append(p.info.name); 6868 } 6869 if (bp.perm == p) { 6870 bp.protectionLevel = p.info.protectionLevel; 6871 } 6872 } 6873 6874 if (r != null) { 6875 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r); 6876 } 6877 6878 N = pkg.instrumentation.size(); 6879 r = null; 6880 for (i=0; i<N; i++) { 6881 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 6882 a.info.packageName = pkg.applicationInfo.packageName; 6883 a.info.sourceDir = pkg.applicationInfo.sourceDir; 6884 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 6885 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 6886 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 6887 a.info.dataDir = pkg.applicationInfo.dataDir; 6888 6889 // TODO: Update instrumentation.nativeLibraryDir as well ? Does it 6890 // need other information about the application, like the ABI and what not ? 6891 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 6892 mInstrumentation.put(a.getComponentName(), a); 6893 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6894 if (r == null) { 6895 r = new StringBuilder(256); 6896 } else { 6897 r.append(' '); 6898 } 6899 r.append(a.info.name); 6900 } 6901 } 6902 if (r != null) { 6903 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 6904 } 6905 6906 if (pkg.protectedBroadcasts != null) { 6907 N = pkg.protectedBroadcasts.size(); 6908 for (i=0; i<N; i++) { 6909 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 6910 } 6911 } 6912 6913 pkgSetting.setTimeStamp(scanFileTime); 6914 6915 // Create idmap files for pairs of (packages, overlay packages). 6916 // Note: "android", ie framework-res.apk, is handled by native layers. 6917 if (pkg.mOverlayTarget != null) { 6918 // This is an overlay package. 6919 if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) { 6920 if (!mOverlays.containsKey(pkg.mOverlayTarget)) { 6921 mOverlays.put(pkg.mOverlayTarget, 6922 new ArrayMap<String, PackageParser.Package>()); 6923 } 6924 ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget); 6925 map.put(pkg.packageName, pkg); 6926 PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget); 6927 if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) { 6928 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 6929 "scanPackageLI failed to createIdmap"); 6930 } 6931 } 6932 } else if (mOverlays.containsKey(pkg.packageName) && 6933 !pkg.packageName.equals("android")) { 6934 // This is a regular package, with one or more known overlay packages. 6935 createIdmapsForPackageLI(pkg); 6936 } 6937 } 6938 6939 return pkg; 6940 } 6941 6942 /** 6943 * Derive the ABI of a non-system package located at {@code scanFile}. This information 6944 * is derived purely on the basis of the contents of {@code scanFile} and 6945 * {@code cpuAbiOverride}. 6946 * 6947 * If {@code extractLibs} is true, native libraries are extracted from the app if required. 6948 */ 6949 public void deriveNonSystemPackageAbi(PackageParser.Package pkg, File scanFile, 6950 String cpuAbiOverride, boolean extractLibs) 6951 throws PackageManagerException { 6952 // TODO: We can probably be smarter about this stuff. For installed apps, 6953 // we can calculate this information at install time once and for all. For 6954 // system apps, we can probably assume that this information doesn't change 6955 // after the first boot scan. As things stand, we do lots of unnecessary work. 6956 6957 // Give ourselves some initial paths; we'll come back for another 6958 // pass once we've determined ABI below. 6959 setNativeLibraryPaths(pkg); 6960 6961 // We would never need to extract libs for forward-locked and external packages, 6962 // since the container service will do it for us. 6963 if (pkg.isForwardLocked() || isExternal(pkg)) { 6964 extractLibs = false; 6965 } 6966 6967 final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir; 6968 final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa; 6969 6970 NativeLibraryHelper.Handle handle = null; 6971 try { 6972 handle = NativeLibraryHelper.Handle.create(scanFile); 6973 // TODO(multiArch): This can be null for apps that didn't go through the 6974 // usual installation process. We can calculate it again, like we 6975 // do during install time. 6976 // 6977 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally 6978 // unnecessary. 6979 final File nativeLibraryRoot = new File(nativeLibraryRootStr); 6980 6981 // Null out the abis so that they can be recalculated. 6982 pkg.applicationInfo.primaryCpuAbi = null; 6983 pkg.applicationInfo.secondaryCpuAbi = null; 6984 if (isMultiArch(pkg.applicationInfo)) { 6985 // Warn if we've set an abiOverride for multi-lib packages.. 6986 // By definition, we need to copy both 32 and 64 bit libraries for 6987 // such packages. 6988 if (pkg.cpuAbiOverride != null 6989 && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) { 6990 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 6991 } 6992 6993 int abi32 = PackageManager.NO_NATIVE_LIBRARIES; 6994 int abi64 = PackageManager.NO_NATIVE_LIBRARIES; 6995 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 6996 if (extractLibs) { 6997 abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 6998 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, 6999 useIsaSpecificSubdirs); 7000 } else { 7001 abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS); 7002 } 7003 } 7004 7005 maybeThrowExceptionForMultiArchCopy( 7006 "Error unpackaging 32 bit native libs for multiarch app.", abi32); 7007 7008 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 7009 if (extractLibs) { 7010 abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 7011 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, 7012 useIsaSpecificSubdirs); 7013 } else { 7014 abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS); 7015 } 7016 } 7017 7018 maybeThrowExceptionForMultiArchCopy( 7019 "Error unpackaging 64 bit native libs for multiarch app.", abi64); 7020 7021 if (abi64 >= 0) { 7022 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64]; 7023 } 7024 7025 if (abi32 >= 0) { 7026 final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32]; 7027 if (abi64 >= 0) { 7028 pkg.applicationInfo.secondaryCpuAbi = abi; 7029 } else { 7030 pkg.applicationInfo.primaryCpuAbi = abi; 7031 } 7032 } 7033 } else { 7034 String[] abiList = (cpuAbiOverride != null) ? 7035 new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS; 7036 7037 // Enable gross and lame hacks for apps that are built with old 7038 // SDK tools. We must scan their APKs for renderscript bitcode and 7039 // not launch them if it's present. Don't bother checking on devices 7040 // that don't have 64 bit support. 7041 boolean needsRenderScriptOverride = false; 7042 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null && 7043 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 7044 abiList = Build.SUPPORTED_32_BIT_ABIS; 7045 needsRenderScriptOverride = true; 7046 } 7047 7048 final int copyRet; 7049 if (extractLibs) { 7050 copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 7051 nativeLibraryRoot, abiList, useIsaSpecificSubdirs); 7052 } else { 7053 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList); 7054 } 7055 7056 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 7057 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 7058 "Error unpackaging native libs for app, errorCode=" + copyRet); 7059 } 7060 7061 if (copyRet >= 0) { 7062 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet]; 7063 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) { 7064 pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride; 7065 } else if (needsRenderScriptOverride) { 7066 pkg.applicationInfo.primaryCpuAbi = abiList[0]; 7067 } 7068 } 7069 } catch (IOException ioe) { 7070 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 7071 } finally { 7072 IoUtils.closeQuietly(handle); 7073 } 7074 7075 // Now that we've calculated the ABIs and determined if it's an internal app, 7076 // we will go ahead and populate the nativeLibraryPath. 7077 setNativeLibraryPaths(pkg); 7078 } 7079 7080 /** 7081 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 7082 * i.e, so that all packages can be run inside a single process if required. 7083 * 7084 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 7085 * this function will either try and make the ABI for all packages in {@code packagesForUser} 7086 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 7087 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 7088 * updating a package that belongs to a shared user. 7089 * 7090 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary 7091 * adds unnecessary complexity. 7092 */ 7093 private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser, 7094 PackageParser.Package scannedPackage, boolean forceDexOpt, boolean deferDexOpt) { 7095 String requiredInstructionSet = null; 7096 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) { 7097 requiredInstructionSet = VMRuntime.getInstructionSet( 7098 scannedPackage.applicationInfo.primaryCpuAbi); 7099 } 7100 7101 PackageSetting requirer = null; 7102 for (PackageSetting ps : packagesForUser) { 7103 // If packagesForUser contains scannedPackage, we skip it. This will happen 7104 // when scannedPackage is an update of an existing package. Without this check, 7105 // we will never be able to change the ABI of any package belonging to a shared 7106 // user, even if it's compatible with other packages. 7107 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 7108 if (ps.primaryCpuAbiString == null) { 7109 continue; 7110 } 7111 7112 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString); 7113 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) { 7114 // We have a mismatch between instruction sets (say arm vs arm64) warn about 7115 // this but there's not much we can do. 7116 String errorMessage = "Instruction set mismatch, " 7117 + ((requirer == null) ? "[caller]" : requirer) 7118 + " requires " + requiredInstructionSet + " whereas " + ps 7119 + " requires " + instructionSet; 7120 Slog.w(TAG, errorMessage); 7121 } 7122 7123 if (requiredInstructionSet == null) { 7124 requiredInstructionSet = instructionSet; 7125 requirer = ps; 7126 } 7127 } 7128 } 7129 7130 if (requiredInstructionSet != null) { 7131 String adjustedAbi; 7132 if (requirer != null) { 7133 // requirer != null implies that either scannedPackage was null or that scannedPackage 7134 // did not require an ABI, in which case we have to adjust scannedPackage to match 7135 // the ABI of the set (which is the same as requirer's ABI) 7136 adjustedAbi = requirer.primaryCpuAbiString; 7137 if (scannedPackage != null) { 7138 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi; 7139 } 7140 } else { 7141 // requirer == null implies that we're updating all ABIs in the set to 7142 // match scannedPackage. 7143 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi; 7144 } 7145 7146 for (PackageSetting ps : packagesForUser) { 7147 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 7148 if (ps.primaryCpuAbiString != null) { 7149 continue; 7150 } 7151 7152 ps.primaryCpuAbiString = adjustedAbi; 7153 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 7154 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi; 7155 Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi); 7156 7157 int result = mPackageDexOptimizer.performDexOpt(ps.pkg, 7158 null /* instruction sets */, forceDexOpt, deferDexOpt, true); 7159 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 7160 ps.primaryCpuAbiString = null; 7161 ps.pkg.applicationInfo.primaryCpuAbi = null; 7162 return; 7163 } else { 7164 mInstaller.rmdex(ps.codePathString, 7165 getDexCodeInstructionSet(getPreferredInstructionSet())); 7166 } 7167 } 7168 } 7169 } 7170 } 7171 } 7172 7173 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 7174 synchronized (mPackages) { 7175 mResolverReplaced = true; 7176 // Set up information for custom user intent resolution activity. 7177 mResolveActivity.applicationInfo = pkg.applicationInfo; 7178 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 7179 mResolveActivity.packageName = pkg.applicationInfo.packageName; 7180 mResolveActivity.processName = pkg.applicationInfo.packageName; 7181 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 7182 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 7183 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 7184 mResolveActivity.theme = 0; 7185 mResolveActivity.exported = true; 7186 mResolveActivity.enabled = true; 7187 mResolveInfo.activityInfo = mResolveActivity; 7188 mResolveInfo.priority = 0; 7189 mResolveInfo.preferredOrder = 0; 7190 mResolveInfo.match = 0; 7191 mResolveComponentName = mCustomResolverComponentName; 7192 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 7193 mResolveComponentName); 7194 } 7195 } 7196 7197 private static String calculateBundledApkRoot(final String codePathString) { 7198 final File codePath = new File(codePathString); 7199 final File codeRoot; 7200 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 7201 codeRoot = Environment.getRootDirectory(); 7202 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 7203 codeRoot = Environment.getOemDirectory(); 7204 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 7205 codeRoot = Environment.getVendorDirectory(); 7206 } else { 7207 // Unrecognized code path; take its top real segment as the apk root: 7208 // e.g. /something/app/blah.apk => /something 7209 try { 7210 File f = codePath.getCanonicalFile(); 7211 File parent = f.getParentFile(); // non-null because codePath is a file 7212 File tmp; 7213 while ((tmp = parent.getParentFile()) != null) { 7214 f = parent; 7215 parent = tmp; 7216 } 7217 codeRoot = f; 7218 Slog.w(TAG, "Unrecognized code path " 7219 + codePath + " - using " + codeRoot); 7220 } catch (IOException e) { 7221 // Can't canonicalize the code path -- shenanigans? 7222 Slog.w(TAG, "Can't canonicalize code path " + codePath); 7223 return Environment.getRootDirectory().getPath(); 7224 } 7225 } 7226 return codeRoot.getPath(); 7227 } 7228 7229 /** 7230 * Derive and set the location of native libraries for the given package, 7231 * which varies depending on where and how the package was installed. 7232 */ 7233 private void setNativeLibraryPaths(PackageParser.Package pkg) { 7234 final ApplicationInfo info = pkg.applicationInfo; 7235 final String codePath = pkg.codePath; 7236 final File codeFile = new File(codePath); 7237 final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp(); 7238 final boolean asecApp = info.isForwardLocked() || isExternal(info); 7239 7240 info.nativeLibraryRootDir = null; 7241 info.nativeLibraryRootRequiresIsa = false; 7242 info.nativeLibraryDir = null; 7243 info.secondaryNativeLibraryDir = null; 7244 7245 if (isApkFile(codeFile)) { 7246 // Monolithic install 7247 if (bundledApp) { 7248 // If "/system/lib64/apkname" exists, assume that is the per-package 7249 // native library directory to use; otherwise use "/system/lib/apkname". 7250 final String apkRoot = calculateBundledApkRoot(info.sourceDir); 7251 final boolean is64Bit = VMRuntime.is64BitInstructionSet( 7252 getPrimaryInstructionSet(info)); 7253 7254 // This is a bundled system app so choose the path based on the ABI. 7255 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this 7256 // is just the default path. 7257 final String apkName = deriveCodePathName(codePath); 7258 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME; 7259 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir, 7260 apkName).getAbsolutePath(); 7261 7262 if (info.secondaryCpuAbi != null) { 7263 final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME; 7264 info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot), 7265 secondaryLibDir, apkName).getAbsolutePath(); 7266 } 7267 } else if (asecApp) { 7268 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME) 7269 .getAbsolutePath(); 7270 } else { 7271 final String apkName = deriveCodePathName(codePath); 7272 info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName) 7273 .getAbsolutePath(); 7274 } 7275 7276 info.nativeLibraryRootRequiresIsa = false; 7277 info.nativeLibraryDir = info.nativeLibraryRootDir; 7278 } else { 7279 // Cluster install 7280 info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath(); 7281 info.nativeLibraryRootRequiresIsa = true; 7282 7283 info.nativeLibraryDir = new File(info.nativeLibraryRootDir, 7284 getPrimaryInstructionSet(info)).getAbsolutePath(); 7285 7286 if (info.secondaryCpuAbi != null) { 7287 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir, 7288 VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath(); 7289 } 7290 } 7291 } 7292 7293 /** 7294 * Calculate the abis and roots for a bundled app. These can uniquely 7295 * be determined from the contents of the system partition, i.e whether 7296 * it contains 64 or 32 bit shared libraries etc. We do not validate any 7297 * of this information, and instead assume that the system was built 7298 * sensibly. 7299 */ 7300 private void setBundledAppAbisAndRoots(PackageParser.Package pkg, 7301 PackageSetting pkgSetting) { 7302 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); 7303 7304 // If "/system/lib64/apkname" exists, assume that is the per-package 7305 // native library directory to use; otherwise use "/system/lib/apkname". 7306 final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir); 7307 setBundledAppAbi(pkg, apkRoot, apkName); 7308 // pkgSetting might be null during rescan following uninstall of updates 7309 // to a bundled app, so accommodate that possibility. The settings in 7310 // that case will be established later from the parsed package. 7311 // 7312 // If the settings aren't null, sync them up with what we've just derived. 7313 // note that apkRoot isn't stored in the package settings. 7314 if (pkgSetting != null) { 7315 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 7316 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 7317 } 7318 } 7319 7320 /** 7321 * Deduces the ABI of a bundled app and sets the relevant fields on the 7322 * parsed pkg object. 7323 * 7324 * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem} 7325 * under which system libraries are installed. 7326 * @param apkName the name of the installed package. 7327 */ 7328 private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) { 7329 final File codeFile = new File(pkg.codePath); 7330 7331 final boolean has64BitLibs; 7332 final boolean has32BitLibs; 7333 if (isApkFile(codeFile)) { 7334 // Monolithic install 7335 has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists(); 7336 has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists(); 7337 } else { 7338 // Cluster install 7339 final File rootDir = new File(codeFile, LIB_DIR_NAME); 7340 if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS) 7341 && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) { 7342 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]); 7343 has64BitLibs = (new File(rootDir, isa)).exists(); 7344 } else { 7345 has64BitLibs = false; 7346 } 7347 if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS) 7348 && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) { 7349 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]); 7350 has32BitLibs = (new File(rootDir, isa)).exists(); 7351 } else { 7352 has32BitLibs = false; 7353 } 7354 } 7355 7356 if (has64BitLibs && !has32BitLibs) { 7357 // The package has 64 bit libs, but not 32 bit libs. Its primary 7358 // ABI should be 64 bit. We can safely assume here that the bundled 7359 // native libraries correspond to the most preferred ABI in the list. 7360 7361 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 7362 pkg.applicationInfo.secondaryCpuAbi = null; 7363 } else if (has32BitLibs && !has64BitLibs) { 7364 // The package has 32 bit libs but not 64 bit libs. Its primary 7365 // ABI should be 32 bit. 7366 7367 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 7368 pkg.applicationInfo.secondaryCpuAbi = null; 7369 } else if (has32BitLibs && has64BitLibs) { 7370 // The application has both 64 and 32 bit bundled libraries. We check 7371 // here that the app declares multiArch support, and warn if it doesn't. 7372 // 7373 // We will be lenient here and record both ABIs. The primary will be the 7374 // ABI that's higher on the list, i.e, a device that's configured to prefer 7375 // 64 bit apps will see a 64 bit primary ABI, 7376 7377 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) { 7378 Slog.e(TAG, "Package: " + pkg + " has multiple bundled libs, but is not multiarch."); 7379 } 7380 7381 if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) { 7382 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 7383 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 7384 } else { 7385 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 7386 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 7387 } 7388 } else { 7389 pkg.applicationInfo.primaryCpuAbi = null; 7390 pkg.applicationInfo.secondaryCpuAbi = null; 7391 } 7392 } 7393 7394 private void killApplication(String pkgName, int appId, String reason) { 7395 // Request the ActivityManager to kill the process(only for existing packages) 7396 // so that we do not end up in a confused state while the user is still using the older 7397 // version of the application while the new one gets installed. 7398 IActivityManager am = ActivityManagerNative.getDefault(); 7399 if (am != null) { 7400 try { 7401 am.killApplicationWithAppId(pkgName, appId, reason); 7402 } catch (RemoteException e) { 7403 } 7404 } 7405 } 7406 7407 void removePackageLI(PackageSetting ps, boolean chatty) { 7408 if (DEBUG_INSTALL) { 7409 if (chatty) 7410 Log.d(TAG, "Removing package " + ps.name); 7411 } 7412 7413 // writer 7414 synchronized (mPackages) { 7415 mPackages.remove(ps.name); 7416 final PackageParser.Package pkg = ps.pkg; 7417 if (pkg != null) { 7418 cleanPackageDataStructuresLILPw(pkg, chatty); 7419 } 7420 } 7421 } 7422 7423 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 7424 if (DEBUG_INSTALL) { 7425 if (chatty) 7426 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 7427 } 7428 7429 // writer 7430 synchronized (mPackages) { 7431 mPackages.remove(pkg.applicationInfo.packageName); 7432 cleanPackageDataStructuresLILPw(pkg, chatty); 7433 } 7434 } 7435 7436 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 7437 int N = pkg.providers.size(); 7438 StringBuilder r = null; 7439 int i; 7440 for (i=0; i<N; i++) { 7441 PackageParser.Provider p = pkg.providers.get(i); 7442 mProviders.removeProvider(p); 7443 if (p.info.authority == null) { 7444 7445 /* There was another ContentProvider with this authority when 7446 * this app was installed so this authority is null, 7447 * Ignore it as we don't have to unregister the provider. 7448 */ 7449 continue; 7450 } 7451 String names[] = p.info.authority.split(";"); 7452 for (int j = 0; j < names.length; j++) { 7453 if (mProvidersByAuthority.get(names[j]) == p) { 7454 mProvidersByAuthority.remove(names[j]); 7455 if (DEBUG_REMOVE) { 7456 if (chatty) 7457 Log.d(TAG, "Unregistered content provider: " + names[j] 7458 + ", className = " + p.info.name + ", isSyncable = " 7459 + p.info.isSyncable); 7460 } 7461 } 7462 } 7463 if (DEBUG_REMOVE && chatty) { 7464 if (r == null) { 7465 r = new StringBuilder(256); 7466 } else { 7467 r.append(' '); 7468 } 7469 r.append(p.info.name); 7470 } 7471 } 7472 if (r != null) { 7473 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 7474 } 7475 7476 N = pkg.services.size(); 7477 r = null; 7478 for (i=0; i<N; i++) { 7479 PackageParser.Service s = pkg.services.get(i); 7480 mServices.removeService(s); 7481 if (chatty) { 7482 if (r == null) { 7483 r = new StringBuilder(256); 7484 } else { 7485 r.append(' '); 7486 } 7487 r.append(s.info.name); 7488 } 7489 } 7490 if (r != null) { 7491 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 7492 } 7493 7494 N = pkg.receivers.size(); 7495 r = null; 7496 for (i=0; i<N; i++) { 7497 PackageParser.Activity a = pkg.receivers.get(i); 7498 mReceivers.removeActivity(a, "receiver"); 7499 if (DEBUG_REMOVE && chatty) { 7500 if (r == null) { 7501 r = new StringBuilder(256); 7502 } else { 7503 r.append(' '); 7504 } 7505 r.append(a.info.name); 7506 } 7507 } 7508 if (r != null) { 7509 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 7510 } 7511 7512 N = pkg.activities.size(); 7513 r = null; 7514 for (i=0; i<N; i++) { 7515 PackageParser.Activity a = pkg.activities.get(i); 7516 mActivities.removeActivity(a, "activity"); 7517 if (DEBUG_REMOVE && chatty) { 7518 if (r == null) { 7519 r = new StringBuilder(256); 7520 } else { 7521 r.append(' '); 7522 } 7523 r.append(a.info.name); 7524 } 7525 } 7526 if (r != null) { 7527 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 7528 } 7529 7530 N = pkg.permissions.size(); 7531 r = null; 7532 for (i=0; i<N; i++) { 7533 PackageParser.Permission p = pkg.permissions.get(i); 7534 BasePermission bp = mSettings.mPermissions.get(p.info.name); 7535 if (bp == null) { 7536 bp = mSettings.mPermissionTrees.get(p.info.name); 7537 } 7538 if (bp != null && bp.perm == p) { 7539 bp.perm = null; 7540 if (DEBUG_REMOVE && chatty) { 7541 if (r == null) { 7542 r = new StringBuilder(256); 7543 } else { 7544 r.append(' '); 7545 } 7546 r.append(p.info.name); 7547 } 7548 } 7549 if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 7550 ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(p.info.name); 7551 if (appOpPerms != null) { 7552 appOpPerms.remove(pkg.packageName); 7553 } 7554 } 7555 } 7556 if (r != null) { 7557 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 7558 } 7559 7560 N = pkg.requestedPermissions.size(); 7561 r = null; 7562 for (i=0; i<N; i++) { 7563 String perm = pkg.requestedPermissions.get(i); 7564 BasePermission bp = mSettings.mPermissions.get(perm); 7565 if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 7566 ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(perm); 7567 if (appOpPerms != null) { 7568 appOpPerms.remove(pkg.packageName); 7569 if (appOpPerms.isEmpty()) { 7570 mAppOpPermissionPackages.remove(perm); 7571 } 7572 } 7573 } 7574 } 7575 if (r != null) { 7576 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 7577 } 7578 7579 N = pkg.instrumentation.size(); 7580 r = null; 7581 for (i=0; i<N; i++) { 7582 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 7583 mInstrumentation.remove(a.getComponentName()); 7584 if (DEBUG_REMOVE && chatty) { 7585 if (r == null) { 7586 r = new StringBuilder(256); 7587 } else { 7588 r.append(' '); 7589 } 7590 r.append(a.info.name); 7591 } 7592 } 7593 if (r != null) { 7594 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 7595 } 7596 7597 r = null; 7598 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 7599 // Only system apps can hold shared libraries. 7600 if (pkg.libraryNames != null) { 7601 for (i=0; i<pkg.libraryNames.size(); i++) { 7602 String name = pkg.libraryNames.get(i); 7603 SharedLibraryEntry cur = mSharedLibraries.get(name); 7604 if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) { 7605 mSharedLibraries.remove(name); 7606 if (DEBUG_REMOVE && chatty) { 7607 if (r == null) { 7608 r = new StringBuilder(256); 7609 } else { 7610 r.append(' '); 7611 } 7612 r.append(name); 7613 } 7614 } 7615 } 7616 } 7617 } 7618 if (r != null) { 7619 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 7620 } 7621 } 7622 7623 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) { 7624 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) { 7625 if (pkgInfo.permissions.get(i).info.name.equals(perm)) { 7626 return true; 7627 } 7628 } 7629 return false; 7630 } 7631 7632 static final int UPDATE_PERMISSIONS_ALL = 1<<0; 7633 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1; 7634 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2; 7635 7636 private void updatePermissionsLPw(String changingPkg, 7637 PackageParser.Package pkgInfo, int flags) { 7638 // Make sure there are no dangling permission trees. 7639 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator(); 7640 while (it.hasNext()) { 7641 final BasePermission bp = it.next(); 7642 if (bp.packageSetting == null) { 7643 // We may not yet have parsed the package, so just see if 7644 // we still know about its settings. 7645 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 7646 } 7647 if (bp.packageSetting == null) { 7648 Slog.w(TAG, "Removing dangling permission tree: " + bp.name 7649 + " from package " + bp.sourcePackage); 7650 it.remove(); 7651 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 7652 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 7653 Slog.i(TAG, "Removing old permission tree: " + bp.name 7654 + " from package " + bp.sourcePackage); 7655 flags |= UPDATE_PERMISSIONS_ALL; 7656 it.remove(); 7657 } 7658 } 7659 } 7660 7661 // Make sure all dynamic permissions have been assigned to a package, 7662 // and make sure there are no dangling permissions. 7663 it = mSettings.mPermissions.values().iterator(); 7664 while (it.hasNext()) { 7665 final BasePermission bp = it.next(); 7666 if (bp.type == BasePermission.TYPE_DYNAMIC) { 7667 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name=" 7668 + bp.name + " pkg=" + bp.sourcePackage 7669 + " info=" + bp.pendingInfo); 7670 if (bp.packageSetting == null && bp.pendingInfo != null) { 7671 final BasePermission tree = findPermissionTreeLP(bp.name); 7672 if (tree != null && tree.perm != null) { 7673 bp.packageSetting = tree.packageSetting; 7674 bp.perm = new PackageParser.Permission(tree.perm.owner, 7675 new PermissionInfo(bp.pendingInfo)); 7676 bp.perm.info.packageName = tree.perm.info.packageName; 7677 bp.perm.info.name = bp.name; 7678 bp.uid = tree.uid; 7679 } 7680 } 7681 } 7682 if (bp.packageSetting == null) { 7683 // We may not yet have parsed the package, so just see if 7684 // we still know about its settings. 7685 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 7686 } 7687 if (bp.packageSetting == null) { 7688 Slog.w(TAG, "Removing dangling permission: " + bp.name 7689 + " from package " + bp.sourcePackage); 7690 it.remove(); 7691 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 7692 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 7693 Slog.i(TAG, "Removing old permission: " + bp.name 7694 + " from package " + bp.sourcePackage); 7695 flags |= UPDATE_PERMISSIONS_ALL; 7696 it.remove(); 7697 } 7698 } 7699 } 7700 7701 // Now update the permissions for all packages, in particular 7702 // replace the granted permissions of the system packages. 7703 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) { 7704 for (PackageParser.Package pkg : mPackages.values()) { 7705 if (pkg != pkgInfo) { 7706 grantPermissionsLPw(pkg, (flags&UPDATE_PERMISSIONS_REPLACE_ALL) != 0, 7707 changingPkg); 7708 } 7709 } 7710 } 7711 7712 if (pkgInfo != null) { 7713 grantPermissionsLPw(pkgInfo, (flags&UPDATE_PERMISSIONS_REPLACE_PKG) != 0, changingPkg); 7714 } 7715 } 7716 7717 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace, 7718 String packageOfInterest) { 7719 // IMPORTANT: There are two types of permissions: install and runtime. 7720 // Install time permissions are granted when the app is installed to 7721 // all device users and users added in the future. Runtime permissions 7722 // are granted at runtime explicitly to specific users. Normal and signature 7723 // protected permissions are install time permissions. Dangerous permissions 7724 // are install permissions if the app's target SDK is Lollipop MR1 or older, 7725 // otherwise they are runtime permissions. This function does not manage 7726 // runtime permissions except for the case an app targeting Lollipop MR1 7727 // being upgraded to target a newer SDK, in which case dangerous permissions 7728 // are transformed from install time to runtime ones. 7729 7730 final PackageSetting ps = (PackageSetting) pkg.mExtras; 7731 if (ps == null) { 7732 return; 7733 } 7734 7735 PermissionsState permissionsState = ps.getPermissionsState(); 7736 PermissionsState origPermissions = permissionsState; 7737 7738 final int[] currentUserIds = UserManagerService.getInstance().getUserIds(); 7739 7740 int[] upgradeUserIds = EMPTY_INT_ARRAY; 7741 int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY; 7742 7743 boolean changedInstallPermission = false; 7744 7745 if (replace) { 7746 ps.installPermissionsFixed = false; 7747 if (!ps.isSharedUser()) { 7748 origPermissions = new PermissionsState(permissionsState); 7749 permissionsState.reset(); 7750 } 7751 } 7752 7753 permissionsState.setGlobalGids(mGlobalGids); 7754 7755 final int N = pkg.requestedPermissions.size(); 7756 for (int i=0; i<N; i++) { 7757 final String name = pkg.requestedPermissions.get(i); 7758 final BasePermission bp = mSettings.mPermissions.get(name); 7759 7760 if (DEBUG_INSTALL) { 7761 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp); 7762 } 7763 7764 if (bp == null || bp.packageSetting == null) { 7765 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 7766 Slog.w(TAG, "Unknown permission " + name 7767 + " in package " + pkg.packageName); 7768 } 7769 continue; 7770 } 7771 7772 final String perm = bp.name; 7773 boolean allowedSig = false; 7774 int grant = GRANT_DENIED; 7775 7776 // Keep track of app op permissions. 7777 if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 7778 ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name); 7779 if (pkgs == null) { 7780 pkgs = new ArraySet<>(); 7781 mAppOpPermissionPackages.put(bp.name, pkgs); 7782 } 7783 pkgs.add(pkg.packageName); 7784 } 7785 7786 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE; 7787 switch (level) { 7788 case PermissionInfo.PROTECTION_NORMAL: { 7789 // For all apps normal permissions are install time ones. 7790 grant = GRANT_INSTALL; 7791 } break; 7792 7793 case PermissionInfo.PROTECTION_DANGEROUS: { 7794 if (pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1) { 7795 // For legacy apps dangerous permissions are install time ones. 7796 grant = GRANT_INSTALL_LEGACY; 7797 } else if (ps.isSystem()) { 7798 final int[] updatedUserIds = ps.getPermissionsUpdatedForUserIds(); 7799 if (origPermissions.hasInstallPermission(bp.name)) { 7800 // If a system app had an install permission, then the app was 7801 // upgraded and we grant the permissions as runtime to all users. 7802 grant = GRANT_UPGRADE; 7803 upgradeUserIds = currentUserIds; 7804 } else if (!Arrays.equals(updatedUserIds, currentUserIds)) { 7805 // If users changed since the last permissions update for a 7806 // system app, we grant the permission as runtime to the new users. 7807 grant = GRANT_UPGRADE; 7808 upgradeUserIds = currentUserIds; 7809 for (int userId : updatedUserIds) { 7810 upgradeUserIds = ArrayUtils.removeInt(upgradeUserIds, userId); 7811 } 7812 } else { 7813 // Otherwise, we grant the permission as runtime if the app 7814 // already had it, i.e. we preserve runtime permissions. 7815 grant = GRANT_RUNTIME; 7816 } 7817 } else if (origPermissions.hasInstallPermission(bp.name)) { 7818 // For legacy apps that became modern, install becomes runtime. 7819 grant = GRANT_UPGRADE; 7820 upgradeUserIds = currentUserIds; 7821 } else if (replace) { 7822 // For upgraded modern apps keep runtime permissions unchanged. 7823 grant = GRANT_RUNTIME; 7824 } 7825 } break; 7826 7827 case PermissionInfo.PROTECTION_SIGNATURE: { 7828 // For all apps signature permissions are install time ones. 7829 allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions); 7830 if (allowedSig) { 7831 grant = GRANT_INSTALL; 7832 } 7833 } break; 7834 } 7835 7836 if (DEBUG_INSTALL) { 7837 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm); 7838 } 7839 7840 if (grant != GRANT_DENIED) { 7841 if (!isSystemApp(ps) && ps.installPermissionsFixed) { 7842 // If this is an existing, non-system package, then 7843 // we can't add any new permissions to it. 7844 if (!allowedSig && !origPermissions.hasInstallPermission(perm)) { 7845 // Except... if this is a permission that was added 7846 // to the platform (note: need to only do this when 7847 // updating the platform). 7848 if (!isNewPlatformPermissionForPackage(perm, pkg)) { 7849 grant = GRANT_DENIED; 7850 } 7851 } 7852 } 7853 7854 switch (grant) { 7855 case GRANT_INSTALL: { 7856 // Revoke this as runtime permission to handle the case of 7857 // a runtime permssion being downgraded to an install one. 7858 for (int userId : UserManagerService.getInstance().getUserIds()) { 7859 if (origPermissions.getRuntimePermissionState( 7860 bp.name, userId) != null) { 7861 // Revoke the runtime permission and clear the flags. 7862 origPermissions.revokeRuntimePermission(bp, userId); 7863 origPermissions.updatePermissionFlags(bp, userId, 7864 PackageManager.MASK_PERMISSION_FLAGS, 0); 7865 // If we revoked a permission permission, we have to write. 7866 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 7867 changedRuntimePermissionUserIds, userId); 7868 } 7869 } 7870 // Grant an install permission. 7871 if (permissionsState.grantInstallPermission(bp) != 7872 PermissionsState.PERMISSION_OPERATION_FAILURE) { 7873 changedInstallPermission = true; 7874 } 7875 } break; 7876 7877 case GRANT_INSTALL_LEGACY: { 7878 // Grant an install permission. 7879 if (permissionsState.grantInstallPermission(bp) != 7880 PermissionsState.PERMISSION_OPERATION_FAILURE) { 7881 changedInstallPermission = true; 7882 } 7883 } break; 7884 7885 case GRANT_RUNTIME: { 7886 // Grant previously granted runtime permissions. 7887 for (int userId : UserManagerService.getInstance().getUserIds()) { 7888 if (origPermissions.hasRuntimePermission(bp.name, userId)) { 7889 PermissionState permissionState = origPermissions 7890 .getRuntimePermissionState(bp.name, userId); 7891 final int flags = permissionState.getFlags(); 7892 if (permissionsState.grantRuntimePermission(bp, userId) == 7893 PermissionsState.PERMISSION_OPERATION_FAILURE) { 7894 // If we cannot put the permission as it was, we have to write. 7895 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 7896 changedRuntimePermissionUserIds, userId); 7897 } else { 7898 // System components not only get the permissions but 7899 // they are also fixed, so nothing can change that. 7900 final int newFlags = !isSystemComponentOrPersistentPrivApp(pkg) 7901 ? flags 7902 : flags | PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 7903 // Propagate the permission flags. 7904 permissionsState.updatePermissionFlags(bp, userId, 7905 newFlags, newFlags); 7906 } 7907 } 7908 } 7909 } break; 7910 7911 case GRANT_UPGRADE: { 7912 // Grant runtime permissions for a previously held install permission. 7913 PermissionState permissionState = origPermissions 7914 .getInstallPermissionState(bp.name); 7915 final int flags = permissionState != null ? permissionState.getFlags() : 0; 7916 7917 origPermissions.revokeInstallPermission(bp); 7918 // We will be transferring the permission flags, so clear them. 7919 origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL, 7920 PackageManager.MASK_PERMISSION_FLAGS, 0); 7921 7922 // If the permission is not to be promoted to runtime we ignore it and 7923 // also its other flags as they are not applicable to install permissions. 7924 if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) { 7925 for (int userId : upgradeUserIds) { 7926 if (permissionsState.grantRuntimePermission(bp, userId) != 7927 PermissionsState.PERMISSION_OPERATION_FAILURE) { 7928 // System components not only get the permissions but 7929 // they are also fixed so nothing can change that. 7930 final int newFlags = !isSystemComponentOrPersistentPrivApp(pkg) 7931 ? flags 7932 : flags | PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 7933 // Transfer the permission flags. 7934 permissionsState.updatePermissionFlags(bp, userId, 7935 newFlags, newFlags); 7936 // If we granted the permission, we have to write. 7937 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 7938 changedRuntimePermissionUserIds, userId); 7939 } 7940 } 7941 } 7942 } break; 7943 7944 default: { 7945 if (packageOfInterest == null 7946 || packageOfInterest.equals(pkg.packageName)) { 7947 Slog.w(TAG, "Not granting permission " + perm 7948 + " to package " + pkg.packageName 7949 + " because it was previously installed without"); 7950 } 7951 } break; 7952 } 7953 } else { 7954 if (permissionsState.revokeInstallPermission(bp) != 7955 PermissionsState.PERMISSION_OPERATION_FAILURE) { 7956 // Also drop the permission flags. 7957 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 7958 PackageManager.MASK_PERMISSION_FLAGS, 0); 7959 changedInstallPermission = true; 7960 Slog.i(TAG, "Un-granting permission " + perm 7961 + " from package " + pkg.packageName 7962 + " (protectionLevel=" + bp.protectionLevel 7963 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 7964 + ")"); 7965 } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) { 7966 // Don't print warning for app op permissions, since it is fine for them 7967 // not to be granted, there is a UI for the user to decide. 7968 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 7969 Slog.w(TAG, "Not granting permission " + perm 7970 + " to package " + pkg.packageName 7971 + " (protectionLevel=" + bp.protectionLevel 7972 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 7973 + ")"); 7974 } 7975 } 7976 } 7977 } 7978 7979 if ((changedInstallPermission || replace) && !ps.installPermissionsFixed && 7980 !isSystemApp(ps) || isUpdatedSystemApp(ps)){ 7981 // This is the first that we have heard about this package, so the 7982 // permissions we have now selected are fixed until explicitly 7983 // changed. 7984 ps.installPermissionsFixed = true; 7985 } 7986 7987 ps.setPermissionsUpdatedForUserIds(currentUserIds); 7988 7989 // Persist the runtime permissions state for users with changes. 7990 for (int userId : changedRuntimePermissionUserIds) { 7991 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 7992 } 7993 } 7994 7995 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) { 7996 boolean allowed = false; 7997 final int NP = PackageParser.NEW_PERMISSIONS.length; 7998 for (int ip=0; ip<NP; ip++) { 7999 final PackageParser.NewPermissionInfo npi 8000 = PackageParser.NEW_PERMISSIONS[ip]; 8001 if (npi.name.equals(perm) 8002 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { 8003 allowed = true; 8004 Log.i(TAG, "Auto-granting " + perm + " to old pkg " 8005 + pkg.packageName); 8006 break; 8007 } 8008 } 8009 return allowed; 8010 } 8011 8012 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg, 8013 BasePermission bp, PermissionsState origPermissions) { 8014 boolean allowed; 8015 allowed = (compareSignatures( 8016 bp.packageSetting.signatures.mSignatures, pkg.mSignatures) 8017 == PackageManager.SIGNATURE_MATCH) 8018 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures) 8019 == PackageManager.SIGNATURE_MATCH); 8020 if (!allowed && (bp.protectionLevel 8021 & PermissionInfo.PROTECTION_FLAG_SYSTEM) != 0) { 8022 if (isSystemApp(pkg)) { 8023 // For updated system applications, a system permission 8024 // is granted only if it had been defined by the original application. 8025 if (pkg.isUpdatedSystemApp()) { 8026 final PackageSetting sysPs = mSettings 8027 .getDisabledSystemPkgLPr(pkg.packageName); 8028 if (sysPs.getPermissionsState().hasInstallPermission(perm)) { 8029 // If the original was granted this permission, we take 8030 // that grant decision as read and propagate it to the 8031 // update. 8032 if (sysPs.isPrivileged()) { 8033 allowed = true; 8034 } 8035 } else { 8036 // The system apk may have been updated with an older 8037 // version of the one on the data partition, but which 8038 // granted a new system permission that it didn't have 8039 // before. In this case we do want to allow the app to 8040 // now get the new permission if the ancestral apk is 8041 // privileged to get it. 8042 if (sysPs.pkg != null && sysPs.isPrivileged()) { 8043 for (int j=0; 8044 j<sysPs.pkg.requestedPermissions.size(); j++) { 8045 if (perm.equals( 8046 sysPs.pkg.requestedPermissions.get(j))) { 8047 allowed = true; 8048 break; 8049 } 8050 } 8051 } 8052 } 8053 } else { 8054 allowed = isPrivilegedApp(pkg); 8055 } 8056 } 8057 } 8058 if (!allowed && (bp.protectionLevel 8059 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) { 8060 // For development permissions, a development permission 8061 // is granted only if it was already granted. 8062 allowed = origPermissions.hasInstallPermission(perm); 8063 } 8064 return allowed; 8065 } 8066 8067 final class ActivityIntentResolver 8068 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 8069 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 8070 boolean defaultOnly, int userId) { 8071 if (!sUserManager.exists(userId)) return null; 8072 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 8073 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 8074 } 8075 8076 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 8077 int userId) { 8078 if (!sUserManager.exists(userId)) return null; 8079 mFlags = flags; 8080 return super.queryIntent(intent, resolvedType, 8081 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 8082 } 8083 8084 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 8085 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 8086 if (!sUserManager.exists(userId)) return null; 8087 if (packageActivities == null) { 8088 return null; 8089 } 8090 mFlags = flags; 8091 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 8092 final int N = packageActivities.size(); 8093 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 8094 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 8095 8096 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 8097 for (int i = 0; i < N; ++i) { 8098 intentFilters = packageActivities.get(i).intents; 8099 if (intentFilters != null && intentFilters.size() > 0) { 8100 PackageParser.ActivityIntentInfo[] array = 8101 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 8102 intentFilters.toArray(array); 8103 listCut.add(array); 8104 } 8105 } 8106 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 8107 } 8108 8109 public final void addActivity(PackageParser.Activity a, String type) { 8110 final boolean systemApp = a.info.applicationInfo.isSystemApp(); 8111 mActivities.put(a.getComponentName(), a); 8112 if (DEBUG_SHOW_INFO) 8113 Log.v( 8114 TAG, " " + type + " " + 8115 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 8116 if (DEBUG_SHOW_INFO) 8117 Log.v(TAG, " Class=" + a.info.name); 8118 final int NI = a.intents.size(); 8119 for (int j=0; j<NI; j++) { 8120 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 8121 if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) { 8122 intent.setPriority(0); 8123 Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity " 8124 + a.className + " with priority > 0, forcing to 0"); 8125 } 8126 if (DEBUG_SHOW_INFO) { 8127 Log.v(TAG, " IntentFilter:"); 8128 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8129 } 8130 if (!intent.debugCheck()) { 8131 Log.w(TAG, "==> For Activity " + a.info.name); 8132 } 8133 addFilter(intent); 8134 } 8135 } 8136 8137 public final void removeActivity(PackageParser.Activity a, String type) { 8138 mActivities.remove(a.getComponentName()); 8139 if (DEBUG_SHOW_INFO) { 8140 Log.v(TAG, " " + type + " " 8141 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 8142 : a.info.name) + ":"); 8143 Log.v(TAG, " Class=" + a.info.name); 8144 } 8145 final int NI = a.intents.size(); 8146 for (int j=0; j<NI; j++) { 8147 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 8148 if (DEBUG_SHOW_INFO) { 8149 Log.v(TAG, " IntentFilter:"); 8150 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8151 } 8152 removeFilter(intent); 8153 } 8154 } 8155 8156 @Override 8157 protected boolean allowFilterResult( 8158 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 8159 ActivityInfo filterAi = filter.activity.info; 8160 for (int i=dest.size()-1; i>=0; i--) { 8161 ActivityInfo destAi = dest.get(i).activityInfo; 8162 if (destAi.name == filterAi.name 8163 && destAi.packageName == filterAi.packageName) { 8164 return false; 8165 } 8166 } 8167 return true; 8168 } 8169 8170 @Override 8171 protected ActivityIntentInfo[] newArray(int size) { 8172 return new ActivityIntentInfo[size]; 8173 } 8174 8175 @Override 8176 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 8177 if (!sUserManager.exists(userId)) return true; 8178 PackageParser.Package p = filter.activity.owner; 8179 if (p != null) { 8180 PackageSetting ps = (PackageSetting)p.mExtras; 8181 if (ps != null) { 8182 // System apps are never considered stopped for purposes of 8183 // filtering, because there may be no way for the user to 8184 // actually re-launch them. 8185 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 8186 && ps.getStopped(userId); 8187 } 8188 } 8189 return false; 8190 } 8191 8192 @Override 8193 protected boolean isPackageForFilter(String packageName, 8194 PackageParser.ActivityIntentInfo info) { 8195 return packageName.equals(info.activity.owner.packageName); 8196 } 8197 8198 @Override 8199 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 8200 int match, int userId) { 8201 if (!sUserManager.exists(userId)) return null; 8202 if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) { 8203 return null; 8204 } 8205 final PackageParser.Activity activity = info.activity; 8206 if (mSafeMode && (activity.info.applicationInfo.flags 8207 &ApplicationInfo.FLAG_SYSTEM) == 0) { 8208 return null; 8209 } 8210 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 8211 if (ps == null) { 8212 return null; 8213 } 8214 ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags, 8215 ps.readUserState(userId), userId); 8216 if (ai == null) { 8217 return null; 8218 } 8219 final ResolveInfo res = new ResolveInfo(); 8220 res.activityInfo = ai; 8221 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 8222 res.filter = info; 8223 } 8224 if (info != null) { 8225 res.handleAllWebDataURI = info.handleAllWebDataURI(); 8226 } 8227 res.priority = info.getPriority(); 8228 res.preferredOrder = activity.owner.mPreferredOrder; 8229 //System.out.println("Result: " + res.activityInfo.className + 8230 // " = " + res.priority); 8231 res.match = match; 8232 res.isDefault = info.hasDefault; 8233 res.labelRes = info.labelRes; 8234 res.nonLocalizedLabel = info.nonLocalizedLabel; 8235 if (userNeedsBadging(userId)) { 8236 res.noResourceId = true; 8237 } else { 8238 res.icon = info.icon; 8239 } 8240 res.system = res.activityInfo.applicationInfo.isSystemApp(); 8241 return res; 8242 } 8243 8244 @Override 8245 protected void sortResults(List<ResolveInfo> results) { 8246 Collections.sort(results, mResolvePrioritySorter); 8247 } 8248 8249 @Override 8250 protected void dumpFilter(PrintWriter out, String prefix, 8251 PackageParser.ActivityIntentInfo filter) { 8252 out.print(prefix); out.print( 8253 Integer.toHexString(System.identityHashCode(filter.activity))); 8254 out.print(' '); 8255 filter.activity.printComponentShortName(out); 8256 out.print(" filter "); 8257 out.println(Integer.toHexString(System.identityHashCode(filter))); 8258 } 8259 8260 @Override 8261 protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) { 8262 return filter.activity; 8263 } 8264 8265 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 8266 PackageParser.Activity activity = (PackageParser.Activity)label; 8267 out.print(prefix); out.print( 8268 Integer.toHexString(System.identityHashCode(activity))); 8269 out.print(' '); 8270 activity.printComponentShortName(out); 8271 if (count > 1) { 8272 out.print(" ("); out.print(count); out.print(" filters)"); 8273 } 8274 out.println(); 8275 } 8276 8277// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 8278// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 8279// final List<ResolveInfo> retList = Lists.newArrayList(); 8280// while (i.hasNext()) { 8281// final ResolveInfo resolveInfo = i.next(); 8282// if (isEnabledLP(resolveInfo.activityInfo)) { 8283// retList.add(resolveInfo); 8284// } 8285// } 8286// return retList; 8287// } 8288 8289 // Keys are String (activity class name), values are Activity. 8290 private final ArrayMap<ComponentName, PackageParser.Activity> mActivities 8291 = new ArrayMap<ComponentName, PackageParser.Activity>(); 8292 private int mFlags; 8293 } 8294 8295 private final class ServiceIntentResolver 8296 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 8297 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 8298 boolean defaultOnly, int userId) { 8299 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 8300 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 8301 } 8302 8303 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 8304 int userId) { 8305 if (!sUserManager.exists(userId)) return null; 8306 mFlags = flags; 8307 return super.queryIntent(intent, resolvedType, 8308 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 8309 } 8310 8311 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 8312 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 8313 if (!sUserManager.exists(userId)) return null; 8314 if (packageServices == null) { 8315 return null; 8316 } 8317 mFlags = flags; 8318 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 8319 final int N = packageServices.size(); 8320 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 8321 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 8322 8323 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 8324 for (int i = 0; i < N; ++i) { 8325 intentFilters = packageServices.get(i).intents; 8326 if (intentFilters != null && intentFilters.size() > 0) { 8327 PackageParser.ServiceIntentInfo[] array = 8328 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 8329 intentFilters.toArray(array); 8330 listCut.add(array); 8331 } 8332 } 8333 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 8334 } 8335 8336 public final void addService(PackageParser.Service s) { 8337 mServices.put(s.getComponentName(), s); 8338 if (DEBUG_SHOW_INFO) { 8339 Log.v(TAG, " " 8340 + (s.info.nonLocalizedLabel != null 8341 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 8342 Log.v(TAG, " Class=" + s.info.name); 8343 } 8344 final int NI = s.intents.size(); 8345 int j; 8346 for (j=0; j<NI; j++) { 8347 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 8348 if (DEBUG_SHOW_INFO) { 8349 Log.v(TAG, " IntentFilter:"); 8350 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8351 } 8352 if (!intent.debugCheck()) { 8353 Log.w(TAG, "==> For Service " + s.info.name); 8354 } 8355 addFilter(intent); 8356 } 8357 } 8358 8359 public final void removeService(PackageParser.Service s) { 8360 mServices.remove(s.getComponentName()); 8361 if (DEBUG_SHOW_INFO) { 8362 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 8363 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 8364 Log.v(TAG, " Class=" + s.info.name); 8365 } 8366 final int NI = s.intents.size(); 8367 int j; 8368 for (j=0; j<NI; j++) { 8369 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 8370 if (DEBUG_SHOW_INFO) { 8371 Log.v(TAG, " IntentFilter:"); 8372 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8373 } 8374 removeFilter(intent); 8375 } 8376 } 8377 8378 @Override 8379 protected boolean allowFilterResult( 8380 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 8381 ServiceInfo filterSi = filter.service.info; 8382 for (int i=dest.size()-1; i>=0; i--) { 8383 ServiceInfo destAi = dest.get(i).serviceInfo; 8384 if (destAi.name == filterSi.name 8385 && destAi.packageName == filterSi.packageName) { 8386 return false; 8387 } 8388 } 8389 return true; 8390 } 8391 8392 @Override 8393 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 8394 return new PackageParser.ServiceIntentInfo[size]; 8395 } 8396 8397 @Override 8398 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 8399 if (!sUserManager.exists(userId)) return true; 8400 PackageParser.Package p = filter.service.owner; 8401 if (p != null) { 8402 PackageSetting ps = (PackageSetting)p.mExtras; 8403 if (ps != null) { 8404 // System apps are never considered stopped for purposes of 8405 // filtering, because there may be no way for the user to 8406 // actually re-launch them. 8407 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 8408 && ps.getStopped(userId); 8409 } 8410 } 8411 return false; 8412 } 8413 8414 @Override 8415 protected boolean isPackageForFilter(String packageName, 8416 PackageParser.ServiceIntentInfo info) { 8417 return packageName.equals(info.service.owner.packageName); 8418 } 8419 8420 @Override 8421 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 8422 int match, int userId) { 8423 if (!sUserManager.exists(userId)) return null; 8424 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 8425 if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) { 8426 return null; 8427 } 8428 final PackageParser.Service service = info.service; 8429 if (mSafeMode && (service.info.applicationInfo.flags 8430 &ApplicationInfo.FLAG_SYSTEM) == 0) { 8431 return null; 8432 } 8433 PackageSetting ps = (PackageSetting) service.owner.mExtras; 8434 if (ps == null) { 8435 return null; 8436 } 8437 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 8438 ps.readUserState(userId), userId); 8439 if (si == null) { 8440 return null; 8441 } 8442 final ResolveInfo res = new ResolveInfo(); 8443 res.serviceInfo = si; 8444 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 8445 res.filter = filter; 8446 } 8447 res.priority = info.getPriority(); 8448 res.preferredOrder = service.owner.mPreferredOrder; 8449 res.match = match; 8450 res.isDefault = info.hasDefault; 8451 res.labelRes = info.labelRes; 8452 res.nonLocalizedLabel = info.nonLocalizedLabel; 8453 res.icon = info.icon; 8454 res.system = res.serviceInfo.applicationInfo.isSystemApp(); 8455 return res; 8456 } 8457 8458 @Override 8459 protected void sortResults(List<ResolveInfo> results) { 8460 Collections.sort(results, mResolvePrioritySorter); 8461 } 8462 8463 @Override 8464 protected void dumpFilter(PrintWriter out, String prefix, 8465 PackageParser.ServiceIntentInfo filter) { 8466 out.print(prefix); out.print( 8467 Integer.toHexString(System.identityHashCode(filter.service))); 8468 out.print(' '); 8469 filter.service.printComponentShortName(out); 8470 out.print(" filter "); 8471 out.println(Integer.toHexString(System.identityHashCode(filter))); 8472 } 8473 8474 @Override 8475 protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) { 8476 return filter.service; 8477 } 8478 8479 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 8480 PackageParser.Service service = (PackageParser.Service)label; 8481 out.print(prefix); out.print( 8482 Integer.toHexString(System.identityHashCode(service))); 8483 out.print(' '); 8484 service.printComponentShortName(out); 8485 if (count > 1) { 8486 out.print(" ("); out.print(count); out.print(" filters)"); 8487 } 8488 out.println(); 8489 } 8490 8491// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 8492// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 8493// final List<ResolveInfo> retList = Lists.newArrayList(); 8494// while (i.hasNext()) { 8495// final ResolveInfo resolveInfo = (ResolveInfo) i; 8496// if (isEnabledLP(resolveInfo.serviceInfo)) { 8497// retList.add(resolveInfo); 8498// } 8499// } 8500// return retList; 8501// } 8502 8503 // Keys are String (activity class name), values are Activity. 8504 private final ArrayMap<ComponentName, PackageParser.Service> mServices 8505 = new ArrayMap<ComponentName, PackageParser.Service>(); 8506 private int mFlags; 8507 }; 8508 8509 private final class ProviderIntentResolver 8510 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 8511 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 8512 boolean defaultOnly, int userId) { 8513 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 8514 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 8515 } 8516 8517 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 8518 int userId) { 8519 if (!sUserManager.exists(userId)) 8520 return null; 8521 mFlags = flags; 8522 return super.queryIntent(intent, resolvedType, 8523 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 8524 } 8525 8526 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 8527 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 8528 if (!sUserManager.exists(userId)) 8529 return null; 8530 if (packageProviders == null) { 8531 return null; 8532 } 8533 mFlags = flags; 8534 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 8535 final int N = packageProviders.size(); 8536 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 8537 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 8538 8539 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 8540 for (int i = 0; i < N; ++i) { 8541 intentFilters = packageProviders.get(i).intents; 8542 if (intentFilters != null && intentFilters.size() > 0) { 8543 PackageParser.ProviderIntentInfo[] array = 8544 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 8545 intentFilters.toArray(array); 8546 listCut.add(array); 8547 } 8548 } 8549 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 8550 } 8551 8552 public final void addProvider(PackageParser.Provider p) { 8553 if (mProviders.containsKey(p.getComponentName())) { 8554 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 8555 return; 8556 } 8557 8558 mProviders.put(p.getComponentName(), p); 8559 if (DEBUG_SHOW_INFO) { 8560 Log.v(TAG, " " 8561 + (p.info.nonLocalizedLabel != null 8562 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 8563 Log.v(TAG, " Class=" + p.info.name); 8564 } 8565 final int NI = p.intents.size(); 8566 int j; 8567 for (j = 0; j < NI; j++) { 8568 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 8569 if (DEBUG_SHOW_INFO) { 8570 Log.v(TAG, " IntentFilter:"); 8571 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8572 } 8573 if (!intent.debugCheck()) { 8574 Log.w(TAG, "==> For Provider " + p.info.name); 8575 } 8576 addFilter(intent); 8577 } 8578 } 8579 8580 public final void removeProvider(PackageParser.Provider p) { 8581 mProviders.remove(p.getComponentName()); 8582 if (DEBUG_SHOW_INFO) { 8583 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 8584 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 8585 Log.v(TAG, " Class=" + p.info.name); 8586 } 8587 final int NI = p.intents.size(); 8588 int j; 8589 for (j = 0; j < NI; j++) { 8590 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 8591 if (DEBUG_SHOW_INFO) { 8592 Log.v(TAG, " IntentFilter:"); 8593 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8594 } 8595 removeFilter(intent); 8596 } 8597 } 8598 8599 @Override 8600 protected boolean allowFilterResult( 8601 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 8602 ProviderInfo filterPi = filter.provider.info; 8603 for (int i = dest.size() - 1; i >= 0; i--) { 8604 ProviderInfo destPi = dest.get(i).providerInfo; 8605 if (destPi.name == filterPi.name 8606 && destPi.packageName == filterPi.packageName) { 8607 return false; 8608 } 8609 } 8610 return true; 8611 } 8612 8613 @Override 8614 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 8615 return new PackageParser.ProviderIntentInfo[size]; 8616 } 8617 8618 @Override 8619 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 8620 if (!sUserManager.exists(userId)) 8621 return true; 8622 PackageParser.Package p = filter.provider.owner; 8623 if (p != null) { 8624 PackageSetting ps = (PackageSetting) p.mExtras; 8625 if (ps != null) { 8626 // System apps are never considered stopped for purposes of 8627 // filtering, because there may be no way for the user to 8628 // actually re-launch them. 8629 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 8630 && ps.getStopped(userId); 8631 } 8632 } 8633 return false; 8634 } 8635 8636 @Override 8637 protected boolean isPackageForFilter(String packageName, 8638 PackageParser.ProviderIntentInfo info) { 8639 return packageName.equals(info.provider.owner.packageName); 8640 } 8641 8642 @Override 8643 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 8644 int match, int userId) { 8645 if (!sUserManager.exists(userId)) 8646 return null; 8647 final PackageParser.ProviderIntentInfo info = filter; 8648 if (!mSettings.isEnabledLPr(info.provider.info, mFlags, userId)) { 8649 return null; 8650 } 8651 final PackageParser.Provider provider = info.provider; 8652 if (mSafeMode && (provider.info.applicationInfo.flags 8653 & ApplicationInfo.FLAG_SYSTEM) == 0) { 8654 return null; 8655 } 8656 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 8657 if (ps == null) { 8658 return null; 8659 } 8660 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 8661 ps.readUserState(userId), userId); 8662 if (pi == null) { 8663 return null; 8664 } 8665 final ResolveInfo res = new ResolveInfo(); 8666 res.providerInfo = pi; 8667 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 8668 res.filter = filter; 8669 } 8670 res.priority = info.getPriority(); 8671 res.preferredOrder = provider.owner.mPreferredOrder; 8672 res.match = match; 8673 res.isDefault = info.hasDefault; 8674 res.labelRes = info.labelRes; 8675 res.nonLocalizedLabel = info.nonLocalizedLabel; 8676 res.icon = info.icon; 8677 res.system = res.providerInfo.applicationInfo.isSystemApp(); 8678 return res; 8679 } 8680 8681 @Override 8682 protected void sortResults(List<ResolveInfo> results) { 8683 Collections.sort(results, mResolvePrioritySorter); 8684 } 8685 8686 @Override 8687 protected void dumpFilter(PrintWriter out, String prefix, 8688 PackageParser.ProviderIntentInfo filter) { 8689 out.print(prefix); 8690 out.print( 8691 Integer.toHexString(System.identityHashCode(filter.provider))); 8692 out.print(' '); 8693 filter.provider.printComponentShortName(out); 8694 out.print(" filter "); 8695 out.println(Integer.toHexString(System.identityHashCode(filter))); 8696 } 8697 8698 @Override 8699 protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) { 8700 return filter.provider; 8701 } 8702 8703 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 8704 PackageParser.Provider provider = (PackageParser.Provider)label; 8705 out.print(prefix); out.print( 8706 Integer.toHexString(System.identityHashCode(provider))); 8707 out.print(' '); 8708 provider.printComponentShortName(out); 8709 if (count > 1) { 8710 out.print(" ("); out.print(count); out.print(" filters)"); 8711 } 8712 out.println(); 8713 } 8714 8715 private final ArrayMap<ComponentName, PackageParser.Provider> mProviders 8716 = new ArrayMap<ComponentName, PackageParser.Provider>(); 8717 private int mFlags; 8718 }; 8719 8720 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 8721 new Comparator<ResolveInfo>() { 8722 public int compare(ResolveInfo r1, ResolveInfo r2) { 8723 int v1 = r1.priority; 8724 int v2 = r2.priority; 8725 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 8726 if (v1 != v2) { 8727 return (v1 > v2) ? -1 : 1; 8728 } 8729 v1 = r1.preferredOrder; 8730 v2 = r2.preferredOrder; 8731 if (v1 != v2) { 8732 return (v1 > v2) ? -1 : 1; 8733 } 8734 if (r1.isDefault != r2.isDefault) { 8735 return r1.isDefault ? -1 : 1; 8736 } 8737 v1 = r1.match; 8738 v2 = r2.match; 8739 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 8740 if (v1 != v2) { 8741 return (v1 > v2) ? -1 : 1; 8742 } 8743 if (r1.system != r2.system) { 8744 return r1.system ? -1 : 1; 8745 } 8746 return 0; 8747 } 8748 }; 8749 8750 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 8751 new Comparator<ProviderInfo>() { 8752 public int compare(ProviderInfo p1, ProviderInfo p2) { 8753 final int v1 = p1.initOrder; 8754 final int v2 = p2.initOrder; 8755 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 8756 } 8757 }; 8758 8759 final void sendPackageBroadcast(final String action, final String pkg, 8760 final Bundle extras, final String targetPkg, final IIntentReceiver finishedReceiver, 8761 final int[] userIds) { 8762 mHandler.post(new Runnable() { 8763 @Override 8764 public void run() { 8765 try { 8766 final IActivityManager am = ActivityManagerNative.getDefault(); 8767 if (am == null) return; 8768 final int[] resolvedUserIds; 8769 if (userIds == null) { 8770 resolvedUserIds = am.getRunningUserIds(); 8771 } else { 8772 resolvedUserIds = userIds; 8773 } 8774 for (int id : resolvedUserIds) { 8775 final Intent intent = new Intent(action, 8776 pkg != null ? Uri.fromParts("package", pkg, null) : null); 8777 if (extras != null) { 8778 intent.putExtras(extras); 8779 } 8780 if (targetPkg != null) { 8781 intent.setPackage(targetPkg); 8782 } 8783 // Modify the UID when posting to other users 8784 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 8785 if (uid > 0 && UserHandle.getUserId(uid) != id) { 8786 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 8787 intent.putExtra(Intent.EXTRA_UID, uid); 8788 } 8789 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 8790 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT); 8791 if (DEBUG_BROADCASTS) { 8792 RuntimeException here = new RuntimeException("here"); 8793 here.fillInStackTrace(); 8794 Slog.d(TAG, "Sending to user " + id + ": " 8795 + intent.toShortString(false, true, false, false) 8796 + " " + intent.getExtras(), here); 8797 } 8798 am.broadcastIntent(null, intent, null, finishedReceiver, 8799 0, null, null, null, android.app.AppOpsManager.OP_NONE, 8800 finishedReceiver != null, false, id); 8801 } 8802 } catch (RemoteException ex) { 8803 } 8804 } 8805 }); 8806 } 8807 8808 /** 8809 * Check if the external storage media is available. This is true if there 8810 * is a mounted external storage medium or if the external storage is 8811 * emulated. 8812 */ 8813 private boolean isExternalMediaAvailable() { 8814 return mMediaMounted || Environment.isExternalStorageEmulated(); 8815 } 8816 8817 @Override 8818 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 8819 // writer 8820 synchronized (mPackages) { 8821 if (!isExternalMediaAvailable()) { 8822 // If the external storage is no longer mounted at this point, 8823 // the caller may not have been able to delete all of this 8824 // packages files and can not delete any more. Bail. 8825 return null; 8826 } 8827 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 8828 if (lastPackage != null) { 8829 pkgs.remove(lastPackage); 8830 } 8831 if (pkgs.size() > 0) { 8832 return pkgs.get(0); 8833 } 8834 } 8835 return null; 8836 } 8837 8838 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 8839 final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE, 8840 userId, andCode ? 1 : 0, packageName); 8841 if (mSystemReady) { 8842 msg.sendToTarget(); 8843 } else { 8844 if (mPostSystemReadyMessages == null) { 8845 mPostSystemReadyMessages = new ArrayList<>(); 8846 } 8847 mPostSystemReadyMessages.add(msg); 8848 } 8849 } 8850 8851 void startCleaningPackages() { 8852 // reader 8853 synchronized (mPackages) { 8854 if (!isExternalMediaAvailable()) { 8855 return; 8856 } 8857 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 8858 return; 8859 } 8860 } 8861 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 8862 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 8863 IActivityManager am = ActivityManagerNative.getDefault(); 8864 if (am != null) { 8865 try { 8866 am.startService(null, intent, null, UserHandle.USER_OWNER); 8867 } catch (RemoteException e) { 8868 } 8869 } 8870 } 8871 8872 @Override 8873 public void installPackage(String originPath, IPackageInstallObserver2 observer, 8874 int installFlags, String installerPackageName, VerificationParams verificationParams, 8875 String packageAbiOverride) { 8876 installPackageAsUser(originPath, observer, installFlags, installerPackageName, 8877 verificationParams, packageAbiOverride, UserHandle.getCallingUserId()); 8878 } 8879 8880 @Override 8881 public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer, 8882 int installFlags, String installerPackageName, VerificationParams verificationParams, 8883 String packageAbiOverride, int userId) { 8884 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null); 8885 8886 final int callingUid = Binder.getCallingUid(); 8887 enforceCrossUserPermission(callingUid, userId, true, true, "installPackageAsUser"); 8888 8889 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 8890 try { 8891 if (observer != null) { 8892 observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null); 8893 } 8894 } catch (RemoteException re) { 8895 } 8896 return; 8897 } 8898 8899 if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) { 8900 installFlags |= PackageManager.INSTALL_FROM_ADB; 8901 8902 } else { 8903 // Caller holds INSTALL_PACKAGES permission, so we're less strict 8904 // about installerPackageName. 8905 8906 installFlags &= ~PackageManager.INSTALL_FROM_ADB; 8907 installFlags &= ~PackageManager.INSTALL_ALL_USERS; 8908 } 8909 8910 UserHandle user; 8911 if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) { 8912 user = UserHandle.ALL; 8913 } else { 8914 user = new UserHandle(userId); 8915 } 8916 8917 // Only system components can circumvent runtime permissions when installing. 8918 if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0 8919 && mContext.checkCallingOrSelfPermission(Manifest.permission 8920 .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) { 8921 throw new SecurityException("You need the " 8922 + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission " 8923 + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag"); 8924 } 8925 8926 verificationParams.setInstallerUid(callingUid); 8927 8928 final File originFile = new File(originPath); 8929 final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile); 8930 8931 final Message msg = mHandler.obtainMessage(INIT_COPY); 8932 msg.obj = new InstallParams(origin, null, observer, installFlags, installerPackageName, 8933 null, verificationParams, user, packageAbiOverride); 8934 mHandler.sendMessage(msg); 8935 } 8936 8937 void installStage(String packageName, File stagedDir, String stagedCid, 8938 IPackageInstallObserver2 observer, PackageInstaller.SessionParams params, 8939 String installerPackageName, int installerUid, UserHandle user) { 8940 final VerificationParams verifParams = new VerificationParams(null, params.originatingUri, 8941 params.referrerUri, installerUid, null); 8942 8943 final OriginInfo origin; 8944 if (stagedDir != null) { 8945 origin = OriginInfo.fromStagedFile(stagedDir); 8946 } else { 8947 origin = OriginInfo.fromStagedContainer(stagedCid); 8948 } 8949 8950 final Message msg = mHandler.obtainMessage(INIT_COPY); 8951 msg.obj = new InstallParams(origin, null, observer, params.installFlags, 8952 installerPackageName, params.volumeUuid, verifParams, user, params.abiOverride); 8953 mHandler.sendMessage(msg); 8954 } 8955 8956 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) { 8957 Bundle extras = new Bundle(1); 8958 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId)); 8959 8960 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 8961 packageName, extras, null, null, new int[] {userId}); 8962 try { 8963 IActivityManager am = ActivityManagerNative.getDefault(); 8964 final boolean isSystem = 8965 isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 8966 if (isSystem && am.isUserRunning(userId, false)) { 8967 // The just-installed/enabled app is bundled on the system, so presumed 8968 // to be able to run automatically without needing an explicit launch. 8969 // Send it a BOOT_COMPLETED if it would ordinarily have gotten one. 8970 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED) 8971 .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES) 8972 .setPackage(packageName); 8973 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null, 8974 android.app.AppOpsManager.OP_NONE, false, false, userId); 8975 } 8976 } catch (RemoteException e) { 8977 // shouldn't happen 8978 Slog.w(TAG, "Unable to bootstrap installed package", e); 8979 } 8980 } 8981 8982 @Override 8983 public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden, 8984 int userId) { 8985 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 8986 PackageSetting pkgSetting; 8987 final int uid = Binder.getCallingUid(); 8988 enforceCrossUserPermission(uid, userId, true, true, 8989 "setApplicationHiddenSetting for user " + userId); 8990 8991 if (hidden && isPackageDeviceAdmin(packageName, userId)) { 8992 Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin"); 8993 return false; 8994 } 8995 8996 long callingId = Binder.clearCallingIdentity(); 8997 try { 8998 boolean sendAdded = false; 8999 boolean sendRemoved = false; 9000 // writer 9001 synchronized (mPackages) { 9002 pkgSetting = mSettings.mPackages.get(packageName); 9003 if (pkgSetting == null) { 9004 return false; 9005 } 9006 if (pkgSetting.getHidden(userId) != hidden) { 9007 pkgSetting.setHidden(hidden, userId); 9008 mSettings.writePackageRestrictionsLPr(userId); 9009 if (hidden) { 9010 sendRemoved = true; 9011 } else { 9012 sendAdded = true; 9013 } 9014 } 9015 } 9016 if (sendAdded) { 9017 sendPackageAddedForUser(packageName, pkgSetting, userId); 9018 return true; 9019 } 9020 if (sendRemoved) { 9021 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 9022 "hiding pkg"); 9023 sendApplicationHiddenForUser(packageName, pkgSetting, userId); 9024 } 9025 } finally { 9026 Binder.restoreCallingIdentity(callingId); 9027 } 9028 return false; 9029 } 9030 9031 private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting, 9032 int userId) { 9033 final PackageRemovedInfo info = new PackageRemovedInfo(); 9034 info.removedPackage = packageName; 9035 info.removedUsers = new int[] {userId}; 9036 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 9037 info.sendBroadcast(false, false, false); 9038 } 9039 9040 /** 9041 * Returns true if application is not found or there was an error. Otherwise it returns 9042 * the hidden state of the package for the given user. 9043 */ 9044 @Override 9045 public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) { 9046 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 9047 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, 9048 false, "getApplicationHidden for user " + userId); 9049 PackageSetting pkgSetting; 9050 long callingId = Binder.clearCallingIdentity(); 9051 try { 9052 // writer 9053 synchronized (mPackages) { 9054 pkgSetting = mSettings.mPackages.get(packageName); 9055 if (pkgSetting == null) { 9056 return true; 9057 } 9058 return pkgSetting.getHidden(userId); 9059 } 9060 } finally { 9061 Binder.restoreCallingIdentity(callingId); 9062 } 9063 } 9064 9065 /** 9066 * @hide 9067 */ 9068 @Override 9069 public int installExistingPackageAsUser(String packageName, int userId) { 9070 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 9071 null); 9072 PackageSetting pkgSetting; 9073 final int uid = Binder.getCallingUid(); 9074 enforceCrossUserPermission(uid, userId, true, true, "installExistingPackage for user " 9075 + userId); 9076 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 9077 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 9078 } 9079 9080 long callingId = Binder.clearCallingIdentity(); 9081 try { 9082 boolean sendAdded = false; 9083 9084 // writer 9085 synchronized (mPackages) { 9086 pkgSetting = mSettings.mPackages.get(packageName); 9087 if (pkgSetting == null) { 9088 return PackageManager.INSTALL_FAILED_INVALID_URI; 9089 } 9090 if (!pkgSetting.getInstalled(userId)) { 9091 pkgSetting.setInstalled(true, userId); 9092 pkgSetting.setHidden(false, userId); 9093 mSettings.writePackageRestrictionsLPr(userId); 9094 sendAdded = true; 9095 } 9096 } 9097 9098 if (sendAdded) { 9099 sendPackageAddedForUser(packageName, pkgSetting, userId); 9100 } 9101 } finally { 9102 Binder.restoreCallingIdentity(callingId); 9103 } 9104 9105 return PackageManager.INSTALL_SUCCEEDED; 9106 } 9107 9108 boolean isUserRestricted(int userId, String restrictionKey) { 9109 Bundle restrictions = sUserManager.getUserRestrictions(userId); 9110 if (restrictions.getBoolean(restrictionKey, false)) { 9111 Log.w(TAG, "User is restricted: " + restrictionKey); 9112 return true; 9113 } 9114 return false; 9115 } 9116 9117 @Override 9118 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 9119 mContext.enforceCallingOrSelfPermission( 9120 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 9121 "Only package verification agents can verify applications"); 9122 9123 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 9124 final PackageVerificationResponse response = new PackageVerificationResponse( 9125 verificationCode, Binder.getCallingUid()); 9126 msg.arg1 = id; 9127 msg.obj = response; 9128 mHandler.sendMessage(msg); 9129 } 9130 9131 @Override 9132 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 9133 long millisecondsToDelay) { 9134 mContext.enforceCallingOrSelfPermission( 9135 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 9136 "Only package verification agents can extend verification timeouts"); 9137 9138 final PackageVerificationState state = mPendingVerification.get(id); 9139 final PackageVerificationResponse response = new PackageVerificationResponse( 9140 verificationCodeAtTimeout, Binder.getCallingUid()); 9141 9142 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 9143 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 9144 } 9145 if (millisecondsToDelay < 0) { 9146 millisecondsToDelay = 0; 9147 } 9148 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 9149 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 9150 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 9151 } 9152 9153 if ((state != null) && !state.timeoutExtended()) { 9154 state.extendTimeout(); 9155 9156 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 9157 msg.arg1 = id; 9158 msg.obj = response; 9159 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 9160 } 9161 } 9162 9163 private void broadcastPackageVerified(int verificationId, Uri packageUri, 9164 int verificationCode, UserHandle user) { 9165 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 9166 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 9167 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 9168 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 9169 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 9170 9171 mContext.sendBroadcastAsUser(intent, user, 9172 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 9173 } 9174 9175 private ComponentName matchComponentForVerifier(String packageName, 9176 List<ResolveInfo> receivers) { 9177 ActivityInfo targetReceiver = null; 9178 9179 final int NR = receivers.size(); 9180 for (int i = 0; i < NR; i++) { 9181 final ResolveInfo info = receivers.get(i); 9182 if (info.activityInfo == null) { 9183 continue; 9184 } 9185 9186 if (packageName.equals(info.activityInfo.packageName)) { 9187 targetReceiver = info.activityInfo; 9188 break; 9189 } 9190 } 9191 9192 if (targetReceiver == null) { 9193 return null; 9194 } 9195 9196 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 9197 } 9198 9199 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 9200 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 9201 if (pkgInfo.verifiers.length == 0) { 9202 return null; 9203 } 9204 9205 final int N = pkgInfo.verifiers.length; 9206 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 9207 for (int i = 0; i < N; i++) { 9208 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 9209 9210 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 9211 receivers); 9212 if (comp == null) { 9213 continue; 9214 } 9215 9216 final int verifierUid = getUidForVerifier(verifierInfo); 9217 if (verifierUid == -1) { 9218 continue; 9219 } 9220 9221 if (DEBUG_VERIFY) { 9222 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 9223 + " with the correct signature"); 9224 } 9225 sufficientVerifiers.add(comp); 9226 verificationState.addSufficientVerifier(verifierUid); 9227 } 9228 9229 return sufficientVerifiers; 9230 } 9231 9232 private int getUidForVerifier(VerifierInfo verifierInfo) { 9233 synchronized (mPackages) { 9234 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 9235 if (pkg == null) { 9236 return -1; 9237 } else if (pkg.mSignatures.length != 1) { 9238 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 9239 + " has more than one signature; ignoring"); 9240 return -1; 9241 } 9242 9243 /* 9244 * If the public key of the package's signature does not match 9245 * our expected public key, then this is a different package and 9246 * we should skip. 9247 */ 9248 9249 final byte[] expectedPublicKey; 9250 try { 9251 final Signature verifierSig = pkg.mSignatures[0]; 9252 final PublicKey publicKey = verifierSig.getPublicKey(); 9253 expectedPublicKey = publicKey.getEncoded(); 9254 } catch (CertificateException e) { 9255 return -1; 9256 } 9257 9258 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 9259 9260 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 9261 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 9262 + " does not have the expected public key; ignoring"); 9263 return -1; 9264 } 9265 9266 return pkg.applicationInfo.uid; 9267 } 9268 } 9269 9270 @Override 9271 public void finishPackageInstall(int token) { 9272 enforceSystemOrRoot("Only the system is allowed to finish installs"); 9273 9274 if (DEBUG_INSTALL) { 9275 Slog.v(TAG, "BM finishing package install for " + token); 9276 } 9277 9278 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 9279 mHandler.sendMessage(msg); 9280 } 9281 9282 /** 9283 * Get the verification agent timeout. 9284 * 9285 * @return verification timeout in milliseconds 9286 */ 9287 private long getVerificationTimeout() { 9288 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 9289 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 9290 DEFAULT_VERIFICATION_TIMEOUT); 9291 } 9292 9293 /** 9294 * Get the default verification agent response code. 9295 * 9296 * @return default verification response code 9297 */ 9298 private int getDefaultVerificationResponse() { 9299 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 9300 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 9301 DEFAULT_VERIFICATION_RESPONSE); 9302 } 9303 9304 /** 9305 * Check whether or not package verification has been enabled. 9306 * 9307 * @return true if verification should be performed 9308 */ 9309 private boolean isVerificationEnabled(int userId, int installFlags) { 9310 if (!DEFAULT_VERIFY_ENABLE) { 9311 return false; 9312 } 9313 9314 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 9315 9316 // Check if installing from ADB 9317 if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) { 9318 // Do not run verification in a test harness environment 9319 if (ActivityManager.isRunningInTestHarness()) { 9320 return false; 9321 } 9322 if (ensureVerifyAppsEnabled) { 9323 return true; 9324 } 9325 // Check if the developer does not want package verification for ADB installs 9326 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 9327 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 9328 return false; 9329 } 9330 } 9331 9332 if (ensureVerifyAppsEnabled) { 9333 return true; 9334 } 9335 9336 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 9337 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 9338 } 9339 9340 @Override 9341 public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains) 9342 throws RemoteException { 9343 mContext.enforceCallingOrSelfPermission( 9344 Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 9345 "Only intentfilter verification agents can verify applications"); 9346 9347 final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED); 9348 final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse( 9349 Binder.getCallingUid(), verificationCode, failedDomains); 9350 msg.arg1 = id; 9351 msg.obj = response; 9352 mHandler.sendMessage(msg); 9353 } 9354 9355 @Override 9356 public int getIntentVerificationStatus(String packageName, int userId) { 9357 synchronized (mPackages) { 9358 return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 9359 } 9360 } 9361 9362 @Override 9363 public boolean updateIntentVerificationStatus(String packageName, int status, int userId) { 9364 boolean result = false; 9365 synchronized (mPackages) { 9366 result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId); 9367 } 9368 if (result) { 9369 scheduleWritePackageRestrictionsLocked(userId); 9370 } 9371 return result; 9372 } 9373 9374 @Override 9375 public List<IntentFilterVerificationInfo> getIntentFilterVerifications(String packageName) { 9376 synchronized (mPackages) { 9377 return mSettings.getIntentFilterVerificationsLPr(packageName); 9378 } 9379 } 9380 9381 @Override 9382 public List<IntentFilter> getAllIntentFilters(String packageName) { 9383 if (TextUtils.isEmpty(packageName)) { 9384 return Collections.<IntentFilter>emptyList(); 9385 } 9386 synchronized (mPackages) { 9387 PackageParser.Package pkg = mPackages.get(packageName); 9388 if (pkg == null || pkg.activities == null) { 9389 return Collections.<IntentFilter>emptyList(); 9390 } 9391 final int count = pkg.activities.size(); 9392 ArrayList<IntentFilter> result = new ArrayList<>(); 9393 for (int n=0; n<count; n++) { 9394 PackageParser.Activity activity = pkg.activities.get(n); 9395 if (activity.intents != null || activity.intents.size() > 0) { 9396 result.addAll(activity.intents); 9397 } 9398 } 9399 return result; 9400 } 9401 } 9402 9403 @Override 9404 public boolean setDefaultBrowserPackageName(String packageName, int userId) { 9405 synchronized (mPackages) { 9406 boolean result = mSettings.setDefaultBrowserPackageNameLPr(packageName, userId); 9407 if (packageName != null) { 9408 result |= updateIntentVerificationStatus(packageName, 9409 PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, 9410 UserHandle.myUserId()); 9411 } 9412 return result; 9413 } 9414 } 9415 9416 @Override 9417 public String getDefaultBrowserPackageName(int userId) { 9418 synchronized (mPackages) { 9419 return mSettings.getDefaultBrowserPackageNameLPw(userId); 9420 } 9421 } 9422 9423 /** 9424 * Get the "allow unknown sources" setting. 9425 * 9426 * @return the current "allow unknown sources" setting 9427 */ 9428 private int getUnknownSourcesSettings() { 9429 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 9430 android.provider.Settings.Global.INSTALL_NON_MARKET_APPS, 9431 -1); 9432 } 9433 9434 @Override 9435 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 9436 final int uid = Binder.getCallingUid(); 9437 // writer 9438 synchronized (mPackages) { 9439 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 9440 if (targetPackageSetting == null) { 9441 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 9442 } 9443 9444 PackageSetting installerPackageSetting; 9445 if (installerPackageName != null) { 9446 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 9447 if (installerPackageSetting == null) { 9448 throw new IllegalArgumentException("Unknown installer package: " 9449 + installerPackageName); 9450 } 9451 } else { 9452 installerPackageSetting = null; 9453 } 9454 9455 Signature[] callerSignature; 9456 Object obj = mSettings.getUserIdLPr(uid); 9457 if (obj != null) { 9458 if (obj instanceof SharedUserSetting) { 9459 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 9460 } else if (obj instanceof PackageSetting) { 9461 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 9462 } else { 9463 throw new SecurityException("Bad object " + obj + " for uid " + uid); 9464 } 9465 } else { 9466 throw new SecurityException("Unknown calling uid " + uid); 9467 } 9468 9469 // Verify: can't set installerPackageName to a package that is 9470 // not signed with the same cert as the caller. 9471 if (installerPackageSetting != null) { 9472 if (compareSignatures(callerSignature, 9473 installerPackageSetting.signatures.mSignatures) 9474 != PackageManager.SIGNATURE_MATCH) { 9475 throw new SecurityException( 9476 "Caller does not have same cert as new installer package " 9477 + installerPackageName); 9478 } 9479 } 9480 9481 // Verify: if target already has an installer package, it must 9482 // be signed with the same cert as the caller. 9483 if (targetPackageSetting.installerPackageName != null) { 9484 PackageSetting setting = mSettings.mPackages.get( 9485 targetPackageSetting.installerPackageName); 9486 // If the currently set package isn't valid, then it's always 9487 // okay to change it. 9488 if (setting != null) { 9489 if (compareSignatures(callerSignature, 9490 setting.signatures.mSignatures) 9491 != PackageManager.SIGNATURE_MATCH) { 9492 throw new SecurityException( 9493 "Caller does not have same cert as old installer package " 9494 + targetPackageSetting.installerPackageName); 9495 } 9496 } 9497 } 9498 9499 // Okay! 9500 targetPackageSetting.installerPackageName = installerPackageName; 9501 scheduleWriteSettingsLocked(); 9502 } 9503 } 9504 9505 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 9506 // Queue up an async operation since the package installation may take a little while. 9507 mHandler.post(new Runnable() { 9508 public void run() { 9509 mHandler.removeCallbacks(this); 9510 // Result object to be returned 9511 PackageInstalledInfo res = new PackageInstalledInfo(); 9512 res.returnCode = currentStatus; 9513 res.uid = -1; 9514 res.pkg = null; 9515 res.removedInfo = new PackageRemovedInfo(); 9516 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 9517 args.doPreInstall(res.returnCode); 9518 synchronized (mInstallLock) { 9519 installPackageLI(args, res); 9520 } 9521 args.doPostInstall(res.returnCode, res.uid); 9522 } 9523 9524 // A restore should be performed at this point if (a) the install 9525 // succeeded, (b) the operation is not an update, and (c) the new 9526 // package has not opted out of backup participation. 9527 final boolean update = res.removedInfo.removedPackage != null; 9528 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags; 9529 boolean doRestore = !update 9530 && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0); 9531 9532 // Set up the post-install work request bookkeeping. This will be used 9533 // and cleaned up by the post-install event handling regardless of whether 9534 // there's a restore pass performed. Token values are >= 1. 9535 int token; 9536 if (mNextInstallToken < 0) mNextInstallToken = 1; 9537 token = mNextInstallToken++; 9538 9539 PostInstallData data = new PostInstallData(args, res); 9540 mRunningInstalls.put(token, data); 9541 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 9542 9543 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 9544 // Pass responsibility to the Backup Manager. It will perform a 9545 // restore if appropriate, then pass responsibility back to the 9546 // Package Manager to run the post-install observer callbacks 9547 // and broadcasts. 9548 IBackupManager bm = IBackupManager.Stub.asInterface( 9549 ServiceManager.getService(Context.BACKUP_SERVICE)); 9550 if (bm != null) { 9551 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 9552 + " to BM for possible restore"); 9553 try { 9554 if (bm.isBackupServiceActive(UserHandle.USER_OWNER)) { 9555 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 9556 } else { 9557 doRestore = false; 9558 } 9559 } catch (RemoteException e) { 9560 // can't happen; the backup manager is local 9561 } catch (Exception e) { 9562 Slog.e(TAG, "Exception trying to enqueue restore", e); 9563 doRestore = false; 9564 } 9565 } else { 9566 Slog.e(TAG, "Backup Manager not found!"); 9567 doRestore = false; 9568 } 9569 } 9570 9571 if (!doRestore) { 9572 // No restore possible, or the Backup Manager was mysteriously not 9573 // available -- just fire the post-install work request directly. 9574 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 9575 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 9576 mHandler.sendMessage(msg); 9577 } 9578 } 9579 }); 9580 } 9581 9582 private abstract class HandlerParams { 9583 private static final int MAX_RETRIES = 4; 9584 9585 /** 9586 * Number of times startCopy() has been attempted and had a non-fatal 9587 * error. 9588 */ 9589 private int mRetries = 0; 9590 9591 /** User handle for the user requesting the information or installation. */ 9592 private final UserHandle mUser; 9593 9594 HandlerParams(UserHandle user) { 9595 mUser = user; 9596 } 9597 9598 UserHandle getUser() { 9599 return mUser; 9600 } 9601 9602 final boolean startCopy() { 9603 boolean res; 9604 try { 9605 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 9606 9607 if (++mRetries > MAX_RETRIES) { 9608 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 9609 mHandler.sendEmptyMessage(MCS_GIVE_UP); 9610 handleServiceError(); 9611 return false; 9612 } else { 9613 handleStartCopy(); 9614 res = true; 9615 } 9616 } catch (RemoteException e) { 9617 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 9618 mHandler.sendEmptyMessage(MCS_RECONNECT); 9619 res = false; 9620 } 9621 handleReturnCode(); 9622 return res; 9623 } 9624 9625 final void serviceError() { 9626 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 9627 handleServiceError(); 9628 handleReturnCode(); 9629 } 9630 9631 abstract void handleStartCopy() throws RemoteException; 9632 abstract void handleServiceError(); 9633 abstract void handleReturnCode(); 9634 } 9635 9636 class MeasureParams extends HandlerParams { 9637 private final PackageStats mStats; 9638 private boolean mSuccess; 9639 9640 private final IPackageStatsObserver mObserver; 9641 9642 public MeasureParams(PackageStats stats, IPackageStatsObserver observer) { 9643 super(new UserHandle(stats.userHandle)); 9644 mObserver = observer; 9645 mStats = stats; 9646 } 9647 9648 @Override 9649 public String toString() { 9650 return "MeasureParams{" 9651 + Integer.toHexString(System.identityHashCode(this)) 9652 + " " + mStats.packageName + "}"; 9653 } 9654 9655 @Override 9656 void handleStartCopy() throws RemoteException { 9657 synchronized (mInstallLock) { 9658 mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats); 9659 } 9660 9661 if (mSuccess) { 9662 final boolean mounted; 9663 if (Environment.isExternalStorageEmulated()) { 9664 mounted = true; 9665 } else { 9666 final String status = Environment.getExternalStorageState(); 9667 mounted = (Environment.MEDIA_MOUNTED.equals(status) 9668 || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status)); 9669 } 9670 9671 if (mounted) { 9672 final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle); 9673 9674 mStats.externalCacheSize = calculateDirectorySize(mContainerService, 9675 userEnv.buildExternalStorageAppCacheDirs(mStats.packageName)); 9676 9677 mStats.externalDataSize = calculateDirectorySize(mContainerService, 9678 userEnv.buildExternalStorageAppDataDirs(mStats.packageName)); 9679 9680 // Always subtract cache size, since it's a subdirectory 9681 mStats.externalDataSize -= mStats.externalCacheSize; 9682 9683 mStats.externalMediaSize = calculateDirectorySize(mContainerService, 9684 userEnv.buildExternalStorageAppMediaDirs(mStats.packageName)); 9685 9686 mStats.externalObbSize = calculateDirectorySize(mContainerService, 9687 userEnv.buildExternalStorageAppObbDirs(mStats.packageName)); 9688 } 9689 } 9690 } 9691 9692 @Override 9693 void handleReturnCode() { 9694 if (mObserver != null) { 9695 try { 9696 mObserver.onGetStatsCompleted(mStats, mSuccess); 9697 } catch (RemoteException e) { 9698 Slog.i(TAG, "Observer no longer exists."); 9699 } 9700 } 9701 } 9702 9703 @Override 9704 void handleServiceError() { 9705 Slog.e(TAG, "Could not measure application " + mStats.packageName 9706 + " external storage"); 9707 } 9708 } 9709 9710 private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths) 9711 throws RemoteException { 9712 long result = 0; 9713 for (File path : paths) { 9714 result += mcs.calculateDirectorySize(path.getAbsolutePath()); 9715 } 9716 return result; 9717 } 9718 9719 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 9720 for (File path : paths) { 9721 try { 9722 mcs.clearDirectory(path.getAbsolutePath()); 9723 } catch (RemoteException e) { 9724 } 9725 } 9726 } 9727 9728 static class OriginInfo { 9729 /** 9730 * Location where install is coming from, before it has been 9731 * copied/renamed into place. This could be a single monolithic APK 9732 * file, or a cluster directory. This location may be untrusted. 9733 */ 9734 final File file; 9735 final String cid; 9736 9737 /** 9738 * Flag indicating that {@link #file} or {@link #cid} has already been 9739 * staged, meaning downstream users don't need to defensively copy the 9740 * contents. 9741 */ 9742 final boolean staged; 9743 9744 /** 9745 * Flag indicating that {@link #file} or {@link #cid} is an already 9746 * installed app that is being moved. 9747 */ 9748 final boolean existing; 9749 9750 final String resolvedPath; 9751 final File resolvedFile; 9752 9753 static OriginInfo fromNothing() { 9754 return new OriginInfo(null, null, false, false); 9755 } 9756 9757 static OriginInfo fromUntrustedFile(File file) { 9758 return new OriginInfo(file, null, false, false); 9759 } 9760 9761 static OriginInfo fromExistingFile(File file) { 9762 return new OriginInfo(file, null, false, true); 9763 } 9764 9765 static OriginInfo fromStagedFile(File file) { 9766 return new OriginInfo(file, null, true, false); 9767 } 9768 9769 static OriginInfo fromStagedContainer(String cid) { 9770 return new OriginInfo(null, cid, true, false); 9771 } 9772 9773 private OriginInfo(File file, String cid, boolean staged, boolean existing) { 9774 this.file = file; 9775 this.cid = cid; 9776 this.staged = staged; 9777 this.existing = existing; 9778 9779 if (cid != null) { 9780 resolvedPath = PackageHelper.getSdDir(cid); 9781 resolvedFile = new File(resolvedPath); 9782 } else if (file != null) { 9783 resolvedPath = file.getAbsolutePath(); 9784 resolvedFile = file; 9785 } else { 9786 resolvedPath = null; 9787 resolvedFile = null; 9788 } 9789 } 9790 } 9791 9792 class MoveInfo { 9793 final int moveId; 9794 final String fromUuid; 9795 final String toUuid; 9796 final String packageName; 9797 final String dataAppName; 9798 final int appId; 9799 final String seinfo; 9800 9801 public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName, 9802 String dataAppName, int appId, String seinfo) { 9803 this.moveId = moveId; 9804 this.fromUuid = fromUuid; 9805 this.toUuid = toUuid; 9806 this.packageName = packageName; 9807 this.dataAppName = dataAppName; 9808 this.appId = appId; 9809 this.seinfo = seinfo; 9810 } 9811 } 9812 9813 class InstallParams extends HandlerParams { 9814 final OriginInfo origin; 9815 final MoveInfo move; 9816 final IPackageInstallObserver2 observer; 9817 int installFlags; 9818 final String installerPackageName; 9819 final String volumeUuid; 9820 final VerificationParams verificationParams; 9821 private InstallArgs mArgs; 9822 private int mRet; 9823 final String packageAbiOverride; 9824 9825 InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 9826 int installFlags, String installerPackageName, String volumeUuid, 9827 VerificationParams verificationParams, UserHandle user, String packageAbiOverride) { 9828 super(user); 9829 this.origin = origin; 9830 this.move = move; 9831 this.observer = observer; 9832 this.installFlags = installFlags; 9833 this.installerPackageName = installerPackageName; 9834 this.volumeUuid = volumeUuid; 9835 this.verificationParams = verificationParams; 9836 this.packageAbiOverride = packageAbiOverride; 9837 } 9838 9839 @Override 9840 public String toString() { 9841 return "InstallParams{" + Integer.toHexString(System.identityHashCode(this)) 9842 + " file=" + origin.file + " cid=" + origin.cid + "}"; 9843 } 9844 9845 public ManifestDigest getManifestDigest() { 9846 if (verificationParams == null) { 9847 return null; 9848 } 9849 return verificationParams.getManifestDigest(); 9850 } 9851 9852 private int installLocationPolicy(PackageInfoLite pkgLite) { 9853 String packageName = pkgLite.packageName; 9854 int installLocation = pkgLite.installLocation; 9855 boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 9856 // reader 9857 synchronized (mPackages) { 9858 PackageParser.Package pkg = mPackages.get(packageName); 9859 if (pkg != null) { 9860 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 9861 // Check for downgrading. 9862 if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) { 9863 try { 9864 checkDowngrade(pkg, pkgLite); 9865 } catch (PackageManagerException e) { 9866 Slog.w(TAG, "Downgrade detected: " + e.getMessage()); 9867 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 9868 } 9869 } 9870 // Check for updated system application. 9871 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 9872 if (onSd) { 9873 Slog.w(TAG, "Cannot install update to system app on sdcard"); 9874 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 9875 } 9876 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 9877 } else { 9878 if (onSd) { 9879 // Install flag overrides everything. 9880 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 9881 } 9882 // If current upgrade specifies particular preference 9883 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 9884 // Application explicitly specified internal. 9885 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 9886 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 9887 // App explictly prefers external. Let policy decide 9888 } else { 9889 // Prefer previous location 9890 if (isExternal(pkg)) { 9891 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 9892 } 9893 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 9894 } 9895 } 9896 } else { 9897 // Invalid install. Return error code 9898 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 9899 } 9900 } 9901 } 9902 // All the special cases have been taken care of. 9903 // Return result based on recommended install location. 9904 if (onSd) { 9905 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 9906 } 9907 return pkgLite.recommendedInstallLocation; 9908 } 9909 9910 /* 9911 * Invoke remote method to get package information and install 9912 * location values. Override install location based on default 9913 * policy if needed and then create install arguments based 9914 * on the install location. 9915 */ 9916 public void handleStartCopy() throws RemoteException { 9917 int ret = PackageManager.INSTALL_SUCCEEDED; 9918 9919 // If we're already staged, we've firmly committed to an install location 9920 if (origin.staged) { 9921 if (origin.file != null) { 9922 installFlags |= PackageManager.INSTALL_INTERNAL; 9923 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 9924 } else if (origin.cid != null) { 9925 installFlags |= PackageManager.INSTALL_EXTERNAL; 9926 installFlags &= ~PackageManager.INSTALL_INTERNAL; 9927 } else { 9928 throw new IllegalStateException("Invalid stage location"); 9929 } 9930 } 9931 9932 final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 9933 final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0; 9934 9935 PackageInfoLite pkgLite = null; 9936 9937 if (onInt && onSd) { 9938 // Check if both bits are set. 9939 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 9940 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 9941 } else { 9942 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags, 9943 packageAbiOverride); 9944 9945 /* 9946 * If we have too little free space, try to free cache 9947 * before giving up. 9948 */ 9949 if (!origin.staged && pkgLite.recommendedInstallLocation 9950 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 9951 // TODO: focus freeing disk space on the target device 9952 final StorageManager storage = StorageManager.from(mContext); 9953 final long lowThreshold = storage.getStorageLowBytes( 9954 Environment.getDataDirectory()); 9955 9956 final long sizeBytes = mContainerService.calculateInstalledSize( 9957 origin.resolvedPath, isForwardLocked(), packageAbiOverride); 9958 9959 if (mInstaller.freeCache(null, sizeBytes + lowThreshold) >= 0) { 9960 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, 9961 installFlags, packageAbiOverride); 9962 } 9963 9964 /* 9965 * The cache free must have deleted the file we 9966 * downloaded to install. 9967 * 9968 * TODO: fix the "freeCache" call to not delete 9969 * the file we care about. 9970 */ 9971 if (pkgLite.recommendedInstallLocation 9972 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 9973 pkgLite.recommendedInstallLocation 9974 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 9975 } 9976 } 9977 } 9978 9979 if (ret == PackageManager.INSTALL_SUCCEEDED) { 9980 int loc = pkgLite.recommendedInstallLocation; 9981 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 9982 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 9983 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 9984 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 9985 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 9986 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 9987 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 9988 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 9989 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 9990 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 9991 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 9992 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 9993 } else { 9994 // Override with defaults if needed. 9995 loc = installLocationPolicy(pkgLite); 9996 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 9997 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 9998 } else if (!onSd && !onInt) { 9999 // Override install location with flags 10000 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 10001 // Set the flag to install on external media. 10002 installFlags |= PackageManager.INSTALL_EXTERNAL; 10003 installFlags &= ~PackageManager.INSTALL_INTERNAL; 10004 } else { 10005 // Make sure the flag for installing on external 10006 // media is unset 10007 installFlags |= PackageManager.INSTALL_INTERNAL; 10008 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 10009 } 10010 } 10011 } 10012 } 10013 10014 final InstallArgs args = createInstallArgs(this); 10015 mArgs = args; 10016 10017 if (ret == PackageManager.INSTALL_SUCCEEDED) { 10018 /* 10019 * ADB installs appear as UserHandle.USER_ALL, and can only be performed by 10020 * UserHandle.USER_OWNER, so use the package verifier for UserHandle.USER_OWNER. 10021 */ 10022 int userIdentifier = getUser().getIdentifier(); 10023 if (userIdentifier == UserHandle.USER_ALL 10024 && ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0)) { 10025 userIdentifier = UserHandle.USER_OWNER; 10026 } 10027 10028 /* 10029 * Determine if we have any installed package verifiers. If we 10030 * do, then we'll defer to them to verify the packages. 10031 */ 10032 final int requiredUid = mRequiredVerifierPackage == null ? -1 10033 : getPackageUid(mRequiredVerifierPackage, userIdentifier); 10034 if (!origin.existing && requiredUid != -1 10035 && isVerificationEnabled(userIdentifier, installFlags)) { 10036 final Intent verification = new Intent( 10037 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 10038 verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 10039 verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)), 10040 PACKAGE_MIME_TYPE); 10041 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 10042 10043 final List<ResolveInfo> receivers = queryIntentReceivers(verification, 10044 PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS, 10045 0 /* TODO: Which userId? */); 10046 10047 if (DEBUG_VERIFY) { 10048 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 10049 + verification.toString() + " with " + pkgLite.verifiers.length 10050 + " optional verifiers"); 10051 } 10052 10053 final int verificationId = mPendingVerificationToken++; 10054 10055 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 10056 10057 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 10058 installerPackageName); 10059 10060 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, 10061 installFlags); 10062 10063 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 10064 pkgLite.packageName); 10065 10066 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 10067 pkgLite.versionCode); 10068 10069 if (verificationParams != null) { 10070 if (verificationParams.getVerificationURI() != null) { 10071 verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI, 10072 verificationParams.getVerificationURI()); 10073 } 10074 if (verificationParams.getOriginatingURI() != null) { 10075 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 10076 verificationParams.getOriginatingURI()); 10077 } 10078 if (verificationParams.getReferrer() != null) { 10079 verification.putExtra(Intent.EXTRA_REFERRER, 10080 verificationParams.getReferrer()); 10081 } 10082 if (verificationParams.getOriginatingUid() >= 0) { 10083 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 10084 verificationParams.getOriginatingUid()); 10085 } 10086 if (verificationParams.getInstallerUid() >= 0) { 10087 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 10088 verificationParams.getInstallerUid()); 10089 } 10090 } 10091 10092 final PackageVerificationState verificationState = new PackageVerificationState( 10093 requiredUid, args); 10094 10095 mPendingVerification.append(verificationId, verificationState); 10096 10097 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 10098 receivers, verificationState); 10099 10100 /* 10101 * If any sufficient verifiers were listed in the package 10102 * manifest, attempt to ask them. 10103 */ 10104 if (sufficientVerifiers != null) { 10105 final int N = sufficientVerifiers.size(); 10106 if (N == 0) { 10107 Slog.i(TAG, "Additional verifiers required, but none installed."); 10108 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 10109 } else { 10110 for (int i = 0; i < N; i++) { 10111 final ComponentName verifierComponent = sufficientVerifiers.get(i); 10112 10113 final Intent sufficientIntent = new Intent(verification); 10114 sufficientIntent.setComponent(verifierComponent); 10115 10116 mContext.sendBroadcastAsUser(sufficientIntent, getUser()); 10117 } 10118 } 10119 } 10120 10121 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 10122 mRequiredVerifierPackage, receivers); 10123 if (ret == PackageManager.INSTALL_SUCCEEDED 10124 && mRequiredVerifierPackage != null) { 10125 /* 10126 * Send the intent to the required verification agent, 10127 * but only start the verification timeout after the 10128 * target BroadcastReceivers have run. 10129 */ 10130 verification.setComponent(requiredVerifierComponent); 10131 mContext.sendOrderedBroadcastAsUser(verification, getUser(), 10132 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 10133 new BroadcastReceiver() { 10134 @Override 10135 public void onReceive(Context context, Intent intent) { 10136 final Message msg = mHandler 10137 .obtainMessage(CHECK_PENDING_VERIFICATION); 10138 msg.arg1 = verificationId; 10139 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 10140 } 10141 }, null, 0, null, null); 10142 10143 /* 10144 * We don't want the copy to proceed until verification 10145 * succeeds, so null out this field. 10146 */ 10147 mArgs = null; 10148 } 10149 } else { 10150 /* 10151 * No package verification is enabled, so immediately start 10152 * the remote call to initiate copy using temporary file. 10153 */ 10154 ret = args.copyApk(mContainerService, true); 10155 } 10156 } 10157 10158 mRet = ret; 10159 } 10160 10161 @Override 10162 void handleReturnCode() { 10163 // If mArgs is null, then MCS couldn't be reached. When it 10164 // reconnects, it will try again to install. At that point, this 10165 // will succeed. 10166 if (mArgs != null) { 10167 processPendingInstall(mArgs, mRet); 10168 } 10169 } 10170 10171 @Override 10172 void handleServiceError() { 10173 mArgs = createInstallArgs(this); 10174 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 10175 } 10176 10177 public boolean isForwardLocked() { 10178 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 10179 } 10180 } 10181 10182 /** 10183 * Used during creation of InstallArgs 10184 * 10185 * @param installFlags package installation flags 10186 * @return true if should be installed on external storage 10187 */ 10188 private static boolean installOnExternalAsec(int installFlags) { 10189 if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) { 10190 return false; 10191 } 10192 if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) { 10193 return true; 10194 } 10195 return false; 10196 } 10197 10198 /** 10199 * Used during creation of InstallArgs 10200 * 10201 * @param installFlags package installation flags 10202 * @return true if should be installed as forward locked 10203 */ 10204 private static boolean installForwardLocked(int installFlags) { 10205 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 10206 } 10207 10208 private InstallArgs createInstallArgs(InstallParams params) { 10209 if (params.move != null) { 10210 return new MoveInstallArgs(params); 10211 } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) { 10212 return new AsecInstallArgs(params); 10213 } else { 10214 return new FileInstallArgs(params); 10215 } 10216 } 10217 10218 /** 10219 * Create args that describe an existing installed package. Typically used 10220 * when cleaning up old installs, or used as a move source. 10221 */ 10222 private InstallArgs createInstallArgsForExisting(int installFlags, String codePath, 10223 String resourcePath, String[] instructionSets) { 10224 final boolean isInAsec; 10225 if (installOnExternalAsec(installFlags)) { 10226 /* Apps on SD card are always in ASEC containers. */ 10227 isInAsec = true; 10228 } else if (installForwardLocked(installFlags) 10229 && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { 10230 /* 10231 * Forward-locked apps are only in ASEC containers if they're the 10232 * new style 10233 */ 10234 isInAsec = true; 10235 } else { 10236 isInAsec = false; 10237 } 10238 10239 if (isInAsec) { 10240 return new AsecInstallArgs(codePath, instructionSets, 10241 installOnExternalAsec(installFlags), installForwardLocked(installFlags)); 10242 } else { 10243 return new FileInstallArgs(codePath, resourcePath, instructionSets); 10244 } 10245 } 10246 10247 static abstract class InstallArgs { 10248 /** @see InstallParams#origin */ 10249 final OriginInfo origin; 10250 /** @see InstallParams#move */ 10251 final MoveInfo move; 10252 10253 final IPackageInstallObserver2 observer; 10254 // Always refers to PackageManager flags only 10255 final int installFlags; 10256 final String installerPackageName; 10257 final String volumeUuid; 10258 final ManifestDigest manifestDigest; 10259 final UserHandle user; 10260 final String abiOverride; 10261 10262 // The list of instruction sets supported by this app. This is currently 10263 // only used during the rmdex() phase to clean up resources. We can get rid of this 10264 // if we move dex files under the common app path. 10265 /* nullable */ String[] instructionSets; 10266 10267 InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 10268 int installFlags, String installerPackageName, String volumeUuid, 10269 ManifestDigest manifestDigest, UserHandle user, String[] instructionSets, 10270 String abiOverride) { 10271 this.origin = origin; 10272 this.move = move; 10273 this.installFlags = installFlags; 10274 this.observer = observer; 10275 this.installerPackageName = installerPackageName; 10276 this.volumeUuid = volumeUuid; 10277 this.manifestDigest = manifestDigest; 10278 this.user = user; 10279 this.instructionSets = instructionSets; 10280 this.abiOverride = abiOverride; 10281 } 10282 10283 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 10284 abstract int doPreInstall(int status); 10285 10286 /** 10287 * Rename package into final resting place. All paths on the given 10288 * scanned package should be updated to reflect the rename. 10289 */ 10290 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath); 10291 abstract int doPostInstall(int status, int uid); 10292 10293 /** @see PackageSettingBase#codePathString */ 10294 abstract String getCodePath(); 10295 /** @see PackageSettingBase#resourcePathString */ 10296 abstract String getResourcePath(); 10297 10298 // Need installer lock especially for dex file removal. 10299 abstract void cleanUpResourcesLI(); 10300 abstract boolean doPostDeleteLI(boolean delete); 10301 10302 /** 10303 * Called before the source arguments are copied. This is used mostly 10304 * for MoveParams when it needs to read the source file to put it in the 10305 * destination. 10306 */ 10307 int doPreCopy() { 10308 return PackageManager.INSTALL_SUCCEEDED; 10309 } 10310 10311 /** 10312 * Called after the source arguments are copied. This is used mostly for 10313 * MoveParams when it needs to read the source file to put it in the 10314 * destination. 10315 * 10316 * @return 10317 */ 10318 int doPostCopy(int uid) { 10319 return PackageManager.INSTALL_SUCCEEDED; 10320 } 10321 10322 protected boolean isFwdLocked() { 10323 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 10324 } 10325 10326 protected boolean isExternalAsec() { 10327 return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 10328 } 10329 10330 UserHandle getUser() { 10331 return user; 10332 } 10333 } 10334 10335 private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) { 10336 if (!allCodePaths.isEmpty()) { 10337 if (instructionSets == null) { 10338 throw new IllegalStateException("instructionSet == null"); 10339 } 10340 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 10341 for (String codePath : allCodePaths) { 10342 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 10343 int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet); 10344 if (retCode < 0) { 10345 Slog.w(TAG, "Couldn't remove dex file for package: " 10346 + " at location " + codePath + ", retcode=" + retCode); 10347 // we don't consider this to be a failure of the core package deletion 10348 } 10349 } 10350 } 10351 } 10352 } 10353 10354 /** 10355 * Logic to handle installation of non-ASEC applications, including copying 10356 * and renaming logic. 10357 */ 10358 class FileInstallArgs extends InstallArgs { 10359 private File codeFile; 10360 private File resourceFile; 10361 10362 // Example topology: 10363 // /data/app/com.example/base.apk 10364 // /data/app/com.example/split_foo.apk 10365 // /data/app/com.example/lib/arm/libfoo.so 10366 // /data/app/com.example/lib/arm64/libfoo.so 10367 // /data/app/com.example/dalvik/arm/base.apk@classes.dex 10368 10369 /** New install */ 10370 FileInstallArgs(InstallParams params) { 10371 super(params.origin, params.move, params.observer, params.installFlags, 10372 params.installerPackageName, params.volumeUuid, params.getManifestDigest(), 10373 params.getUser(), null /* instruction sets */, params.packageAbiOverride); 10374 if (isFwdLocked()) { 10375 throw new IllegalArgumentException("Forward locking only supported in ASEC"); 10376 } 10377 } 10378 10379 /** Existing install */ 10380 FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) { 10381 super(OriginInfo.fromNothing(), null, null, 0, null, null, null, null, instructionSets, 10382 null); 10383 this.codeFile = (codePath != null) ? new File(codePath) : null; 10384 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; 10385 } 10386 10387 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 10388 if (origin.staged) { 10389 Slog.d(TAG, origin.file + " already staged; skipping copy"); 10390 codeFile = origin.file; 10391 resourceFile = origin.file; 10392 return PackageManager.INSTALL_SUCCEEDED; 10393 } 10394 10395 try { 10396 final File tempDir = mInstallerService.allocateStageDirLegacy(volumeUuid); 10397 codeFile = tempDir; 10398 resourceFile = tempDir; 10399 } catch (IOException e) { 10400 Slog.w(TAG, "Failed to create copy file: " + e); 10401 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 10402 } 10403 10404 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() { 10405 @Override 10406 public ParcelFileDescriptor open(String name, int mode) throws RemoteException { 10407 if (!FileUtils.isValidExtFilename(name)) { 10408 throw new IllegalArgumentException("Invalid filename: " + name); 10409 } 10410 try { 10411 final File file = new File(codeFile, name); 10412 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 10413 O_RDWR | O_CREAT, 0644); 10414 Os.chmod(file.getAbsolutePath(), 0644); 10415 return new ParcelFileDescriptor(fd); 10416 } catch (ErrnoException e) { 10417 throw new RemoteException("Failed to open: " + e.getMessage()); 10418 } 10419 } 10420 }; 10421 10422 int ret = PackageManager.INSTALL_SUCCEEDED; 10423 ret = imcs.copyPackage(origin.file.getAbsolutePath(), target); 10424 if (ret != PackageManager.INSTALL_SUCCEEDED) { 10425 Slog.e(TAG, "Failed to copy package"); 10426 return ret; 10427 } 10428 10429 final File libraryRoot = new File(codeFile, LIB_DIR_NAME); 10430 NativeLibraryHelper.Handle handle = null; 10431 try { 10432 handle = NativeLibraryHelper.Handle.create(codeFile); 10433 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot, 10434 abiOverride); 10435 } catch (IOException e) { 10436 Slog.e(TAG, "Copying native libraries failed", e); 10437 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 10438 } finally { 10439 IoUtils.closeQuietly(handle); 10440 } 10441 10442 return ret; 10443 } 10444 10445 int doPreInstall(int status) { 10446 if (status != PackageManager.INSTALL_SUCCEEDED) { 10447 cleanUp(); 10448 } 10449 return status; 10450 } 10451 10452 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 10453 if (status != PackageManager.INSTALL_SUCCEEDED) { 10454 cleanUp(); 10455 return false; 10456 } 10457 10458 final File targetDir = codeFile.getParentFile(); 10459 final File beforeCodeFile = codeFile; 10460 final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName); 10461 10462 Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); 10463 try { 10464 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath()); 10465 } catch (ErrnoException e) { 10466 Slog.d(TAG, "Failed to rename", e); 10467 return false; 10468 } 10469 10470 if (!SELinux.restoreconRecursive(afterCodeFile)) { 10471 Slog.d(TAG, "Failed to restorecon"); 10472 return false; 10473 } 10474 10475 // Reflect the rename internally 10476 codeFile = afterCodeFile; 10477 resourceFile = afterCodeFile; 10478 10479 // Reflect the rename in scanned details 10480 pkg.codePath = afterCodeFile.getAbsolutePath(); 10481 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 10482 pkg.baseCodePath); 10483 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 10484 pkg.splitCodePaths); 10485 10486 // Reflect the rename in app info 10487 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 10488 pkg.applicationInfo.setCodePath(pkg.codePath); 10489 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 10490 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 10491 pkg.applicationInfo.setResourcePath(pkg.codePath); 10492 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 10493 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 10494 10495 return true; 10496 } 10497 10498 int doPostInstall(int status, int uid) { 10499 if (status != PackageManager.INSTALL_SUCCEEDED) { 10500 cleanUp(); 10501 } 10502 return status; 10503 } 10504 10505 @Override 10506 String getCodePath() { 10507 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 10508 } 10509 10510 @Override 10511 String getResourcePath() { 10512 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 10513 } 10514 10515 private boolean cleanUp() { 10516 if (codeFile == null || !codeFile.exists()) { 10517 return false; 10518 } 10519 10520 if (codeFile.isDirectory()) { 10521 mInstaller.rmPackageDir(codeFile.getAbsolutePath()); 10522 } else { 10523 codeFile.delete(); 10524 } 10525 10526 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 10527 resourceFile.delete(); 10528 } 10529 10530 return true; 10531 } 10532 10533 void cleanUpResourcesLI() { 10534 // Try enumerating all code paths before deleting 10535 List<String> allCodePaths = Collections.EMPTY_LIST; 10536 if (codeFile != null && codeFile.exists()) { 10537 try { 10538 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 10539 allCodePaths = pkg.getAllCodePaths(); 10540 } catch (PackageParserException e) { 10541 // Ignored; we tried our best 10542 } 10543 } 10544 10545 cleanUp(); 10546 removeDexFiles(allCodePaths, instructionSets); 10547 } 10548 10549 boolean doPostDeleteLI(boolean delete) { 10550 // XXX err, shouldn't we respect the delete flag? 10551 cleanUpResourcesLI(); 10552 return true; 10553 } 10554 } 10555 10556 private boolean isAsecExternal(String cid) { 10557 final String asecPath = PackageHelper.getSdFilesystem(cid); 10558 return !asecPath.startsWith(mAsecInternalPath); 10559 } 10560 10561 private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws 10562 PackageManagerException { 10563 if (copyRet < 0) { 10564 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES && 10565 copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) { 10566 throw new PackageManagerException(copyRet, message); 10567 } 10568 } 10569 } 10570 10571 /** 10572 * Extract the MountService "container ID" from the full code path of an 10573 * .apk. 10574 */ 10575 static String cidFromCodePath(String fullCodePath) { 10576 int eidx = fullCodePath.lastIndexOf("/"); 10577 String subStr1 = fullCodePath.substring(0, eidx); 10578 int sidx = subStr1.lastIndexOf("/"); 10579 return subStr1.substring(sidx+1, eidx); 10580 } 10581 10582 /** 10583 * Logic to handle installation of ASEC applications, including copying and 10584 * renaming logic. 10585 */ 10586 class AsecInstallArgs extends InstallArgs { 10587 static final String RES_FILE_NAME = "pkg.apk"; 10588 static final String PUBLIC_RES_FILE_NAME = "res.zip"; 10589 10590 String cid; 10591 String packagePath; 10592 String resourcePath; 10593 10594 /** New install */ 10595 AsecInstallArgs(InstallParams params) { 10596 super(params.origin, params.move, params.observer, params.installFlags, 10597 params.installerPackageName, params.volumeUuid, params.getManifestDigest(), 10598 params.getUser(), null /* instruction sets */, params.packageAbiOverride); 10599 } 10600 10601 /** Existing install */ 10602 AsecInstallArgs(String fullCodePath, String[] instructionSets, 10603 boolean isExternal, boolean isForwardLocked) { 10604 super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0) 10605 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null, 10606 instructionSets, null); 10607 // Hackily pretend we're still looking at a full code path 10608 if (!fullCodePath.endsWith(RES_FILE_NAME)) { 10609 fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath(); 10610 } 10611 10612 // Extract cid from fullCodePath 10613 int eidx = fullCodePath.lastIndexOf("/"); 10614 String subStr1 = fullCodePath.substring(0, eidx); 10615 int sidx = subStr1.lastIndexOf("/"); 10616 cid = subStr1.substring(sidx+1, eidx); 10617 setMountPath(subStr1); 10618 } 10619 10620 AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) { 10621 super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0) 10622 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null, 10623 instructionSets, null); 10624 this.cid = cid; 10625 setMountPath(PackageHelper.getSdDir(cid)); 10626 } 10627 10628 void createCopyFile() { 10629 cid = mInstallerService.allocateExternalStageCidLegacy(); 10630 } 10631 10632 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 10633 if (origin.staged) { 10634 Slog.d(TAG, origin.cid + " already staged; skipping copy"); 10635 cid = origin.cid; 10636 setMountPath(PackageHelper.getSdDir(cid)); 10637 return PackageManager.INSTALL_SUCCEEDED; 10638 } 10639 10640 if (temp) { 10641 createCopyFile(); 10642 } else { 10643 /* 10644 * Pre-emptively destroy the container since it's destroyed if 10645 * copying fails due to it existing anyway. 10646 */ 10647 PackageHelper.destroySdDir(cid); 10648 } 10649 10650 final String newMountPath = imcs.copyPackageToContainer( 10651 origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(), 10652 isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */)); 10653 10654 if (newMountPath != null) { 10655 setMountPath(newMountPath); 10656 return PackageManager.INSTALL_SUCCEEDED; 10657 } else { 10658 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 10659 } 10660 } 10661 10662 @Override 10663 String getCodePath() { 10664 return packagePath; 10665 } 10666 10667 @Override 10668 String getResourcePath() { 10669 return resourcePath; 10670 } 10671 10672 int doPreInstall(int status) { 10673 if (status != PackageManager.INSTALL_SUCCEEDED) { 10674 // Destroy container 10675 PackageHelper.destroySdDir(cid); 10676 } else { 10677 boolean mounted = PackageHelper.isContainerMounted(cid); 10678 if (!mounted) { 10679 String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(), 10680 Process.SYSTEM_UID); 10681 if (newMountPath != null) { 10682 setMountPath(newMountPath); 10683 } else { 10684 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 10685 } 10686 } 10687 } 10688 return status; 10689 } 10690 10691 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 10692 String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME); 10693 String newMountPath = null; 10694 if (PackageHelper.isContainerMounted(cid)) { 10695 // Unmount the container 10696 if (!PackageHelper.unMountSdDir(cid)) { 10697 Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); 10698 return false; 10699 } 10700 } 10701 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 10702 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + 10703 " which might be stale. Will try to clean up."); 10704 // Clean up the stale container and proceed to recreate. 10705 if (!PackageHelper.destroySdDir(newCacheId)) { 10706 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); 10707 return false; 10708 } 10709 // Successfully cleaned up stale container. Try to rename again. 10710 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 10711 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId 10712 + " inspite of cleaning it up."); 10713 return false; 10714 } 10715 } 10716 if (!PackageHelper.isContainerMounted(newCacheId)) { 10717 Slog.w(TAG, "Mounting container " + newCacheId); 10718 newMountPath = PackageHelper.mountSdDir(newCacheId, 10719 getEncryptKey(), Process.SYSTEM_UID); 10720 } else { 10721 newMountPath = PackageHelper.getSdDir(newCacheId); 10722 } 10723 if (newMountPath == null) { 10724 Slog.w(TAG, "Failed to get cache path for " + newCacheId); 10725 return false; 10726 } 10727 Log.i(TAG, "Succesfully renamed " + cid + 10728 " to " + newCacheId + 10729 " at new path: " + newMountPath); 10730 cid = newCacheId; 10731 10732 final File beforeCodeFile = new File(packagePath); 10733 setMountPath(newMountPath); 10734 final File afterCodeFile = new File(packagePath); 10735 10736 // Reflect the rename in scanned details 10737 pkg.codePath = afterCodeFile.getAbsolutePath(); 10738 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 10739 pkg.baseCodePath); 10740 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 10741 pkg.splitCodePaths); 10742 10743 // Reflect the rename in app info 10744 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 10745 pkg.applicationInfo.setCodePath(pkg.codePath); 10746 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 10747 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 10748 pkg.applicationInfo.setResourcePath(pkg.codePath); 10749 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 10750 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 10751 10752 return true; 10753 } 10754 10755 private void setMountPath(String mountPath) { 10756 final File mountFile = new File(mountPath); 10757 10758 final File monolithicFile = new File(mountFile, RES_FILE_NAME); 10759 if (monolithicFile.exists()) { 10760 packagePath = monolithicFile.getAbsolutePath(); 10761 if (isFwdLocked()) { 10762 resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath(); 10763 } else { 10764 resourcePath = packagePath; 10765 } 10766 } else { 10767 packagePath = mountFile.getAbsolutePath(); 10768 resourcePath = packagePath; 10769 } 10770 } 10771 10772 int doPostInstall(int status, int uid) { 10773 if (status != PackageManager.INSTALL_SUCCEEDED) { 10774 cleanUp(); 10775 } else { 10776 final int groupOwner; 10777 final String protectedFile; 10778 if (isFwdLocked()) { 10779 groupOwner = UserHandle.getSharedAppGid(uid); 10780 protectedFile = RES_FILE_NAME; 10781 } else { 10782 groupOwner = -1; 10783 protectedFile = null; 10784 } 10785 10786 if (uid < Process.FIRST_APPLICATION_UID 10787 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { 10788 Slog.e(TAG, "Failed to finalize " + cid); 10789 PackageHelper.destroySdDir(cid); 10790 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 10791 } 10792 10793 boolean mounted = PackageHelper.isContainerMounted(cid); 10794 if (!mounted) { 10795 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); 10796 } 10797 } 10798 return status; 10799 } 10800 10801 private void cleanUp() { 10802 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); 10803 10804 // Destroy secure container 10805 PackageHelper.destroySdDir(cid); 10806 } 10807 10808 private List<String> getAllCodePaths() { 10809 final File codeFile = new File(getCodePath()); 10810 if (codeFile != null && codeFile.exists()) { 10811 try { 10812 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 10813 return pkg.getAllCodePaths(); 10814 } catch (PackageParserException e) { 10815 // Ignored; we tried our best 10816 } 10817 } 10818 return Collections.EMPTY_LIST; 10819 } 10820 10821 void cleanUpResourcesLI() { 10822 // Enumerate all code paths before deleting 10823 cleanUpResourcesLI(getAllCodePaths()); 10824 } 10825 10826 private void cleanUpResourcesLI(List<String> allCodePaths) { 10827 cleanUp(); 10828 removeDexFiles(allCodePaths, instructionSets); 10829 } 10830 10831 String getPackageName() { 10832 return getAsecPackageName(cid); 10833 } 10834 10835 boolean doPostDeleteLI(boolean delete) { 10836 if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete); 10837 final List<String> allCodePaths = getAllCodePaths(); 10838 boolean mounted = PackageHelper.isContainerMounted(cid); 10839 if (mounted) { 10840 // Unmount first 10841 if (PackageHelper.unMountSdDir(cid)) { 10842 mounted = false; 10843 } 10844 } 10845 if (!mounted && delete) { 10846 cleanUpResourcesLI(allCodePaths); 10847 } 10848 return !mounted; 10849 } 10850 10851 @Override 10852 int doPreCopy() { 10853 if (isFwdLocked()) { 10854 if (!PackageHelper.fixSdPermissions(cid, 10855 getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) { 10856 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 10857 } 10858 } 10859 10860 return PackageManager.INSTALL_SUCCEEDED; 10861 } 10862 10863 @Override 10864 int doPostCopy(int uid) { 10865 if (isFwdLocked()) { 10866 if (uid < Process.FIRST_APPLICATION_UID 10867 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid), 10868 RES_FILE_NAME)) { 10869 Slog.e(TAG, "Failed to finalize " + cid); 10870 PackageHelper.destroySdDir(cid); 10871 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 10872 } 10873 } 10874 10875 return PackageManager.INSTALL_SUCCEEDED; 10876 } 10877 } 10878 10879 /** 10880 * Logic to handle movement of existing installed applications. 10881 */ 10882 class MoveInstallArgs extends InstallArgs { 10883 private File codeFile; 10884 private File resourceFile; 10885 10886 /** New install */ 10887 MoveInstallArgs(InstallParams params) { 10888 super(params.origin, params.move, params.observer, params.installFlags, 10889 params.installerPackageName, params.volumeUuid, params.getManifestDigest(), 10890 params.getUser(), null /* instruction sets */, params.packageAbiOverride); 10891 } 10892 10893 int copyApk(IMediaContainerService imcs, boolean temp) { 10894 Slog.d(TAG, "Moving " + move.packageName + " from " + move.fromUuid + " to " 10895 + move.toUuid); 10896 synchronized (mInstaller) { 10897 if (mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName, 10898 move.dataAppName, move.appId, move.seinfo) != 0) { 10899 return PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 10900 } 10901 } 10902 10903 codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName); 10904 resourceFile = codeFile; 10905 Slog.d(TAG, "codeFile after move is " + codeFile); 10906 10907 return PackageManager.INSTALL_SUCCEEDED; 10908 } 10909 10910 int doPreInstall(int status) { 10911 if (status != PackageManager.INSTALL_SUCCEEDED) { 10912 cleanUp(); 10913 } 10914 return status; 10915 } 10916 10917 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 10918 if (status != PackageManager.INSTALL_SUCCEEDED) { 10919 cleanUp(); 10920 return false; 10921 } 10922 10923 // Reflect the move in app info 10924 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 10925 pkg.applicationInfo.setCodePath(pkg.codePath); 10926 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 10927 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 10928 pkg.applicationInfo.setResourcePath(pkg.codePath); 10929 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 10930 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 10931 10932 return true; 10933 } 10934 10935 int doPostInstall(int status, int uid) { 10936 if (status != PackageManager.INSTALL_SUCCEEDED) { 10937 cleanUp(); 10938 } 10939 return status; 10940 } 10941 10942 @Override 10943 String getCodePath() { 10944 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 10945 } 10946 10947 @Override 10948 String getResourcePath() { 10949 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 10950 } 10951 10952 private boolean cleanUp() { 10953 if (codeFile == null || !codeFile.exists()) { 10954 return false; 10955 } 10956 10957 if (codeFile.isDirectory()) { 10958 mInstaller.rmPackageDir(codeFile.getAbsolutePath()); 10959 } else { 10960 codeFile.delete(); 10961 } 10962 10963 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 10964 resourceFile.delete(); 10965 } 10966 10967 return true; 10968 } 10969 10970 void cleanUpResourcesLI() { 10971 cleanUp(); 10972 } 10973 10974 boolean doPostDeleteLI(boolean delete) { 10975 // XXX err, shouldn't we respect the delete flag? 10976 cleanUpResourcesLI(); 10977 return true; 10978 } 10979 } 10980 10981 static String getAsecPackageName(String packageCid) { 10982 int idx = packageCid.lastIndexOf("-"); 10983 if (idx == -1) { 10984 return packageCid; 10985 } 10986 return packageCid.substring(0, idx); 10987 } 10988 10989 // Utility method used to create code paths based on package name and available index. 10990 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 10991 String idxStr = ""; 10992 int idx = 1; 10993 // Fall back to default value of idx=1 if prefix is not 10994 // part of oldCodePath 10995 if (oldCodePath != null) { 10996 String subStr = oldCodePath; 10997 // Drop the suffix right away 10998 if (suffix != null && subStr.endsWith(suffix)) { 10999 subStr = subStr.substring(0, subStr.length() - suffix.length()); 11000 } 11001 // If oldCodePath already contains prefix find out the 11002 // ending index to either increment or decrement. 11003 int sidx = subStr.lastIndexOf(prefix); 11004 if (sidx != -1) { 11005 subStr = subStr.substring(sidx + prefix.length()); 11006 if (subStr != null) { 11007 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 11008 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 11009 } 11010 try { 11011 idx = Integer.parseInt(subStr); 11012 if (idx <= 1) { 11013 idx++; 11014 } else { 11015 idx--; 11016 } 11017 } catch(NumberFormatException e) { 11018 } 11019 } 11020 } 11021 } 11022 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 11023 return prefix + idxStr; 11024 } 11025 11026 private File getNextCodePath(File targetDir, String packageName) { 11027 int suffix = 1; 11028 File result; 11029 do { 11030 result = new File(targetDir, packageName + "-" + suffix); 11031 suffix++; 11032 } while (result.exists()); 11033 return result; 11034 } 11035 11036 // Utility method that returns the relative package path with respect 11037 // to the installation directory. Like say for /data/data/com.test-1.apk 11038 // string com.test-1 is returned. 11039 static String deriveCodePathName(String codePath) { 11040 if (codePath == null) { 11041 return null; 11042 } 11043 final File codeFile = new File(codePath); 11044 final String name = codeFile.getName(); 11045 if (codeFile.isDirectory()) { 11046 return name; 11047 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 11048 final int lastDot = name.lastIndexOf('.'); 11049 return name.substring(0, lastDot); 11050 } else { 11051 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 11052 return null; 11053 } 11054 } 11055 11056 class PackageInstalledInfo { 11057 String name; 11058 int uid; 11059 // The set of users that originally had this package installed. 11060 int[] origUsers; 11061 // The set of users that now have this package installed. 11062 int[] newUsers; 11063 PackageParser.Package pkg; 11064 int returnCode; 11065 String returnMsg; 11066 PackageRemovedInfo removedInfo; 11067 11068 public void setError(int code, String msg) { 11069 returnCode = code; 11070 returnMsg = msg; 11071 Slog.w(TAG, msg); 11072 } 11073 11074 public void setError(String msg, PackageParserException e) { 11075 returnCode = e.error; 11076 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 11077 Slog.w(TAG, msg, e); 11078 } 11079 11080 public void setError(String msg, PackageManagerException e) { 11081 returnCode = e.error; 11082 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 11083 Slog.w(TAG, msg, e); 11084 } 11085 11086 // In some error cases we want to convey more info back to the observer 11087 String origPackage; 11088 String origPermission; 11089 } 11090 11091 /* 11092 * Install a non-existing package. 11093 */ 11094 private void installNewPackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags, 11095 UserHandle user, String installerPackageName, String volumeUuid, 11096 PackageInstalledInfo res) { 11097 // Remember this for later, in case we need to rollback this install 11098 String pkgName = pkg.packageName; 11099 11100 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 11101 final boolean dataDirExists = PackageManager.getDataDirForUser(volumeUuid, pkgName, 11102 UserHandle.USER_OWNER).exists(); 11103 synchronized(mPackages) { 11104 if (mSettings.mRenamedPackages.containsKey(pkgName)) { 11105 // A package with the same name is already installed, though 11106 // it has been renamed to an older name. The package we 11107 // are trying to install should be installed as an update to 11108 // the existing one, but that has not been requested, so bail. 11109 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 11110 + " without first uninstalling package running as " 11111 + mSettings.mRenamedPackages.get(pkgName)); 11112 return; 11113 } 11114 if (mPackages.containsKey(pkgName)) { 11115 // Don't allow installation over an existing package with the same name. 11116 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 11117 + " without first uninstalling."); 11118 return; 11119 } 11120 } 11121 11122 try { 11123 PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 11124 System.currentTimeMillis(), user); 11125 11126 updateSettingsLI(newPackage, installerPackageName, volumeUuid, null, null, res, user); 11127 // delete the partially installed application. the data directory will have to be 11128 // restored if it was already existing 11129 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 11130 // remove package from internal structures. Note that we want deletePackageX to 11131 // delete the package data and cache directories that it created in 11132 // scanPackageLocked, unless those directories existed before we even tried to 11133 // install. 11134 deletePackageLI(pkgName, UserHandle.ALL, false, null, null, 11135 dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0, 11136 res.removedInfo, true); 11137 } 11138 11139 } catch (PackageManagerException e) { 11140 res.setError("Package couldn't be installed in " + pkg.codePath, e); 11141 } 11142 } 11143 11144 private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) { 11145 // Upgrade keysets are being used. Determine if new package has a superset of the 11146 // required keys. 11147 long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets(); 11148 KeySetManagerService ksms = mSettings.mKeySetManagerService; 11149 for (int i = 0; i < upgradeKeySets.length; i++) { 11150 Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]); 11151 if (newPkg.mSigningKeys.containsAll(upgradeSet)) { 11152 return true; 11153 } 11154 } 11155 return false; 11156 } 11157 11158 private void replacePackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags, 11159 UserHandle user, String installerPackageName, String volumeUuid, 11160 PackageInstalledInfo res) { 11161 final PackageParser.Package oldPackage; 11162 final String pkgName = pkg.packageName; 11163 final int[] allUsers; 11164 final boolean[] perUserInstalled; 11165 final boolean weFroze; 11166 11167 // First find the old package info and check signatures 11168 synchronized(mPackages) { 11169 oldPackage = mPackages.get(pkgName); 11170 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 11171 final PackageSetting ps = mSettings.mPackages.get(pkgName); 11172 if (ps == null || !ps.keySetData.isUsingUpgradeKeySets() || ps.sharedUser != null) { 11173 // default to original signature matching 11174 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 11175 != PackageManager.SIGNATURE_MATCH) { 11176 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 11177 "New package has a different signature: " + pkgName); 11178 return; 11179 } 11180 } else { 11181 if(!checkUpgradeKeySetLP(ps, pkg)) { 11182 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 11183 "New package not signed by keys specified by upgrade-keysets: " 11184 + pkgName); 11185 return; 11186 } 11187 } 11188 11189 // In case of rollback, remember per-user/profile install state 11190 allUsers = sUserManager.getUserIds(); 11191 perUserInstalled = new boolean[allUsers.length]; 11192 for (int i = 0; i < allUsers.length; i++) { 11193 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 11194 } 11195 11196 // Mark the app as frozen to prevent launching during the upgrade 11197 // process, and then kill all running instances 11198 if (!ps.frozen) { 11199 ps.frozen = true; 11200 weFroze = true; 11201 } else { 11202 weFroze = false; 11203 } 11204 } 11205 11206 // Now that we're guarded by frozen state, kill app during upgrade 11207 killApplication(pkgName, oldPackage.applicationInfo.uid, "replace pkg"); 11208 11209 try { 11210 boolean sysPkg = (isSystemApp(oldPackage)); 11211 if (sysPkg) { 11212 replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 11213 user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res); 11214 } else { 11215 replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 11216 user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res); 11217 } 11218 } finally { 11219 // Regardless of success or failure of upgrade steps above, always 11220 // unfreeze the package if we froze it 11221 if (weFroze) { 11222 unfreezePackage(pkgName); 11223 } 11224 } 11225 } 11226 11227 private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage, 11228 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 11229 int[] allUsers, boolean[] perUserInstalled, String installerPackageName, 11230 String volumeUuid, PackageInstalledInfo res) { 11231 String pkgName = deletedPackage.packageName; 11232 boolean deletedPkg = true; 11233 boolean updatedSettings = false; 11234 11235 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 11236 + deletedPackage); 11237 long origUpdateTime; 11238 if (pkg.mExtras != null) { 11239 origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime; 11240 } else { 11241 origUpdateTime = 0; 11242 } 11243 11244 // First delete the existing package while retaining the data directory 11245 if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA, 11246 res.removedInfo, true)) { 11247 // If the existing package wasn't successfully deleted 11248 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI"); 11249 deletedPkg = false; 11250 } else { 11251 // Successfully deleted the old package; proceed with replace. 11252 11253 // If deleted package lived in a container, give users a chance to 11254 // relinquish resources before killing. 11255 if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) { 11256 if (DEBUG_INSTALL) { 11257 Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE"); 11258 } 11259 final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid }; 11260 final ArrayList<String> pkgList = new ArrayList<String>(1); 11261 pkgList.add(deletedPackage.applicationInfo.packageName); 11262 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 11263 } 11264 11265 deleteCodeCacheDirsLI(pkg.volumeUuid, pkgName); 11266 try { 11267 final PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, 11268 scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user); 11269 updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers, 11270 perUserInstalled, res, user); 11271 updatedSettings = true; 11272 } catch (PackageManagerException e) { 11273 res.setError("Package couldn't be installed in " + pkg.codePath, e); 11274 } 11275 } 11276 11277 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 11278 // remove package from internal structures. Note that we want deletePackageX to 11279 // delete the package data and cache directories that it created in 11280 // scanPackageLocked, unless those directories existed before we even tried to 11281 // install. 11282 if(updatedSettings) { 11283 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 11284 deletePackageLI( 11285 pkgName, null, true, allUsers, perUserInstalled, 11286 PackageManager.DELETE_KEEP_DATA, 11287 res.removedInfo, true); 11288 } 11289 // Since we failed to install the new package we need to restore the old 11290 // package that we deleted. 11291 if (deletedPkg) { 11292 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 11293 File restoreFile = new File(deletedPackage.codePath); 11294 // Parse old package 11295 boolean oldExternal = isExternal(deletedPackage); 11296 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 11297 (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) | 11298 (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 11299 int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME; 11300 try { 11301 scanPackageLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, null); 11302 } catch (PackageManagerException e) { 11303 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: " 11304 + e.getMessage()); 11305 return; 11306 } 11307 // Restore of old package succeeded. Update permissions. 11308 // writer 11309 synchronized (mPackages) { 11310 updatePermissionsLPw(deletedPackage.packageName, deletedPackage, 11311 UPDATE_PERMISSIONS_ALL); 11312 // can downgrade to reader 11313 mSettings.writeLPr(); 11314 } 11315 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 11316 } 11317 } 11318 } 11319 11320 private void replaceSystemPackageLI(PackageParser.Package deletedPackage, 11321 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 11322 int[] allUsers, boolean[] perUserInstalled, String installerPackageName, 11323 String volumeUuid, PackageInstalledInfo res) { 11324 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 11325 + ", old=" + deletedPackage); 11326 boolean disabledSystem = false; 11327 boolean updatedSettings = false; 11328 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 11329 if ((deletedPackage.applicationInfo.privateFlags&ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) 11330 != 0) { 11331 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 11332 } 11333 String packageName = deletedPackage.packageName; 11334 if (packageName == null) { 11335 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 11336 "Attempt to delete null packageName."); 11337 return; 11338 } 11339 PackageParser.Package oldPkg; 11340 PackageSetting oldPkgSetting; 11341 // reader 11342 synchronized (mPackages) { 11343 oldPkg = mPackages.get(packageName); 11344 oldPkgSetting = mSettings.mPackages.get(packageName); 11345 if((oldPkg == null) || (oldPkg.applicationInfo == null) || 11346 (oldPkgSetting == null)) { 11347 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 11348 "Couldn't find package:" + packageName + " information"); 11349 return; 11350 } 11351 } 11352 11353 res.removedInfo.uid = oldPkg.applicationInfo.uid; 11354 res.removedInfo.removedPackage = packageName; 11355 // Remove existing system package 11356 removePackageLI(oldPkgSetting, true); 11357 // writer 11358 synchronized (mPackages) { 11359 disabledSystem = mSettings.disableSystemPackageLPw(packageName); 11360 if (!disabledSystem && deletedPackage != null) { 11361 // We didn't need to disable the .apk as a current system package, 11362 // which means we are replacing another update that is already 11363 // installed. We need to make sure to delete the older one's .apk. 11364 res.removedInfo.args = createInstallArgsForExisting(0, 11365 deletedPackage.applicationInfo.getCodePath(), 11366 deletedPackage.applicationInfo.getResourcePath(), 11367 getAppDexInstructionSets(deletedPackage.applicationInfo)); 11368 } else { 11369 res.removedInfo.args = null; 11370 } 11371 } 11372 11373 // Successfully disabled the old package. Now proceed with re-installation 11374 deleteCodeCacheDirsLI(pkg.volumeUuid, packageName); 11375 11376 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 11377 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 11378 11379 PackageParser.Package newPackage = null; 11380 try { 11381 newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 0, user); 11382 if (newPackage.mExtras != null) { 11383 final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras; 11384 newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime; 11385 newPkgSetting.lastUpdateTime = System.currentTimeMillis(); 11386 11387 // is the update attempting to change shared user? that isn't going to work... 11388 if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) { 11389 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 11390 "Forbidding shared user change from " + oldPkgSetting.sharedUser 11391 + " to " + newPkgSetting.sharedUser); 11392 updatedSettings = true; 11393 } 11394 } 11395 11396 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 11397 updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers, 11398 perUserInstalled, res, user); 11399 updatedSettings = true; 11400 } 11401 11402 } catch (PackageManagerException e) { 11403 res.setError("Package couldn't be installed in " + pkg.codePath, e); 11404 } 11405 11406 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 11407 // Re installation failed. Restore old information 11408 // Remove new pkg information 11409 if (newPackage != null) { 11410 removeInstalledPackageLI(newPackage, true); 11411 } 11412 // Add back the old system package 11413 try { 11414 scanPackageLI(oldPkg, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user); 11415 } catch (PackageManagerException e) { 11416 Slog.e(TAG, "Failed to restore original package: " + e.getMessage()); 11417 } 11418 // Restore the old system information in Settings 11419 synchronized (mPackages) { 11420 if (disabledSystem) { 11421 mSettings.enableSystemPackageLPw(packageName); 11422 } 11423 if (updatedSettings) { 11424 mSettings.setInstallerPackageName(packageName, 11425 oldPkgSetting.installerPackageName); 11426 } 11427 mSettings.writeLPr(); 11428 } 11429 } 11430 } 11431 11432 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 11433 String volumeUuid, int[] allUsers, boolean[] perUserInstalled, PackageInstalledInfo res, 11434 UserHandle user) { 11435 String pkgName = newPackage.packageName; 11436 synchronized (mPackages) { 11437 //write settings. the installStatus will be incomplete at this stage. 11438 //note that the new package setting would have already been 11439 //added to mPackages. It hasn't been persisted yet. 11440 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 11441 mSettings.writeLPr(); 11442 } 11443 11444 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath); 11445 11446 synchronized (mPackages) { 11447 updatePermissionsLPw(newPackage.packageName, newPackage, 11448 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 11449 ? UPDATE_PERMISSIONS_ALL : 0)); 11450 // For system-bundled packages, we assume that installing an upgraded version 11451 // of the package implies that the user actually wants to run that new code, 11452 // so we enable the package. 11453 PackageSetting ps = mSettings.mPackages.get(pkgName); 11454 if (ps != null) { 11455 if (isSystemApp(newPackage)) { 11456 // NB: implicit assumption that system package upgrades apply to all users 11457 if (DEBUG_INSTALL) { 11458 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 11459 } 11460 if (res.origUsers != null) { 11461 for (int userHandle : res.origUsers) { 11462 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 11463 userHandle, installerPackageName); 11464 } 11465 } 11466 // Also convey the prior install/uninstall state 11467 if (allUsers != null && perUserInstalled != null) { 11468 for (int i = 0; i < allUsers.length; i++) { 11469 if (DEBUG_INSTALL) { 11470 Slog.d(TAG, " user " + allUsers[i] 11471 + " => " + perUserInstalled[i]); 11472 } 11473 ps.setInstalled(perUserInstalled[i], allUsers[i]); 11474 } 11475 // these install state changes will be persisted in the 11476 // upcoming call to mSettings.writeLPr(). 11477 } 11478 } 11479 // It's implied that when a user requests installation, they want the app to be 11480 // installed and enabled. 11481 int userId = user.getIdentifier(); 11482 if (userId != UserHandle.USER_ALL) { 11483 ps.setInstalled(true, userId); 11484 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName); 11485 } 11486 } 11487 res.name = pkgName; 11488 res.uid = newPackage.applicationInfo.uid; 11489 res.pkg = newPackage; 11490 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 11491 mSettings.setInstallerPackageName(pkgName, installerPackageName); 11492 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 11493 //to update install status 11494 mSettings.writeLPr(); 11495 } 11496 } 11497 11498 private void installPackageLI(InstallArgs args, PackageInstalledInfo res) { 11499 final int installFlags = args.installFlags; 11500 final String installerPackageName = args.installerPackageName; 11501 final String volumeUuid = args.volumeUuid; 11502 final File tmpPackageFile = new File(args.getCodePath()); 11503 final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 11504 final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) 11505 || (args.volumeUuid != null)); 11506 boolean replace = false; 11507 int scanFlags = SCAN_NEW_INSTALL | SCAN_FORCE_DEX | SCAN_UPDATE_SIGNATURE; 11508 // Result object to be returned 11509 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 11510 11511 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 11512 // Retrieve PackageSettings and parse package 11513 final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 11514 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 11515 | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 11516 PackageParser pp = new PackageParser(); 11517 pp.setSeparateProcesses(mSeparateProcesses); 11518 pp.setDisplayMetrics(mMetrics); 11519 11520 final PackageParser.Package pkg; 11521 try { 11522 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 11523 } catch (PackageParserException e) { 11524 res.setError("Failed parse during installPackageLI", e); 11525 return; 11526 } 11527 11528 // Mark that we have an install time CPU ABI override. 11529 pkg.cpuAbiOverride = args.abiOverride; 11530 11531 String pkgName = res.name = pkg.packageName; 11532 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 11533 if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) { 11534 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI"); 11535 return; 11536 } 11537 } 11538 11539 try { 11540 pp.collectCertificates(pkg, parseFlags); 11541 pp.collectManifestDigest(pkg); 11542 } catch (PackageParserException e) { 11543 res.setError("Failed collect during installPackageLI", e); 11544 return; 11545 } 11546 11547 /* If the installer passed in a manifest digest, compare it now. */ 11548 if (args.manifestDigest != null) { 11549 if (DEBUG_INSTALL) { 11550 final String parsedManifest = pkg.manifestDigest == null ? "null" 11551 : pkg.manifestDigest.toString(); 11552 Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. " 11553 + parsedManifest); 11554 } 11555 11556 if (!args.manifestDigest.equals(pkg.manifestDigest)) { 11557 res.setError(INSTALL_FAILED_PACKAGE_CHANGED, "Manifest digest changed"); 11558 return; 11559 } 11560 } else if (DEBUG_INSTALL) { 11561 final String parsedManifest = pkg.manifestDigest == null 11562 ? "null" : pkg.manifestDigest.toString(); 11563 Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest); 11564 } 11565 11566 // Get rid of all references to package scan path via parser. 11567 pp = null; 11568 String oldCodePath = null; 11569 boolean systemApp = false; 11570 synchronized (mPackages) { 11571 // Check if installing already existing package 11572 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 11573 String oldName = mSettings.mRenamedPackages.get(pkgName); 11574 if (pkg.mOriginalPackages != null 11575 && pkg.mOriginalPackages.contains(oldName) 11576 && mPackages.containsKey(oldName)) { 11577 // This package is derived from an original package, 11578 // and this device has been updating from that original 11579 // name. We must continue using the original name, so 11580 // rename the new package here. 11581 pkg.setPackageName(oldName); 11582 pkgName = pkg.packageName; 11583 replace = true; 11584 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 11585 + oldName + " pkgName=" + pkgName); 11586 } else if (mPackages.containsKey(pkgName)) { 11587 // This package, under its official name, already exists 11588 // on the device; we should replace it. 11589 replace = true; 11590 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 11591 } 11592 11593 // Prevent apps opting out from runtime permissions 11594 if (replace) { 11595 PackageParser.Package oldPackage = mPackages.get(pkgName); 11596 final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion; 11597 final int newTargetSdk = pkg.applicationInfo.targetSdkVersion; 11598 if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1 11599 && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) { 11600 res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE, 11601 "Package " + pkg.packageName + " new target SDK " + newTargetSdk 11602 + " doesn't support runtime permissions but the old" 11603 + " target SDK " + oldTargetSdk + " does."); 11604 return; 11605 } 11606 } 11607 } 11608 11609 PackageSetting ps = mSettings.mPackages.get(pkgName); 11610 if (ps != null) { 11611 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 11612 11613 // Quick sanity check that we're signed correctly if updating; 11614 // we'll check this again later when scanning, but we want to 11615 // bail early here before tripping over redefined permissions. 11616 if (!ps.keySetData.isUsingUpgradeKeySets() || ps.sharedUser != null) { 11617 try { 11618 verifySignaturesLP(ps, pkg); 11619 } catch (PackageManagerException e) { 11620 res.setError(e.error, e.getMessage()); 11621 return; 11622 } 11623 } else { 11624 if (!checkUpgradeKeySetLP(ps, pkg)) { 11625 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 11626 + pkg.packageName + " upgrade keys do not match the " 11627 + "previously installed version"); 11628 return; 11629 } 11630 } 11631 11632 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 11633 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 11634 systemApp = (ps.pkg.applicationInfo.flags & 11635 ApplicationInfo.FLAG_SYSTEM) != 0; 11636 } 11637 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 11638 } 11639 11640 // Check whether the newly-scanned package wants to define an already-defined perm 11641 int N = pkg.permissions.size(); 11642 for (int i = N-1; i >= 0; i--) { 11643 PackageParser.Permission perm = pkg.permissions.get(i); 11644 BasePermission bp = mSettings.mPermissions.get(perm.info.name); 11645 if (bp != null) { 11646 // If the defining package is signed with our cert, it's okay. This 11647 // also includes the "updating the same package" case, of course. 11648 // "updating same package" could also involve key-rotation. 11649 final boolean sigsOk; 11650 if (!bp.sourcePackage.equals(pkg.packageName) 11651 || !(bp.packageSetting instanceof PackageSetting) 11652 || !bp.packageSetting.keySetData.isUsingUpgradeKeySets() 11653 || ((PackageSetting) bp.packageSetting).sharedUser != null) { 11654 sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures, 11655 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 11656 } else { 11657 sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg); 11658 } 11659 if (!sigsOk) { 11660 // If the owning package is the system itself, we log but allow 11661 // install to proceed; we fail the install on all other permission 11662 // redefinitions. 11663 if (!bp.sourcePackage.equals("android")) { 11664 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package " 11665 + pkg.packageName + " attempting to redeclare permission " 11666 + perm.info.name + " already owned by " + bp.sourcePackage); 11667 res.origPermission = perm.info.name; 11668 res.origPackage = bp.sourcePackage; 11669 return; 11670 } else { 11671 Slog.w(TAG, "Package " + pkg.packageName 11672 + " attempting to redeclare system permission " 11673 + perm.info.name + "; ignoring new declaration"); 11674 pkg.permissions.remove(i); 11675 } 11676 } 11677 } 11678 } 11679 11680 } 11681 11682 if (systemApp && onExternal) { 11683 // Disable updates to system apps on sdcard 11684 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 11685 "Cannot install updates to system apps on sdcard"); 11686 return; 11687 } 11688 11689 if (args.move != null) { 11690 // We did an in-place move, so dex is ready to roll 11691 scanFlags |= SCAN_NO_DEX; 11692 scanFlags |= SCAN_MOVE; 11693 } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) { 11694 // Enable SCAN_NO_DEX flag to skip dexopt at a later stage 11695 scanFlags |= SCAN_NO_DEX; 11696 11697 try { 11698 deriveNonSystemPackageAbi(pkg, new File(pkg.codePath), args.abiOverride, 11699 true /* extract libs */); 11700 } catch (PackageManagerException pme) { 11701 Slog.e(TAG, "Error deriving application ABI", pme); 11702 res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI"); 11703 return; 11704 } 11705 11706 // Run dexopt before old package gets removed, to minimize time when app is unavailable 11707 int result = mPackageDexOptimizer 11708 .performDexOpt(pkg, null /* instruction sets */, true /* forceDex */, 11709 false /* defer */, false /* inclDependencies */); 11710 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 11711 res.setError(INSTALL_FAILED_DEXOPT, "Dexopt failed for " + pkg.codePath); 11712 return; 11713 } 11714 } 11715 11716 if (!args.doRename(res.returnCode, pkg, oldCodePath)) { 11717 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename"); 11718 return; 11719 } 11720 11721 startIntentFilterVerifications(args.user.getIdentifier(), pkg); 11722 11723 if (replace) { 11724 replacePackageLI(pkg, parseFlags, scanFlags, args.user, 11725 installerPackageName, volumeUuid, res); 11726 } else { 11727 installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES, 11728 args.user, installerPackageName, volumeUuid, res); 11729 } 11730 synchronized (mPackages) { 11731 final PackageSetting ps = mSettings.mPackages.get(pkgName); 11732 if (ps != null) { 11733 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 11734 } 11735 } 11736 } 11737 11738 private void startIntentFilterVerifications(int userId, PackageParser.Package pkg) { 11739 if (mIntentFilterVerifierComponent == null) { 11740 Slog.d(TAG, "No IntentFilter verification will not be done as " 11741 + "there is no IntentFilterVerifier available!"); 11742 return; 11743 } 11744 11745 final int verifierUid = getPackageUid( 11746 mIntentFilterVerifierComponent.getPackageName(), 11747 (userId == UserHandle.USER_ALL) ? UserHandle.USER_OWNER : userId); 11748 11749 mHandler.removeMessages(START_INTENT_FILTER_VERIFICATIONS); 11750 final Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 11751 msg.obj = pkg; 11752 msg.arg1 = userId; 11753 msg.arg2 = verifierUid; 11754 11755 mHandler.sendMessage(msg); 11756 } 11757 11758 private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, 11759 PackageParser.Package pkg) { 11760 int size = pkg.activities.size(); 11761 if (size == 0) { 11762 Slog.d(TAG, "No activity, so no need to verify any IntentFilter!"); 11763 return; 11764 } 11765 11766 final boolean hasDomainURLs = hasDomainURLs(pkg); 11767 if (!hasDomainURLs) { 11768 Slog.d(TAG, "No domain URLs, so no need to verify any IntentFilter!"); 11769 return; 11770 } 11771 11772 Slog.d(TAG, "Checking for userId:" + userId + " if any IntentFilter from the " + size 11773 + " Activities needs verification ..."); 11774 11775 final int verificationId = mIntentFilterVerificationToken++; 11776 int count = 0; 11777 final String packageName = pkg.packageName; 11778 ArrayList<String> allHosts = new ArrayList<>(); 11779 11780 synchronized (mPackages) { 11781 for (PackageParser.Activity a : pkg.activities) { 11782 for (ActivityIntentInfo filter : a.intents) { 11783 boolean needsFilterVerification = filter.needsVerification(); 11784 if (needsFilterVerification && needsNetworkVerificationLPr(filter)) { 11785 Slog.d(TAG, "Verification needed for IntentFilter:" + filter.toString()); 11786 mIntentFilterVerifier.addOneIntentFilterVerification( 11787 verifierUid, userId, verificationId, filter, packageName); 11788 count++; 11789 } else if (!needsFilterVerification) { 11790 Slog.d(TAG, "No verification needed for IntentFilter:" + filter.toString()); 11791 if (hasValidDomains(filter)) { 11792 ArrayList<String> hosts = filter.getHostsList(); 11793 if (hosts.size() > 0) { 11794 allHosts.addAll(hosts); 11795 } else { 11796 if (allHosts.isEmpty()) { 11797 allHosts.add("*"); 11798 } 11799 } 11800 } 11801 } else { 11802 Slog.d(TAG, "Verification already done for IntentFilter:" 11803 + filter.toString()); 11804 } 11805 } 11806 } 11807 } 11808 11809 if (count > 0) { 11810 mIntentFilterVerifier.startVerifications(userId); 11811 Slog.d(TAG, "Started " + count + " IntentFilter verification" 11812 + (count > 1 ? "s" : "") + " for userId:" + userId + "!"); 11813 } else { 11814 Slog.d(TAG, "No need to start any IntentFilter verification!"); 11815 if (allHosts.size() > 0 && mSettings.createIntentFilterVerificationIfNeededLPw( 11816 packageName, allHosts) != null) { 11817 scheduleWriteSettingsLocked(); 11818 } 11819 } 11820 } 11821 11822 private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) { 11823 final ComponentName cn = filter.activity.getComponentName(); 11824 final String packageName = cn.getPackageName(); 11825 11826 IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr( 11827 packageName); 11828 if (ivi == null) { 11829 return true; 11830 } 11831 int status = ivi.getStatus(); 11832 switch (status) { 11833 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 11834 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 11835 return true; 11836 11837 default: 11838 // Nothing to do 11839 return false; 11840 } 11841 } 11842 11843 private boolean isSystemComponentOrPersistentPrivApp(PackageParser.Package pkg) { 11844 return UserHandle.getAppId(pkg.applicationInfo.uid) < FIRST_APPLICATION_UID 11845 || ((pkg.applicationInfo.privateFlags 11846 & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0 11847 && (pkg.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0); 11848 } 11849 11850 private static boolean isMultiArch(PackageSetting ps) { 11851 return (ps.pkgFlags & ApplicationInfo.FLAG_MULTIARCH) != 0; 11852 } 11853 11854 private static boolean isMultiArch(ApplicationInfo info) { 11855 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0; 11856 } 11857 11858 private static boolean isExternal(PackageParser.Package pkg) { 11859 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 11860 } 11861 11862 private static boolean isExternal(PackageSetting ps) { 11863 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 11864 } 11865 11866 private static boolean isExternal(ApplicationInfo info) { 11867 return (info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 11868 } 11869 11870 private static boolean isSystemApp(PackageParser.Package pkg) { 11871 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 11872 } 11873 11874 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 11875 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 11876 } 11877 11878 private static boolean hasDomainURLs(PackageParser.Package pkg) { 11879 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0; 11880 } 11881 11882 private static boolean isSystemApp(PackageSetting ps) { 11883 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 11884 } 11885 11886 private static boolean isUpdatedSystemApp(PackageSetting ps) { 11887 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 11888 } 11889 11890 private int packageFlagsToInstallFlags(PackageSetting ps) { 11891 int installFlags = 0; 11892 if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) { 11893 // This existing package was an external ASEC install when we have 11894 // the external flag without a UUID 11895 installFlags |= PackageManager.INSTALL_EXTERNAL; 11896 } 11897 if (ps.isForwardLocked()) { 11898 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 11899 } 11900 return installFlags; 11901 } 11902 11903 private void deleteTempPackageFiles() { 11904 final FilenameFilter filter = new FilenameFilter() { 11905 public boolean accept(File dir, String name) { 11906 return name.startsWith("vmdl") && name.endsWith(".tmp"); 11907 } 11908 }; 11909 for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) { 11910 file.delete(); 11911 } 11912 } 11913 11914 @Override 11915 public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId, 11916 int flags) { 11917 deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId, 11918 flags); 11919 } 11920 11921 @Override 11922 public void deletePackage(final String packageName, 11923 final IPackageDeleteObserver2 observer, final int userId, final int flags) { 11924 mContext.enforceCallingOrSelfPermission( 11925 android.Manifest.permission.DELETE_PACKAGES, null); 11926 final int uid = Binder.getCallingUid(); 11927 if (UserHandle.getUserId(uid) != userId) { 11928 mContext.enforceCallingPermission( 11929 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 11930 "deletePackage for user " + userId); 11931 } 11932 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 11933 try { 11934 observer.onPackageDeleted(packageName, 11935 PackageManager.DELETE_FAILED_USER_RESTRICTED, null); 11936 } catch (RemoteException re) { 11937 } 11938 return; 11939 } 11940 11941 boolean uninstallBlocked = false; 11942 if ((flags & PackageManager.DELETE_ALL_USERS) != 0) { 11943 int[] users = sUserManager.getUserIds(); 11944 for (int i = 0; i < users.length; ++i) { 11945 if (getBlockUninstallForUser(packageName, users[i])) { 11946 uninstallBlocked = true; 11947 break; 11948 } 11949 } 11950 } else { 11951 uninstallBlocked = getBlockUninstallForUser(packageName, userId); 11952 } 11953 if (uninstallBlocked) { 11954 try { 11955 observer.onPackageDeleted(packageName, PackageManager.DELETE_FAILED_OWNER_BLOCKED, 11956 null); 11957 } catch (RemoteException re) { 11958 } 11959 return; 11960 } 11961 11962 if (DEBUG_REMOVE) { 11963 Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId); 11964 } 11965 // Queue up an async operation since the package deletion may take a little while. 11966 mHandler.post(new Runnable() { 11967 public void run() { 11968 mHandler.removeCallbacks(this); 11969 final int returnCode = deletePackageX(packageName, userId, flags); 11970 if (observer != null) { 11971 try { 11972 observer.onPackageDeleted(packageName, returnCode, null); 11973 } catch (RemoteException e) { 11974 Log.i(TAG, "Observer no longer exists."); 11975 } //end catch 11976 } //end if 11977 } //end run 11978 }); 11979 } 11980 11981 private boolean isPackageDeviceAdmin(String packageName, int userId) { 11982 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 11983 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 11984 try { 11985 if (dpm != null) { 11986 if (dpm.isDeviceOwner(packageName)) { 11987 return true; 11988 } 11989 int[] users; 11990 if (userId == UserHandle.USER_ALL) { 11991 users = sUserManager.getUserIds(); 11992 } else { 11993 users = new int[]{userId}; 11994 } 11995 for (int i = 0; i < users.length; ++i) { 11996 if (dpm.packageHasActiveAdmins(packageName, users[i])) { 11997 return true; 11998 } 11999 } 12000 } 12001 } catch (RemoteException e) { 12002 } 12003 return false; 12004 } 12005 12006 /** 12007 * This method is an internal method that could be get invoked either 12008 * to delete an installed package or to clean up a failed installation. 12009 * After deleting an installed package, a broadcast is sent to notify any 12010 * listeners that the package has been installed. For cleaning up a failed 12011 * installation, the broadcast is not necessary since the package's 12012 * installation wouldn't have sent the initial broadcast either 12013 * The key steps in deleting a package are 12014 * deleting the package information in internal structures like mPackages, 12015 * deleting the packages base directories through installd 12016 * updating mSettings to reflect current status 12017 * persisting settings for later use 12018 * sending a broadcast if necessary 12019 */ 12020 private int deletePackageX(String packageName, int userId, int flags) { 12021 final PackageRemovedInfo info = new PackageRemovedInfo(); 12022 final boolean res; 12023 12024 final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0 12025 ? UserHandle.ALL : new UserHandle(userId); 12026 12027 if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) { 12028 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 12029 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 12030 } 12031 12032 boolean removedForAllUsers = false; 12033 boolean systemUpdate = false; 12034 12035 // for the uninstall-updates case and restricted profiles, remember the per- 12036 // userhandle installed state 12037 int[] allUsers; 12038 boolean[] perUserInstalled; 12039 synchronized (mPackages) { 12040 PackageSetting ps = mSettings.mPackages.get(packageName); 12041 allUsers = sUserManager.getUserIds(); 12042 perUserInstalled = new boolean[allUsers.length]; 12043 for (int i = 0; i < allUsers.length; i++) { 12044 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 12045 } 12046 } 12047 12048 synchronized (mInstallLock) { 12049 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 12050 res = deletePackageLI(packageName, removeForUser, 12051 true, allUsers, perUserInstalled, 12052 flags | REMOVE_CHATTY, info, true); 12053 systemUpdate = info.isRemovedPackageSystemUpdate; 12054 if (res && !systemUpdate && mPackages.get(packageName) == null) { 12055 removedForAllUsers = true; 12056 } 12057 if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate 12058 + " removedForAllUsers=" + removedForAllUsers); 12059 } 12060 12061 if (res) { 12062 info.sendBroadcast(true, systemUpdate, removedForAllUsers); 12063 12064 // If the removed package was a system update, the old system package 12065 // was re-enabled; we need to broadcast this information 12066 if (systemUpdate) { 12067 Bundle extras = new Bundle(1); 12068 extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0 12069 ? info.removedAppId : info.uid); 12070 extras.putBoolean(Intent.EXTRA_REPLACING, true); 12071 12072 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 12073 extras, null, null, null); 12074 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName, 12075 extras, null, null, null); 12076 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null, 12077 null, packageName, null, null); 12078 } 12079 } 12080 // Force a gc here. 12081 Runtime.getRuntime().gc(); 12082 // Delete the resources here after sending the broadcast to let 12083 // other processes clean up before deleting resources. 12084 if (info.args != null) { 12085 synchronized (mInstallLock) { 12086 info.args.doPostDeleteLI(true); 12087 } 12088 } 12089 12090 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 12091 } 12092 12093 class PackageRemovedInfo { 12094 String removedPackage; 12095 int uid = -1; 12096 int removedAppId = -1; 12097 int[] removedUsers = null; 12098 boolean isRemovedPackageSystemUpdate = false; 12099 // Clean up resources deleted packages. 12100 InstallArgs args = null; 12101 12102 void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) { 12103 Bundle extras = new Bundle(1); 12104 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 12105 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove); 12106 if (replacing) { 12107 extras.putBoolean(Intent.EXTRA_REPLACING, true); 12108 } 12109 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 12110 if (removedPackage != null) { 12111 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 12112 extras, null, null, removedUsers); 12113 if (fullRemove && !replacing) { 12114 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage, 12115 extras, null, null, removedUsers); 12116 } 12117 } 12118 if (removedAppId >= 0) { 12119 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null, 12120 removedUsers); 12121 } 12122 } 12123 } 12124 12125 /* 12126 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 12127 * flag is not set, the data directory is removed as well. 12128 * make sure this flag is set for partially installed apps. If not its meaningless to 12129 * delete a partially installed application. 12130 */ 12131 private void removePackageDataLI(PackageSetting ps, 12132 int[] allUserHandles, boolean[] perUserInstalled, 12133 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 12134 String packageName = ps.name; 12135 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 12136 removePackageLI(ps, (flags&REMOVE_CHATTY) != 0); 12137 // Retrieve object to delete permissions for shared user later on 12138 final PackageSetting deletedPs; 12139 // reader 12140 synchronized (mPackages) { 12141 deletedPs = mSettings.mPackages.get(packageName); 12142 if (outInfo != null) { 12143 outInfo.removedPackage = packageName; 12144 outInfo.removedUsers = deletedPs != null 12145 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true) 12146 : null; 12147 } 12148 } 12149 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 12150 removeDataDirsLI(ps.volumeUuid, packageName); 12151 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 12152 } 12153 // writer 12154 synchronized (mPackages) { 12155 if (deletedPs != null) { 12156 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 12157 clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL); 12158 clearDefaultBrowserIfNeeded(packageName); 12159 if (outInfo != null) { 12160 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName); 12161 outInfo.removedAppId = mSettings.removePackageLPw(packageName); 12162 } 12163 updatePermissionsLPw(deletedPs.name, null, 0); 12164 if (deletedPs.sharedUser != null) { 12165 // Remove permissions associated with package. Since runtime 12166 // permissions are per user we have to kill the removed package 12167 // or packages running under the shared user of the removed 12168 // package if revoking the permissions requested only by the removed 12169 // package is successful and this causes a change in gids. 12170 for (int userId : UserManagerService.getInstance().getUserIds()) { 12171 final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs, 12172 userId); 12173 if (userIdToKill == UserHandle.USER_ALL 12174 || userIdToKill >= UserHandle.USER_OWNER) { 12175 // If gids changed for this user, kill all affected packages. 12176 mHandler.post(new Runnable() { 12177 @Override 12178 public void run() { 12179 // This has to happen with no lock held. 12180 killSettingPackagesForUser(deletedPs, userIdToKill, 12181 KILL_APP_REASON_GIDS_CHANGED); 12182 } 12183 }); 12184 break; 12185 } 12186 } 12187 } 12188 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 12189 } 12190 // make sure to preserve per-user disabled state if this removal was just 12191 // a downgrade of a system app to the factory package 12192 if (allUserHandles != null && perUserInstalled != null) { 12193 if (DEBUG_REMOVE) { 12194 Slog.d(TAG, "Propagating install state across downgrade"); 12195 } 12196 for (int i = 0; i < allUserHandles.length; i++) { 12197 if (DEBUG_REMOVE) { 12198 Slog.d(TAG, " user " + allUserHandles[i] 12199 + " => " + perUserInstalled[i]); 12200 } 12201 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 12202 } 12203 } 12204 } 12205 // can downgrade to reader 12206 if (writeSettings) { 12207 // Save settings now 12208 mSettings.writeLPr(); 12209 } 12210 } 12211 if (outInfo != null) { 12212 // A user ID was deleted here. Go through all users and remove it 12213 // from KeyStore. 12214 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId); 12215 } 12216 } 12217 12218 static boolean locationIsPrivileged(File path) { 12219 try { 12220 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app") 12221 .getCanonicalPath(); 12222 return path.getCanonicalPath().startsWith(privilegedAppDir); 12223 } catch (IOException e) { 12224 Slog.e(TAG, "Unable to access code path " + path); 12225 } 12226 return false; 12227 } 12228 12229 /* 12230 * Tries to delete system package. 12231 */ 12232 private boolean deleteSystemPackageLI(PackageSetting newPs, 12233 int[] allUserHandles, boolean[] perUserInstalled, 12234 int flags, PackageRemovedInfo outInfo, boolean writeSettings) { 12235 final boolean applyUserRestrictions 12236 = (allUserHandles != null) && (perUserInstalled != null); 12237 PackageSetting disabledPs = null; 12238 // Confirm if the system package has been updated 12239 // An updated system app can be deleted. This will also have to restore 12240 // the system pkg from system partition 12241 // reader 12242 synchronized (mPackages) { 12243 disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name); 12244 } 12245 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs 12246 + " disabledPs=" + disabledPs); 12247 if (disabledPs == null) { 12248 Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name); 12249 return false; 12250 } else if (DEBUG_REMOVE) { 12251 Slog.d(TAG, "Deleting system pkg from data partition"); 12252 } 12253 if (DEBUG_REMOVE) { 12254 if (applyUserRestrictions) { 12255 Slog.d(TAG, "Remembering install states:"); 12256 for (int i = 0; i < allUserHandles.length; i++) { 12257 Slog.d(TAG, " u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]); 12258 } 12259 } 12260 } 12261 // Delete the updated package 12262 outInfo.isRemovedPackageSystemUpdate = true; 12263 if (disabledPs.versionCode < newPs.versionCode) { 12264 // Delete data for downgrades 12265 flags &= ~PackageManager.DELETE_KEEP_DATA; 12266 } else { 12267 // Preserve data by setting flag 12268 flags |= PackageManager.DELETE_KEEP_DATA; 12269 } 12270 boolean ret = deleteInstalledPackageLI(newPs, true, flags, 12271 allUserHandles, perUserInstalled, outInfo, writeSettings); 12272 if (!ret) { 12273 return false; 12274 } 12275 // writer 12276 synchronized (mPackages) { 12277 // Reinstate the old system package 12278 mSettings.enableSystemPackageLPw(newPs.name); 12279 // Remove any native libraries from the upgraded package. 12280 NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString); 12281 } 12282 // Install the system package 12283 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 12284 int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM; 12285 if (locationIsPrivileged(disabledPs.codePath)) { 12286 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 12287 } 12288 12289 final PackageParser.Package newPkg; 12290 try { 12291 newPkg = scanPackageLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null); 12292 } catch (PackageManagerException e) { 12293 Slog.w(TAG, "Failed to restore system package:" + newPs.name + ": " + e.getMessage()); 12294 return false; 12295 } 12296 12297 // writer 12298 synchronized (mPackages) { 12299 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName); 12300 updatePermissionsLPw(newPkg.packageName, newPkg, 12301 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 12302 if (applyUserRestrictions) { 12303 if (DEBUG_REMOVE) { 12304 Slog.d(TAG, "Propagating install state across reinstall"); 12305 } 12306 for (int i = 0; i < allUserHandles.length; i++) { 12307 if (DEBUG_REMOVE) { 12308 Slog.d(TAG, " user " + allUserHandles[i] 12309 + " => " + perUserInstalled[i]); 12310 } 12311 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 12312 } 12313 // Regardless of writeSettings we need to ensure that this restriction 12314 // state propagation is persisted 12315 mSettings.writeAllUsersPackageRestrictionsLPr(); 12316 } 12317 // can downgrade to reader here 12318 if (writeSettings) { 12319 mSettings.writeLPr(); 12320 } 12321 } 12322 return true; 12323 } 12324 12325 private boolean deleteInstalledPackageLI(PackageSetting ps, 12326 boolean deleteCodeAndResources, int flags, 12327 int[] allUserHandles, boolean[] perUserInstalled, 12328 PackageRemovedInfo outInfo, boolean writeSettings) { 12329 if (outInfo != null) { 12330 outInfo.uid = ps.appId; 12331 } 12332 12333 // Delete package data from internal structures and also remove data if flag is set 12334 removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings); 12335 12336 // Delete application code and resources 12337 if (deleteCodeAndResources && (outInfo != null)) { 12338 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 12339 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 12340 if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args); 12341 } 12342 return true; 12343 } 12344 12345 @Override 12346 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 12347 int userId) { 12348 mContext.enforceCallingOrSelfPermission( 12349 android.Manifest.permission.DELETE_PACKAGES, null); 12350 synchronized (mPackages) { 12351 PackageSetting ps = mSettings.mPackages.get(packageName); 12352 if (ps == null) { 12353 Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName); 12354 return false; 12355 } 12356 if (!ps.getInstalled(userId)) { 12357 // Can't block uninstall for an app that is not installed or enabled. 12358 Log.i(TAG, "Package not installed in set block uninstall " + packageName); 12359 return false; 12360 } 12361 ps.setBlockUninstall(blockUninstall, userId); 12362 mSettings.writePackageRestrictionsLPr(userId); 12363 } 12364 return true; 12365 } 12366 12367 @Override 12368 public boolean getBlockUninstallForUser(String packageName, int userId) { 12369 synchronized (mPackages) { 12370 PackageSetting ps = mSettings.mPackages.get(packageName); 12371 if (ps == null) { 12372 Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName); 12373 return false; 12374 } 12375 return ps.getBlockUninstall(userId); 12376 } 12377 } 12378 12379 /* 12380 * This method handles package deletion in general 12381 */ 12382 private boolean deletePackageLI(String packageName, UserHandle user, 12383 boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled, 12384 int flags, PackageRemovedInfo outInfo, 12385 boolean writeSettings) { 12386 if (packageName == null) { 12387 Slog.w(TAG, "Attempt to delete null packageName."); 12388 return false; 12389 } 12390 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 12391 PackageSetting ps; 12392 boolean dataOnly = false; 12393 int removeUser = -1; 12394 int appId = -1; 12395 synchronized (mPackages) { 12396 ps = mSettings.mPackages.get(packageName); 12397 if (ps == null) { 12398 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 12399 return false; 12400 } 12401 if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 12402 && user.getIdentifier() != UserHandle.USER_ALL) { 12403 // The caller is asking that the package only be deleted for a single 12404 // user. To do this, we just mark its uninstalled state and delete 12405 // its data. If this is a system app, we only allow this to happen if 12406 // they have set the special DELETE_SYSTEM_APP which requests different 12407 // semantics than normal for uninstalling system apps. 12408 if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user"); 12409 ps.setUserState(user.getIdentifier(), 12410 COMPONENT_ENABLED_STATE_DEFAULT, 12411 false, //installed 12412 true, //stopped 12413 true, //notLaunched 12414 false, //hidden 12415 null, null, null, 12416 false, // blockUninstall 12417 INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED); 12418 if (!isSystemApp(ps)) { 12419 if (ps.isAnyInstalled(sUserManager.getUserIds())) { 12420 // Other user still have this package installed, so all 12421 // we need to do is clear this user's data and save that 12422 // it is uninstalled. 12423 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 12424 removeUser = user.getIdentifier(); 12425 appId = ps.appId; 12426 scheduleWritePackageRestrictionsLocked(removeUser); 12427 } else { 12428 // We need to set it back to 'installed' so the uninstall 12429 // broadcasts will be sent correctly. 12430 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 12431 ps.setInstalled(true, user.getIdentifier()); 12432 } 12433 } else { 12434 // This is a system app, so we assume that the 12435 // other users still have this package installed, so all 12436 // we need to do is clear this user's data and save that 12437 // it is uninstalled. 12438 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 12439 removeUser = user.getIdentifier(); 12440 appId = ps.appId; 12441 scheduleWritePackageRestrictionsLocked(removeUser); 12442 } 12443 } 12444 } 12445 12446 if (removeUser >= 0) { 12447 // From above, we determined that we are deleting this only 12448 // for a single user. Continue the work here. 12449 if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser); 12450 if (outInfo != null) { 12451 outInfo.removedPackage = packageName; 12452 outInfo.removedAppId = appId; 12453 outInfo.removedUsers = new int[] {removeUser}; 12454 } 12455 mInstaller.clearUserData(ps.volumeUuid, packageName, removeUser); 12456 removeKeystoreDataIfNeeded(removeUser, appId); 12457 schedulePackageCleaning(packageName, removeUser, false); 12458 synchronized (mPackages) { 12459 if (clearPackagePreferredActivitiesLPw(packageName, removeUser)) { 12460 scheduleWritePackageRestrictionsLocked(removeUser); 12461 } 12462 } 12463 return true; 12464 } 12465 12466 if (dataOnly) { 12467 // Delete application data first 12468 if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only"); 12469 removePackageDataLI(ps, null, null, outInfo, flags, writeSettings); 12470 return true; 12471 } 12472 12473 boolean ret = false; 12474 if (isSystemApp(ps)) { 12475 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name); 12476 // When an updated system application is deleted we delete the existing resources as well and 12477 // fall back to existing code in system partition 12478 ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled, 12479 flags, outInfo, writeSettings); 12480 } else { 12481 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name); 12482 // Kill application pre-emptively especially for apps on sd. 12483 killApplication(packageName, ps.appId, "uninstall pkg"); 12484 ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags, 12485 allUserHandles, perUserInstalled, 12486 outInfo, writeSettings); 12487 } 12488 12489 return ret; 12490 } 12491 12492 private final class ClearStorageConnection implements ServiceConnection { 12493 IMediaContainerService mContainerService; 12494 12495 @Override 12496 public void onServiceConnected(ComponentName name, IBinder service) { 12497 synchronized (this) { 12498 mContainerService = IMediaContainerService.Stub.asInterface(service); 12499 notifyAll(); 12500 } 12501 } 12502 12503 @Override 12504 public void onServiceDisconnected(ComponentName name) { 12505 } 12506 } 12507 12508 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 12509 final boolean mounted; 12510 if (Environment.isExternalStorageEmulated()) { 12511 mounted = true; 12512 } else { 12513 final String status = Environment.getExternalStorageState(); 12514 12515 mounted = status.equals(Environment.MEDIA_MOUNTED) 12516 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 12517 } 12518 12519 if (!mounted) { 12520 return; 12521 } 12522 12523 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 12524 int[] users; 12525 if (userId == UserHandle.USER_ALL) { 12526 users = sUserManager.getUserIds(); 12527 } else { 12528 users = new int[] { userId }; 12529 } 12530 final ClearStorageConnection conn = new ClearStorageConnection(); 12531 if (mContext.bindServiceAsUser( 12532 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.OWNER)) { 12533 try { 12534 for (int curUser : users) { 12535 long timeout = SystemClock.uptimeMillis() + 5000; 12536 synchronized (conn) { 12537 long now = SystemClock.uptimeMillis(); 12538 while (conn.mContainerService == null && now < timeout) { 12539 try { 12540 conn.wait(timeout - now); 12541 } catch (InterruptedException e) { 12542 } 12543 } 12544 } 12545 if (conn.mContainerService == null) { 12546 return; 12547 } 12548 12549 final UserEnvironment userEnv = new UserEnvironment(curUser); 12550 clearDirectory(conn.mContainerService, 12551 userEnv.buildExternalStorageAppCacheDirs(packageName)); 12552 if (allData) { 12553 clearDirectory(conn.mContainerService, 12554 userEnv.buildExternalStorageAppDataDirs(packageName)); 12555 clearDirectory(conn.mContainerService, 12556 userEnv.buildExternalStorageAppMediaDirs(packageName)); 12557 } 12558 } 12559 } finally { 12560 mContext.unbindService(conn); 12561 } 12562 } 12563 } 12564 12565 @Override 12566 public void clearApplicationUserData(final String packageName, 12567 final IPackageDataObserver observer, final int userId) { 12568 mContext.enforceCallingOrSelfPermission( 12569 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 12570 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "clear application data"); 12571 // Queue up an async operation since the package deletion may take a little while. 12572 mHandler.post(new Runnable() { 12573 public void run() { 12574 mHandler.removeCallbacks(this); 12575 final boolean succeeded; 12576 synchronized (mInstallLock) { 12577 succeeded = clearApplicationUserDataLI(packageName, userId); 12578 } 12579 clearExternalStorageDataSync(packageName, userId, true); 12580 if (succeeded) { 12581 // invoke DeviceStorageMonitor's update method to clear any notifications 12582 DeviceStorageMonitorInternal 12583 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 12584 if (dsm != null) { 12585 dsm.checkMemory(); 12586 } 12587 } 12588 if(observer != null) { 12589 try { 12590 observer.onRemoveCompleted(packageName, succeeded); 12591 } catch (RemoteException e) { 12592 Log.i(TAG, "Observer no longer exists."); 12593 } 12594 } //end if observer 12595 } //end run 12596 }); 12597 } 12598 12599 private boolean clearApplicationUserDataLI(String packageName, int userId) { 12600 if (packageName == null) { 12601 Slog.w(TAG, "Attempt to delete null packageName."); 12602 return false; 12603 } 12604 12605 // Try finding details about the requested package 12606 PackageParser.Package pkg; 12607 synchronized (mPackages) { 12608 pkg = mPackages.get(packageName); 12609 if (pkg == null) { 12610 final PackageSetting ps = mSettings.mPackages.get(packageName); 12611 if (ps != null) { 12612 pkg = ps.pkg; 12613 } 12614 } 12615 } 12616 12617 if (pkg == null) { 12618 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 12619 } 12620 12621 // Always delete data directories for package, even if we found no other 12622 // record of app. This helps users recover from UID mismatches without 12623 // resorting to a full data wipe. 12624 int retCode = mInstaller.clearUserData(pkg.volumeUuid, packageName, userId); 12625 if (retCode < 0) { 12626 Slog.w(TAG, "Couldn't remove cache files for package: " + packageName); 12627 return false; 12628 } 12629 12630 if (pkg == null) { 12631 return false; 12632 } 12633 12634 if (pkg != null && pkg.applicationInfo != null) { 12635 final int appId = pkg.applicationInfo.uid; 12636 removeKeystoreDataIfNeeded(userId, appId); 12637 } 12638 12639 // Create a native library symlink only if we have native libraries 12640 // and if the native libraries are 32 bit libraries. We do not provide 12641 // this symlink for 64 bit libraries. 12642 if (pkg != null && pkg.applicationInfo.primaryCpuAbi != null && 12643 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 12644 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 12645 if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName, 12646 nativeLibPath, userId) < 0) { 12647 Slog.w(TAG, "Failed linking native library dir"); 12648 return false; 12649 } 12650 } 12651 12652 return true; 12653 } 12654 12655 /** 12656 * Remove entries from the keystore daemon. Will only remove it if the 12657 * {@code appId} is valid. 12658 */ 12659 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 12660 if (appId < 0) { 12661 return; 12662 } 12663 12664 final KeyStore keyStore = KeyStore.getInstance(); 12665 if (keyStore != null) { 12666 if (userId == UserHandle.USER_ALL) { 12667 for (final int individual : sUserManager.getUserIds()) { 12668 keyStore.clearUid(UserHandle.getUid(individual, appId)); 12669 } 12670 } else { 12671 keyStore.clearUid(UserHandle.getUid(userId, appId)); 12672 } 12673 } else { 12674 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 12675 } 12676 } 12677 12678 @Override 12679 public void deleteApplicationCacheFiles(final String packageName, 12680 final IPackageDataObserver observer) { 12681 mContext.enforceCallingOrSelfPermission( 12682 android.Manifest.permission.DELETE_CACHE_FILES, null); 12683 // Queue up an async operation since the package deletion may take a little while. 12684 final int userId = UserHandle.getCallingUserId(); 12685 mHandler.post(new Runnable() { 12686 public void run() { 12687 mHandler.removeCallbacks(this); 12688 final boolean succeded; 12689 synchronized (mInstallLock) { 12690 succeded = deleteApplicationCacheFilesLI(packageName, userId); 12691 } 12692 clearExternalStorageDataSync(packageName, userId, false); 12693 if (observer != null) { 12694 try { 12695 observer.onRemoveCompleted(packageName, succeded); 12696 } catch (RemoteException e) { 12697 Log.i(TAG, "Observer no longer exists."); 12698 } 12699 } //end if observer 12700 } //end run 12701 }); 12702 } 12703 12704 private boolean deleteApplicationCacheFilesLI(String packageName, int userId) { 12705 if (packageName == null) { 12706 Slog.w(TAG, "Attempt to delete null packageName."); 12707 return false; 12708 } 12709 PackageParser.Package p; 12710 synchronized (mPackages) { 12711 p = mPackages.get(packageName); 12712 } 12713 if (p == null) { 12714 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 12715 return false; 12716 } 12717 final ApplicationInfo applicationInfo = p.applicationInfo; 12718 if (applicationInfo == null) { 12719 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 12720 return false; 12721 } 12722 int retCode = mInstaller.deleteCacheFiles(p.volumeUuid, packageName, userId); 12723 if (retCode < 0) { 12724 Slog.w(TAG, "Couldn't remove cache files for package: " 12725 + packageName + " u" + userId); 12726 return false; 12727 } 12728 return true; 12729 } 12730 12731 @Override 12732 public void getPackageSizeInfo(final String packageName, int userHandle, 12733 final IPackageStatsObserver observer) { 12734 mContext.enforceCallingOrSelfPermission( 12735 android.Manifest.permission.GET_PACKAGE_SIZE, null); 12736 if (packageName == null) { 12737 throw new IllegalArgumentException("Attempt to get size of null packageName"); 12738 } 12739 12740 PackageStats stats = new PackageStats(packageName, userHandle); 12741 12742 /* 12743 * Queue up an async operation since the package measurement may take a 12744 * little while. 12745 */ 12746 Message msg = mHandler.obtainMessage(INIT_COPY); 12747 msg.obj = new MeasureParams(stats, observer); 12748 mHandler.sendMessage(msg); 12749 } 12750 12751 private boolean getPackageSizeInfoLI(String packageName, int userHandle, 12752 PackageStats pStats) { 12753 if (packageName == null) { 12754 Slog.w(TAG, "Attempt to get size of null packageName."); 12755 return false; 12756 } 12757 PackageParser.Package p; 12758 boolean dataOnly = false; 12759 String libDirRoot = null; 12760 String asecPath = null; 12761 PackageSetting ps = null; 12762 synchronized (mPackages) { 12763 p = mPackages.get(packageName); 12764 ps = mSettings.mPackages.get(packageName); 12765 if(p == null) { 12766 dataOnly = true; 12767 if((ps == null) || (ps.pkg == null)) { 12768 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 12769 return false; 12770 } 12771 p = ps.pkg; 12772 } 12773 if (ps != null) { 12774 libDirRoot = ps.legacyNativeLibraryPathString; 12775 } 12776 if (p != null && (isExternal(p) || p.isForwardLocked())) { 12777 String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath()); 12778 if (secureContainerId != null) { 12779 asecPath = PackageHelper.getSdFilesystem(secureContainerId); 12780 } 12781 } 12782 } 12783 String publicSrcDir = null; 12784 if(!dataOnly) { 12785 final ApplicationInfo applicationInfo = p.applicationInfo; 12786 if (applicationInfo == null) { 12787 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 12788 return false; 12789 } 12790 if (p.isForwardLocked()) { 12791 publicSrcDir = applicationInfo.getBaseResourcePath(); 12792 } 12793 } 12794 // TODO: extend to measure size of split APKs 12795 // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree, 12796 // not just the first level. 12797 // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not 12798 // just the primary. 12799 String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps)); 12800 int res = mInstaller.getSizeInfo(p.volumeUuid, packageName, userHandle, p.baseCodePath, 12801 libDirRoot, publicSrcDir, asecPath, dexCodeInstructionSets, pStats); 12802 if (res < 0) { 12803 return false; 12804 } 12805 12806 // Fix-up for forward-locked applications in ASEC containers. 12807 if (!isExternal(p)) { 12808 pStats.codeSize += pStats.externalCodeSize; 12809 pStats.externalCodeSize = 0L; 12810 } 12811 12812 return true; 12813 } 12814 12815 12816 @Override 12817 public void addPackageToPreferred(String packageName) { 12818 Slog.w(TAG, "addPackageToPreferred: this is now a no-op"); 12819 } 12820 12821 @Override 12822 public void removePackageFromPreferred(String packageName) { 12823 Slog.w(TAG, "removePackageFromPreferred: this is now a no-op"); 12824 } 12825 12826 @Override 12827 public List<PackageInfo> getPreferredPackages(int flags) { 12828 return new ArrayList<PackageInfo>(); 12829 } 12830 12831 private int getUidTargetSdkVersionLockedLPr(int uid) { 12832 Object obj = mSettings.getUserIdLPr(uid); 12833 if (obj instanceof SharedUserSetting) { 12834 final SharedUserSetting sus = (SharedUserSetting) obj; 12835 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 12836 final Iterator<PackageSetting> it = sus.packages.iterator(); 12837 while (it.hasNext()) { 12838 final PackageSetting ps = it.next(); 12839 if (ps.pkg != null) { 12840 int v = ps.pkg.applicationInfo.targetSdkVersion; 12841 if (v < vers) vers = v; 12842 } 12843 } 12844 return vers; 12845 } else if (obj instanceof PackageSetting) { 12846 final PackageSetting ps = (PackageSetting) obj; 12847 if (ps.pkg != null) { 12848 return ps.pkg.applicationInfo.targetSdkVersion; 12849 } 12850 } 12851 return Build.VERSION_CODES.CUR_DEVELOPMENT; 12852 } 12853 12854 @Override 12855 public void addPreferredActivity(IntentFilter filter, int match, 12856 ComponentName[] set, ComponentName activity, int userId) { 12857 addPreferredActivityInternal(filter, match, set, activity, true, userId, 12858 "Adding preferred"); 12859 } 12860 12861 private void addPreferredActivityInternal(IntentFilter filter, int match, 12862 ComponentName[] set, ComponentName activity, boolean always, int userId, 12863 String opname) { 12864 // writer 12865 int callingUid = Binder.getCallingUid(); 12866 enforceCrossUserPermission(callingUid, userId, true, false, "add preferred activity"); 12867 if (filter.countActions() == 0) { 12868 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 12869 return; 12870 } 12871 synchronized (mPackages) { 12872 if (mContext.checkCallingOrSelfPermission( 12873 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 12874 != PackageManager.PERMISSION_GRANTED) { 12875 if (getUidTargetSdkVersionLockedLPr(callingUid) 12876 < Build.VERSION_CODES.FROYO) { 12877 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 12878 + callingUid); 12879 return; 12880 } 12881 mContext.enforceCallingOrSelfPermission( 12882 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 12883 } 12884 12885 PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId); 12886 Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user " 12887 + userId + ":"); 12888 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 12889 pir.addFilter(new PreferredActivity(filter, match, set, activity, always)); 12890 scheduleWritePackageRestrictionsLocked(userId); 12891 } 12892 } 12893 12894 @Override 12895 public void replacePreferredActivity(IntentFilter filter, int match, 12896 ComponentName[] set, ComponentName activity, int userId) { 12897 if (filter.countActions() != 1) { 12898 throw new IllegalArgumentException( 12899 "replacePreferredActivity expects filter to have only 1 action."); 12900 } 12901 if (filter.countDataAuthorities() != 0 12902 || filter.countDataPaths() != 0 12903 || filter.countDataSchemes() > 1 12904 || filter.countDataTypes() != 0) { 12905 throw new IllegalArgumentException( 12906 "replacePreferredActivity expects filter to have no data authorities, " + 12907 "paths, or types; and at most one scheme."); 12908 } 12909 12910 final int callingUid = Binder.getCallingUid(); 12911 enforceCrossUserPermission(callingUid, userId, true, false, "replace preferred activity"); 12912 synchronized (mPackages) { 12913 if (mContext.checkCallingOrSelfPermission( 12914 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 12915 != PackageManager.PERMISSION_GRANTED) { 12916 if (getUidTargetSdkVersionLockedLPr(callingUid) 12917 < Build.VERSION_CODES.FROYO) { 12918 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 12919 + Binder.getCallingUid()); 12920 return; 12921 } 12922 mContext.enforceCallingOrSelfPermission( 12923 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 12924 } 12925 12926 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 12927 if (pir != null) { 12928 // Get all of the existing entries that exactly match this filter. 12929 ArrayList<PreferredActivity> existing = pir.findFilters(filter); 12930 if (existing != null && existing.size() == 1) { 12931 PreferredActivity cur = existing.get(0); 12932 if (DEBUG_PREFERRED) { 12933 Slog.i(TAG, "Checking replace of preferred:"); 12934 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 12935 if (!cur.mPref.mAlways) { 12936 Slog.i(TAG, " -- CUR; not mAlways!"); 12937 } else { 12938 Slog.i(TAG, " -- CUR: mMatch=" + cur.mPref.mMatch); 12939 Slog.i(TAG, " -- CUR: mSet=" 12940 + Arrays.toString(cur.mPref.mSetComponents)); 12941 Slog.i(TAG, " -- CUR: mComponent=" + cur.mPref.mShortComponent); 12942 Slog.i(TAG, " -- NEW: mMatch=" 12943 + (match&IntentFilter.MATCH_CATEGORY_MASK)); 12944 Slog.i(TAG, " -- CUR: mSet=" + Arrays.toString(set)); 12945 Slog.i(TAG, " -- CUR: mComponent=" + activity.flattenToShortString()); 12946 } 12947 } 12948 if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity) 12949 && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK) 12950 && cur.mPref.sameSet(set)) { 12951 // Setting the preferred activity to what it happens to be already 12952 if (DEBUG_PREFERRED) { 12953 Slog.i(TAG, "Replacing with same preferred activity " 12954 + cur.mPref.mShortComponent + " for user " 12955 + userId + ":"); 12956 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 12957 } 12958 return; 12959 } 12960 } 12961 12962 if (existing != null) { 12963 if (DEBUG_PREFERRED) { 12964 Slog.i(TAG, existing.size() + " existing preferred matches for:"); 12965 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 12966 } 12967 for (int i = 0; i < existing.size(); i++) { 12968 PreferredActivity pa = existing.get(i); 12969 if (DEBUG_PREFERRED) { 12970 Slog.i(TAG, "Removing existing preferred activity " 12971 + pa.mPref.mComponent + ":"); 12972 pa.dump(new LogPrinter(Log.INFO, TAG), " "); 12973 } 12974 pir.removeFilter(pa); 12975 } 12976 } 12977 } 12978 addPreferredActivityInternal(filter, match, set, activity, true, userId, 12979 "Replacing preferred"); 12980 } 12981 } 12982 12983 @Override 12984 public void clearPackagePreferredActivities(String packageName) { 12985 final int uid = Binder.getCallingUid(); 12986 // writer 12987 synchronized (mPackages) { 12988 PackageParser.Package pkg = mPackages.get(packageName); 12989 if (pkg == null || pkg.applicationInfo.uid != uid) { 12990 if (mContext.checkCallingOrSelfPermission( 12991 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 12992 != PackageManager.PERMISSION_GRANTED) { 12993 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 12994 < Build.VERSION_CODES.FROYO) { 12995 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 12996 + Binder.getCallingUid()); 12997 return; 12998 } 12999 mContext.enforceCallingOrSelfPermission( 13000 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 13001 } 13002 } 13003 13004 int user = UserHandle.getCallingUserId(); 13005 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 13006 scheduleWritePackageRestrictionsLocked(user); 13007 } 13008 } 13009 } 13010 13011 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 13012 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 13013 ArrayList<PreferredActivity> removed = null; 13014 boolean changed = false; 13015 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 13016 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 13017 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 13018 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 13019 continue; 13020 } 13021 Iterator<PreferredActivity> it = pir.filterIterator(); 13022 while (it.hasNext()) { 13023 PreferredActivity pa = it.next(); 13024 // Mark entry for removal only if it matches the package name 13025 // and the entry is of type "always". 13026 if (packageName == null || 13027 (pa.mPref.mComponent.getPackageName().equals(packageName) 13028 && pa.mPref.mAlways)) { 13029 if (removed == null) { 13030 removed = new ArrayList<PreferredActivity>(); 13031 } 13032 removed.add(pa); 13033 } 13034 } 13035 if (removed != null) { 13036 for (int j=0; j<removed.size(); j++) { 13037 PreferredActivity pa = removed.get(j); 13038 pir.removeFilter(pa); 13039 } 13040 changed = true; 13041 } 13042 } 13043 return changed; 13044 } 13045 13046 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 13047 void clearIntentFilterVerificationsLPw(String packageName, int userId) { 13048 if (userId == UserHandle.USER_ALL) { 13049 if (mSettings.removeIntentFilterVerificationLPw(packageName, 13050 sUserManager.getUserIds())) { 13051 for (int oneUserId : sUserManager.getUserIds()) { 13052 scheduleWritePackageRestrictionsLocked(oneUserId); 13053 } 13054 } 13055 } else { 13056 if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) { 13057 scheduleWritePackageRestrictionsLocked(userId); 13058 } 13059 } 13060 } 13061 13062 13063 void clearDefaultBrowserIfNeeded(String packageName) { 13064 for (int oneUserId : sUserManager.getUserIds()) { 13065 String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId); 13066 if (TextUtils.isEmpty(defaultBrowserPackageName)) continue; 13067 if (packageName.equals(defaultBrowserPackageName)) { 13068 setDefaultBrowserPackageName(null, oneUserId); 13069 } 13070 } 13071 } 13072 13073 @Override 13074 public void resetPreferredActivities(int userId) { 13075 /* TODO: Actually use userId. Why is it being passed in? */ 13076 mContext.enforceCallingOrSelfPermission( 13077 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 13078 // writer 13079 synchronized (mPackages) { 13080 int user = UserHandle.getCallingUserId(); 13081 clearPackagePreferredActivitiesLPw(null, user); 13082 mSettings.readDefaultPreferredAppsLPw(this, user); 13083 scheduleWritePackageRestrictionsLocked(user); 13084 } 13085 } 13086 13087 @Override 13088 public int getPreferredActivities(List<IntentFilter> outFilters, 13089 List<ComponentName> outActivities, String packageName) { 13090 13091 int num = 0; 13092 final int userId = UserHandle.getCallingUserId(); 13093 // reader 13094 synchronized (mPackages) { 13095 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 13096 if (pir != null) { 13097 final Iterator<PreferredActivity> it = pir.filterIterator(); 13098 while (it.hasNext()) { 13099 final PreferredActivity pa = it.next(); 13100 if (packageName == null 13101 || (pa.mPref.mComponent.getPackageName().equals(packageName) 13102 && pa.mPref.mAlways)) { 13103 if (outFilters != null) { 13104 outFilters.add(new IntentFilter(pa)); 13105 } 13106 if (outActivities != null) { 13107 outActivities.add(pa.mPref.mComponent); 13108 } 13109 } 13110 } 13111 } 13112 } 13113 13114 return num; 13115 } 13116 13117 @Override 13118 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 13119 int userId) { 13120 int callingUid = Binder.getCallingUid(); 13121 if (callingUid != Process.SYSTEM_UID) { 13122 throw new SecurityException( 13123 "addPersistentPreferredActivity can only be run by the system"); 13124 } 13125 if (filter.countActions() == 0) { 13126 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 13127 return; 13128 } 13129 synchronized (mPackages) { 13130 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 13131 " :"); 13132 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 13133 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 13134 new PersistentPreferredActivity(filter, activity)); 13135 scheduleWritePackageRestrictionsLocked(userId); 13136 } 13137 } 13138 13139 @Override 13140 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 13141 int callingUid = Binder.getCallingUid(); 13142 if (callingUid != Process.SYSTEM_UID) { 13143 throw new SecurityException( 13144 "clearPackagePersistentPreferredActivities can only be run by the system"); 13145 } 13146 ArrayList<PersistentPreferredActivity> removed = null; 13147 boolean changed = false; 13148 synchronized (mPackages) { 13149 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 13150 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 13151 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 13152 .valueAt(i); 13153 if (userId != thisUserId) { 13154 continue; 13155 } 13156 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 13157 while (it.hasNext()) { 13158 PersistentPreferredActivity ppa = it.next(); 13159 // Mark entry for removal only if it matches the package name. 13160 if (ppa.mComponent.getPackageName().equals(packageName)) { 13161 if (removed == null) { 13162 removed = new ArrayList<PersistentPreferredActivity>(); 13163 } 13164 removed.add(ppa); 13165 } 13166 } 13167 if (removed != null) { 13168 for (int j=0; j<removed.size(); j++) { 13169 PersistentPreferredActivity ppa = removed.get(j); 13170 ppir.removeFilter(ppa); 13171 } 13172 changed = true; 13173 } 13174 } 13175 13176 if (changed) { 13177 scheduleWritePackageRestrictionsLocked(userId); 13178 } 13179 } 13180 } 13181 13182 /** 13183 * Non-Binder method, support for the backup/restore mechanism: write the 13184 * full set of preferred activities in its canonical XML format. Returns true 13185 * on success; false otherwise. 13186 */ 13187 @Override 13188 public byte[] getPreferredActivityBackup(int userId) { 13189 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 13190 throw new SecurityException("Only the system may call getPreferredActivityBackup()"); 13191 } 13192 13193 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 13194 try { 13195 final XmlSerializer serializer = new FastXmlSerializer(); 13196 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 13197 serializer.startDocument(null, true); 13198 serializer.startTag(null, TAG_PREFERRED_BACKUP); 13199 13200 synchronized (mPackages) { 13201 mSettings.writePreferredActivitiesLPr(serializer, userId, true); 13202 } 13203 13204 serializer.endTag(null, TAG_PREFERRED_BACKUP); 13205 serializer.endDocument(); 13206 serializer.flush(); 13207 } catch (Exception e) { 13208 if (DEBUG_BACKUP) { 13209 Slog.e(TAG, "Unable to write preferred activities for backup", e); 13210 } 13211 return null; 13212 } 13213 13214 return dataStream.toByteArray(); 13215 } 13216 13217 @Override 13218 public void restorePreferredActivities(byte[] backup, int userId) { 13219 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 13220 throw new SecurityException("Only the system may call restorePreferredActivities()"); 13221 } 13222 13223 try { 13224 final XmlPullParser parser = Xml.newPullParser(); 13225 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 13226 13227 int type; 13228 while ((type = parser.next()) != XmlPullParser.START_TAG 13229 && type != XmlPullParser.END_DOCUMENT) { 13230 } 13231 if (type != XmlPullParser.START_TAG) { 13232 // oops didn't find a start tag?! 13233 if (DEBUG_BACKUP) { 13234 Slog.e(TAG, "Didn't find start tag during restore"); 13235 } 13236 return; 13237 } 13238 13239 // this is supposed to be TAG_PREFERRED_BACKUP 13240 if (!TAG_PREFERRED_BACKUP.equals(parser.getName())) { 13241 if (DEBUG_BACKUP) { 13242 Slog.e(TAG, "Found unexpected tag " + parser.getName()); 13243 } 13244 return; 13245 } 13246 13247 // skip interfering stuff, then we're aligned with the backing implementation 13248 while ((type = parser.next()) == XmlPullParser.TEXT) { } 13249 synchronized (mPackages) { 13250 mSettings.readPreferredActivitiesLPw(parser, userId); 13251 } 13252 } catch (Exception e) { 13253 if (DEBUG_BACKUP) { 13254 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 13255 } 13256 } 13257 } 13258 13259 @Override 13260 public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage, 13261 int sourceUserId, int targetUserId, int flags) { 13262 mContext.enforceCallingOrSelfPermission( 13263 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 13264 int callingUid = Binder.getCallingUid(); 13265 enforceOwnerRights(ownerPackage, callingUid); 13266 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 13267 if (intentFilter.countActions() == 0) { 13268 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 13269 return; 13270 } 13271 synchronized (mPackages) { 13272 CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter, 13273 ownerPackage, targetUserId, flags); 13274 CrossProfileIntentResolver resolver = 13275 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 13276 ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter); 13277 // We have all those whose filter is equal. Now checking if the rest is equal as well. 13278 if (existing != null) { 13279 int size = existing.size(); 13280 for (int i = 0; i < size; i++) { 13281 if (newFilter.equalsIgnoreFilter(existing.get(i))) { 13282 return; 13283 } 13284 } 13285 } 13286 resolver.addFilter(newFilter); 13287 scheduleWritePackageRestrictionsLocked(sourceUserId); 13288 } 13289 } 13290 13291 @Override 13292 public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) { 13293 mContext.enforceCallingOrSelfPermission( 13294 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 13295 int callingUid = Binder.getCallingUid(); 13296 enforceOwnerRights(ownerPackage, callingUid); 13297 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 13298 synchronized (mPackages) { 13299 CrossProfileIntentResolver resolver = 13300 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 13301 ArraySet<CrossProfileIntentFilter> set = 13302 new ArraySet<CrossProfileIntentFilter>(resolver.filterSet()); 13303 for (CrossProfileIntentFilter filter : set) { 13304 if (filter.getOwnerPackage().equals(ownerPackage)) { 13305 resolver.removeFilter(filter); 13306 } 13307 } 13308 scheduleWritePackageRestrictionsLocked(sourceUserId); 13309 } 13310 } 13311 13312 // Enforcing that callingUid is owning pkg on userId 13313 private void enforceOwnerRights(String pkg, int callingUid) { 13314 // The system owns everything. 13315 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 13316 return; 13317 } 13318 int callingUserId = UserHandle.getUserId(callingUid); 13319 PackageInfo pi = getPackageInfo(pkg, 0, callingUserId); 13320 if (pi == null) { 13321 throw new IllegalArgumentException("Unknown package " + pkg + " on user " 13322 + callingUserId); 13323 } 13324 if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) { 13325 throw new SecurityException("Calling uid " + callingUid 13326 + " does not own package " + pkg); 13327 } 13328 } 13329 13330 @Override 13331 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 13332 Intent intent = new Intent(Intent.ACTION_MAIN); 13333 intent.addCategory(Intent.CATEGORY_HOME); 13334 13335 final int callingUserId = UserHandle.getCallingUserId(); 13336 List<ResolveInfo> list = queryIntentActivities(intent, null, 13337 PackageManager.GET_META_DATA, callingUserId); 13338 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 13339 true, false, false, callingUserId); 13340 13341 allHomeCandidates.clear(); 13342 if (list != null) { 13343 for (ResolveInfo ri : list) { 13344 allHomeCandidates.add(ri); 13345 } 13346 } 13347 return (preferred == null || preferred.activityInfo == null) 13348 ? null 13349 : new ComponentName(preferred.activityInfo.packageName, 13350 preferred.activityInfo.name); 13351 } 13352 13353 @Override 13354 public void setApplicationEnabledSetting(String appPackageName, 13355 int newState, int flags, int userId, String callingPackage) { 13356 if (!sUserManager.exists(userId)) return; 13357 if (callingPackage == null) { 13358 callingPackage = Integer.toString(Binder.getCallingUid()); 13359 } 13360 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 13361 } 13362 13363 @Override 13364 public void setComponentEnabledSetting(ComponentName componentName, 13365 int newState, int flags, int userId) { 13366 if (!sUserManager.exists(userId)) return; 13367 setEnabledSetting(componentName.getPackageName(), 13368 componentName.getClassName(), newState, flags, userId, null); 13369 } 13370 13371 private void setEnabledSetting(final String packageName, String className, int newState, 13372 final int flags, int userId, String callingPackage) { 13373 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 13374 || newState == COMPONENT_ENABLED_STATE_ENABLED 13375 || newState == COMPONENT_ENABLED_STATE_DISABLED 13376 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 13377 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 13378 throw new IllegalArgumentException("Invalid new component state: " 13379 + newState); 13380 } 13381 PackageSetting pkgSetting; 13382 final int uid = Binder.getCallingUid(); 13383 final int permission = mContext.checkCallingOrSelfPermission( 13384 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 13385 enforceCrossUserPermission(uid, userId, false, true, "set enabled"); 13386 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 13387 boolean sendNow = false; 13388 boolean isApp = (className == null); 13389 String componentName = isApp ? packageName : className; 13390 int packageUid = -1; 13391 ArrayList<String> components; 13392 13393 // writer 13394 synchronized (mPackages) { 13395 pkgSetting = mSettings.mPackages.get(packageName); 13396 if (pkgSetting == null) { 13397 if (className == null) { 13398 throw new IllegalArgumentException( 13399 "Unknown package: " + packageName); 13400 } 13401 throw new IllegalArgumentException( 13402 "Unknown component: " + packageName 13403 + "/" + className); 13404 } 13405 // Allow root and verify that userId is not being specified by a different user 13406 if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) { 13407 throw new SecurityException( 13408 "Permission Denial: attempt to change component state from pid=" 13409 + Binder.getCallingPid() 13410 + ", uid=" + uid + ", package uid=" + pkgSetting.appId); 13411 } 13412 if (className == null) { 13413 // We're dealing with an application/package level state change 13414 if (pkgSetting.getEnabled(userId) == newState) { 13415 // Nothing to do 13416 return; 13417 } 13418 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 13419 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 13420 // Don't care about who enables an app. 13421 callingPackage = null; 13422 } 13423 pkgSetting.setEnabled(newState, userId, callingPackage); 13424 // pkgSetting.pkg.mSetEnabled = newState; 13425 } else { 13426 // We're dealing with a component level state change 13427 // First, verify that this is a valid class name. 13428 PackageParser.Package pkg = pkgSetting.pkg; 13429 if (pkg == null || !pkg.hasComponentClassName(className)) { 13430 if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) { 13431 throw new IllegalArgumentException("Component class " + className 13432 + " does not exist in " + packageName); 13433 } else { 13434 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 13435 + className + " does not exist in " + packageName); 13436 } 13437 } 13438 switch (newState) { 13439 case COMPONENT_ENABLED_STATE_ENABLED: 13440 if (!pkgSetting.enableComponentLPw(className, userId)) { 13441 return; 13442 } 13443 break; 13444 case COMPONENT_ENABLED_STATE_DISABLED: 13445 if (!pkgSetting.disableComponentLPw(className, userId)) { 13446 return; 13447 } 13448 break; 13449 case COMPONENT_ENABLED_STATE_DEFAULT: 13450 if (!pkgSetting.restoreComponentLPw(className, userId)) { 13451 return; 13452 } 13453 break; 13454 default: 13455 Slog.e(TAG, "Invalid new component state: " + newState); 13456 return; 13457 } 13458 } 13459 scheduleWritePackageRestrictionsLocked(userId); 13460 components = mPendingBroadcasts.get(userId, packageName); 13461 final boolean newPackage = components == null; 13462 if (newPackage) { 13463 components = new ArrayList<String>(); 13464 } 13465 if (!components.contains(componentName)) { 13466 components.add(componentName); 13467 } 13468 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 13469 sendNow = true; 13470 // Purge entry from pending broadcast list if another one exists already 13471 // since we are sending one right away. 13472 mPendingBroadcasts.remove(userId, packageName); 13473 } else { 13474 if (newPackage) { 13475 mPendingBroadcasts.put(userId, packageName, components); 13476 } 13477 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 13478 // Schedule a message 13479 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 13480 } 13481 } 13482 } 13483 13484 long callingId = Binder.clearCallingIdentity(); 13485 try { 13486 if (sendNow) { 13487 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 13488 sendPackageChangedBroadcast(packageName, 13489 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 13490 } 13491 } finally { 13492 Binder.restoreCallingIdentity(callingId); 13493 } 13494 } 13495 13496 private void sendPackageChangedBroadcast(String packageName, 13497 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 13498 if (DEBUG_INSTALL) 13499 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 13500 + componentNames); 13501 Bundle extras = new Bundle(4); 13502 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 13503 String nameList[] = new String[componentNames.size()]; 13504 componentNames.toArray(nameList); 13505 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 13506 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 13507 extras.putInt(Intent.EXTRA_UID, packageUid); 13508 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, null, null, 13509 new int[] {UserHandle.getUserId(packageUid)}); 13510 } 13511 13512 @Override 13513 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 13514 if (!sUserManager.exists(userId)) return; 13515 final int uid = Binder.getCallingUid(); 13516 final int permission = mContext.checkCallingOrSelfPermission( 13517 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 13518 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 13519 enforceCrossUserPermission(uid, userId, true, true, "stop package"); 13520 // writer 13521 synchronized (mPackages) { 13522 if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped, 13523 allowedByPermission, uid, userId)) { 13524 scheduleWritePackageRestrictionsLocked(userId); 13525 } 13526 } 13527 } 13528 13529 @Override 13530 public String getInstallerPackageName(String packageName) { 13531 // reader 13532 synchronized (mPackages) { 13533 return mSettings.getInstallerPackageNameLPr(packageName); 13534 } 13535 } 13536 13537 @Override 13538 public int getApplicationEnabledSetting(String packageName, int userId) { 13539 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 13540 int uid = Binder.getCallingUid(); 13541 enforceCrossUserPermission(uid, userId, false, false, "get enabled"); 13542 // reader 13543 synchronized (mPackages) { 13544 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 13545 } 13546 } 13547 13548 @Override 13549 public int getComponentEnabledSetting(ComponentName componentName, int userId) { 13550 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 13551 int uid = Binder.getCallingUid(); 13552 enforceCrossUserPermission(uid, userId, false, false, "get component enabled"); 13553 // reader 13554 synchronized (mPackages) { 13555 return mSettings.getComponentEnabledSettingLPr(componentName, userId); 13556 } 13557 } 13558 13559 @Override 13560 public void enterSafeMode() { 13561 enforceSystemOrRoot("Only the system can request entering safe mode"); 13562 13563 if (!mSystemReady) { 13564 mSafeMode = true; 13565 } 13566 } 13567 13568 @Override 13569 public void systemReady() { 13570 mSystemReady = true; 13571 13572 // Read the compatibilty setting when the system is ready. 13573 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 13574 mContext.getContentResolver(), 13575 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 13576 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 13577 if (DEBUG_SETTINGS) { 13578 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 13579 } 13580 13581 synchronized (mPackages) { 13582 // Verify that all of the preferred activity components actually 13583 // exist. It is possible for applications to be updated and at 13584 // that point remove a previously declared activity component that 13585 // had been set as a preferred activity. We try to clean this up 13586 // the next time we encounter that preferred activity, but it is 13587 // possible for the user flow to never be able to return to that 13588 // situation so here we do a sanity check to make sure we haven't 13589 // left any junk around. 13590 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 13591 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 13592 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 13593 removed.clear(); 13594 for (PreferredActivity pa : pir.filterSet()) { 13595 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 13596 removed.add(pa); 13597 } 13598 } 13599 if (removed.size() > 0) { 13600 for (int r=0; r<removed.size(); r++) { 13601 PreferredActivity pa = removed.get(r); 13602 Slog.w(TAG, "Removing dangling preferred activity: " 13603 + pa.mPref.mComponent); 13604 pir.removeFilter(pa); 13605 } 13606 mSettings.writePackageRestrictionsLPr( 13607 mSettings.mPreferredActivities.keyAt(i)); 13608 } 13609 } 13610 } 13611 sUserManager.systemReady(); 13612 13613 // Kick off any messages waiting for system ready 13614 if (mPostSystemReadyMessages != null) { 13615 for (Message msg : mPostSystemReadyMessages) { 13616 msg.sendToTarget(); 13617 } 13618 mPostSystemReadyMessages = null; 13619 } 13620 13621 // Watch for external volumes that come and go over time 13622 final StorageManager storage = mContext.getSystemService(StorageManager.class); 13623 storage.registerListener(mStorageListener); 13624 13625 mInstallerService.systemReady(); 13626 mPackageDexOptimizer.systemReady(); 13627 } 13628 13629 @Override 13630 public boolean isSafeMode() { 13631 return mSafeMode; 13632 } 13633 13634 @Override 13635 public boolean hasSystemUidErrors() { 13636 return mHasSystemUidErrors; 13637 } 13638 13639 static String arrayToString(int[] array) { 13640 StringBuffer buf = new StringBuffer(128); 13641 buf.append('['); 13642 if (array != null) { 13643 for (int i=0; i<array.length; i++) { 13644 if (i > 0) buf.append(", "); 13645 buf.append(array[i]); 13646 } 13647 } 13648 buf.append(']'); 13649 return buf.toString(); 13650 } 13651 13652 static class DumpState { 13653 public static final int DUMP_LIBS = 1 << 0; 13654 public static final int DUMP_FEATURES = 1 << 1; 13655 public static final int DUMP_RESOLVERS = 1 << 2; 13656 public static final int DUMP_PERMISSIONS = 1 << 3; 13657 public static final int DUMP_PACKAGES = 1 << 4; 13658 public static final int DUMP_SHARED_USERS = 1 << 5; 13659 public static final int DUMP_MESSAGES = 1 << 6; 13660 public static final int DUMP_PROVIDERS = 1 << 7; 13661 public static final int DUMP_VERIFIERS = 1 << 8; 13662 public static final int DUMP_PREFERRED = 1 << 9; 13663 public static final int DUMP_PREFERRED_XML = 1 << 10; 13664 public static final int DUMP_KEYSETS = 1 << 11; 13665 public static final int DUMP_VERSION = 1 << 12; 13666 public static final int DUMP_INSTALLS = 1 << 13; 13667 public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 14; 13668 public static final int DUMP_DOMAIN_PREFERRED = 1 << 15; 13669 13670 public static final int OPTION_SHOW_FILTERS = 1 << 0; 13671 13672 private int mTypes; 13673 13674 private int mOptions; 13675 13676 private boolean mTitlePrinted; 13677 13678 private SharedUserSetting mSharedUser; 13679 13680 public boolean isDumping(int type) { 13681 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 13682 return true; 13683 } 13684 13685 return (mTypes & type) != 0; 13686 } 13687 13688 public void setDump(int type) { 13689 mTypes |= type; 13690 } 13691 13692 public boolean isOptionEnabled(int option) { 13693 return (mOptions & option) != 0; 13694 } 13695 13696 public void setOptionEnabled(int option) { 13697 mOptions |= option; 13698 } 13699 13700 public boolean onTitlePrinted() { 13701 final boolean printed = mTitlePrinted; 13702 mTitlePrinted = true; 13703 return printed; 13704 } 13705 13706 public boolean getTitlePrinted() { 13707 return mTitlePrinted; 13708 } 13709 13710 public void setTitlePrinted(boolean enabled) { 13711 mTitlePrinted = enabled; 13712 } 13713 13714 public SharedUserSetting getSharedUser() { 13715 return mSharedUser; 13716 } 13717 13718 public void setSharedUser(SharedUserSetting user) { 13719 mSharedUser = user; 13720 } 13721 } 13722 13723 @Override 13724 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 13725 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 13726 != PackageManager.PERMISSION_GRANTED) { 13727 pw.println("Permission Denial: can't dump ActivityManager from from pid=" 13728 + Binder.getCallingPid() 13729 + ", uid=" + Binder.getCallingUid() 13730 + " without permission " 13731 + android.Manifest.permission.DUMP); 13732 return; 13733 } 13734 13735 DumpState dumpState = new DumpState(); 13736 boolean fullPreferred = false; 13737 boolean checkin = false; 13738 13739 String packageName = null; 13740 13741 int opti = 0; 13742 while (opti < args.length) { 13743 String opt = args[opti]; 13744 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 13745 break; 13746 } 13747 opti++; 13748 13749 if ("-a".equals(opt)) { 13750 // Right now we only know how to print all. 13751 } else if ("-h".equals(opt)) { 13752 pw.println("Package manager dump options:"); 13753 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 13754 pw.println(" --checkin: dump for a checkin"); 13755 pw.println(" -f: print details of intent filters"); 13756 pw.println(" -h: print this help"); 13757 pw.println(" cmd may be one of:"); 13758 pw.println(" l[ibraries]: list known shared libraries"); 13759 pw.println(" f[ibraries]: list device features"); 13760 pw.println(" k[eysets]: print known keysets"); 13761 pw.println(" r[esolvers]: dump intent resolvers"); 13762 pw.println(" perm[issions]: dump permissions"); 13763 pw.println(" pref[erred]: print preferred package settings"); 13764 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 13765 pw.println(" prov[iders]: dump content providers"); 13766 pw.println(" p[ackages]: dump installed packages"); 13767 pw.println(" s[hared-users]: dump shared user IDs"); 13768 pw.println(" m[essages]: print collected runtime messages"); 13769 pw.println(" v[erifiers]: print package verifier info"); 13770 pw.println(" version: print database version info"); 13771 pw.println(" write: write current settings now"); 13772 pw.println(" <package.name>: info about given package"); 13773 pw.println(" installs: details about install sessions"); 13774 pw.println(" d[omain-preferred-apps]: print domains preferred apps"); 13775 pw.println(" i[ntent-filter-verifiers]|ifv: print intent filter verifier info"); 13776 return; 13777 } else if ("--checkin".equals(opt)) { 13778 checkin = true; 13779 } else if ("-f".equals(opt)) { 13780 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 13781 } else { 13782 pw.println("Unknown argument: " + opt + "; use -h for help"); 13783 } 13784 } 13785 13786 // Is the caller requesting to dump a particular piece of data? 13787 if (opti < args.length) { 13788 String cmd = args[opti]; 13789 opti++; 13790 // Is this a package name? 13791 if ("android".equals(cmd) || cmd.contains(".")) { 13792 packageName = cmd; 13793 // When dumping a single package, we always dump all of its 13794 // filter information since the amount of data will be reasonable. 13795 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 13796 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 13797 dumpState.setDump(DumpState.DUMP_LIBS); 13798 } else if ("f".equals(cmd) || "features".equals(cmd)) { 13799 dumpState.setDump(DumpState.DUMP_FEATURES); 13800 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 13801 dumpState.setDump(DumpState.DUMP_RESOLVERS); 13802 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 13803 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 13804 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 13805 dumpState.setDump(DumpState.DUMP_PREFERRED); 13806 } else if ("preferred-xml".equals(cmd)) { 13807 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 13808 if (opti < args.length && "--full".equals(args[opti])) { 13809 fullPreferred = true; 13810 opti++; 13811 } 13812 } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) { 13813 dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED); 13814 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 13815 dumpState.setDump(DumpState.DUMP_PACKAGES); 13816 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 13817 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 13818 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 13819 dumpState.setDump(DumpState.DUMP_PROVIDERS); 13820 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 13821 dumpState.setDump(DumpState.DUMP_MESSAGES); 13822 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 13823 dumpState.setDump(DumpState.DUMP_VERIFIERS); 13824 } else if ("i".equals(cmd) || "ifv".equals(cmd) 13825 || "intent-filter-verifiers".equals(cmd)) { 13826 dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS); 13827 } else if ("version".equals(cmd)) { 13828 dumpState.setDump(DumpState.DUMP_VERSION); 13829 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 13830 dumpState.setDump(DumpState.DUMP_KEYSETS); 13831 } else if ("installs".equals(cmd)) { 13832 dumpState.setDump(DumpState.DUMP_INSTALLS); 13833 } else if ("write".equals(cmd)) { 13834 synchronized (mPackages) { 13835 mSettings.writeLPr(); 13836 pw.println("Settings written."); 13837 return; 13838 } 13839 } 13840 } 13841 13842 if (checkin) { 13843 pw.println("vers,1"); 13844 } 13845 13846 // reader 13847 synchronized (mPackages) { 13848 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 13849 if (!checkin) { 13850 if (dumpState.onTitlePrinted()) 13851 pw.println(); 13852 pw.println("Database versions:"); 13853 pw.print(" SDK Version:"); 13854 pw.print(" internal="); 13855 pw.print(mSettings.mInternalSdkPlatform); 13856 pw.print(" external="); 13857 pw.println(mSettings.mExternalSdkPlatform); 13858 pw.print(" DB Version:"); 13859 pw.print(" internal="); 13860 pw.print(mSettings.mInternalDatabaseVersion); 13861 pw.print(" external="); 13862 pw.println(mSettings.mExternalDatabaseVersion); 13863 } 13864 } 13865 13866 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 13867 if (!checkin) { 13868 if (dumpState.onTitlePrinted()) 13869 pw.println(); 13870 pw.println("Verifiers:"); 13871 pw.print(" Required: "); 13872 pw.print(mRequiredVerifierPackage); 13873 pw.print(" (uid="); 13874 pw.print(getPackageUid(mRequiredVerifierPackage, 0)); 13875 pw.println(")"); 13876 } else if (mRequiredVerifierPackage != null) { 13877 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 13878 pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0)); 13879 } 13880 } 13881 13882 if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) && 13883 packageName == null) { 13884 if (mIntentFilterVerifierComponent != null) { 13885 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName(); 13886 if (!checkin) { 13887 if (dumpState.onTitlePrinted()) 13888 pw.println(); 13889 pw.println("Intent Filter Verifier:"); 13890 pw.print(" Using: "); 13891 pw.print(verifierPackageName); 13892 pw.print(" (uid="); 13893 pw.print(getPackageUid(verifierPackageName, 0)); 13894 pw.println(")"); 13895 } else if (verifierPackageName != null) { 13896 pw.print("ifv,"); pw.print(verifierPackageName); 13897 pw.print(","); pw.println(getPackageUid(verifierPackageName, 0)); 13898 } 13899 } else { 13900 pw.println(); 13901 pw.println("No Intent Filter Verifier available!"); 13902 } 13903 } 13904 13905 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 13906 boolean printedHeader = false; 13907 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 13908 while (it.hasNext()) { 13909 String name = it.next(); 13910 SharedLibraryEntry ent = mSharedLibraries.get(name); 13911 if (!checkin) { 13912 if (!printedHeader) { 13913 if (dumpState.onTitlePrinted()) 13914 pw.println(); 13915 pw.println("Libraries:"); 13916 printedHeader = true; 13917 } 13918 pw.print(" "); 13919 } else { 13920 pw.print("lib,"); 13921 } 13922 pw.print(name); 13923 if (!checkin) { 13924 pw.print(" -> "); 13925 } 13926 if (ent.path != null) { 13927 if (!checkin) { 13928 pw.print("(jar) "); 13929 pw.print(ent.path); 13930 } else { 13931 pw.print(",jar,"); 13932 pw.print(ent.path); 13933 } 13934 } else { 13935 if (!checkin) { 13936 pw.print("(apk) "); 13937 pw.print(ent.apk); 13938 } else { 13939 pw.print(",apk,"); 13940 pw.print(ent.apk); 13941 } 13942 } 13943 pw.println(); 13944 } 13945 } 13946 13947 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 13948 if (dumpState.onTitlePrinted()) 13949 pw.println(); 13950 if (!checkin) { 13951 pw.println("Features:"); 13952 } 13953 Iterator<String> it = mAvailableFeatures.keySet().iterator(); 13954 while (it.hasNext()) { 13955 String name = it.next(); 13956 if (!checkin) { 13957 pw.print(" "); 13958 } else { 13959 pw.print("feat,"); 13960 } 13961 pw.println(name); 13962 } 13963 } 13964 13965 if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) { 13966 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 13967 : "Activity Resolver Table:", " ", packageName, 13968 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 13969 dumpState.setTitlePrinted(true); 13970 } 13971 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 13972 : "Receiver Resolver Table:", " ", packageName, 13973 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 13974 dumpState.setTitlePrinted(true); 13975 } 13976 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 13977 : "Service Resolver Table:", " ", packageName, 13978 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 13979 dumpState.setTitlePrinted(true); 13980 } 13981 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 13982 : "Provider Resolver Table:", " ", packageName, 13983 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 13984 dumpState.setTitlePrinted(true); 13985 } 13986 } 13987 13988 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 13989 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 13990 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 13991 int user = mSettings.mPreferredActivities.keyAt(i); 13992 if (pir.dump(pw, 13993 dumpState.getTitlePrinted() 13994 ? "\nPreferred Activities User " + user + ":" 13995 : "Preferred Activities User " + user + ":", " ", 13996 packageName, true, false)) { 13997 dumpState.setTitlePrinted(true); 13998 } 13999 } 14000 } 14001 14002 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 14003 pw.flush(); 14004 FileOutputStream fout = new FileOutputStream(fd); 14005 BufferedOutputStream str = new BufferedOutputStream(fout); 14006 XmlSerializer serializer = new FastXmlSerializer(); 14007 try { 14008 serializer.setOutput(str, StandardCharsets.UTF_8.name()); 14009 serializer.startDocument(null, true); 14010 serializer.setFeature( 14011 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 14012 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 14013 serializer.endDocument(); 14014 serializer.flush(); 14015 } catch (IllegalArgumentException e) { 14016 pw.println("Failed writing: " + e); 14017 } catch (IllegalStateException e) { 14018 pw.println("Failed writing: " + e); 14019 } catch (IOException e) { 14020 pw.println("Failed writing: " + e); 14021 } 14022 } 14023 14024 if (!checkin && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)) { 14025 pw.println(); 14026 int count = mSettings.mPackages.size(); 14027 if (count == 0) { 14028 pw.println("No domain preferred apps!"); 14029 pw.println(); 14030 } else { 14031 final String prefix = " "; 14032 Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values(); 14033 if (allPackageSettings.size() == 0) { 14034 pw.println("No domain preferred apps!"); 14035 pw.println(); 14036 } else { 14037 pw.println("Domain preferred apps status:"); 14038 pw.println(); 14039 count = 0; 14040 for (PackageSetting ps : allPackageSettings) { 14041 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 14042 if (ivi == null || ivi.getPackageName() == null) continue; 14043 pw.println(prefix + "Package Name: " + ivi.getPackageName()); 14044 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 14045 pw.println(prefix + "Status: " + ivi.getStatusString()); 14046 pw.println(); 14047 count++; 14048 } 14049 if (count == 0) { 14050 pw.println(prefix + "No domain preferred app status!"); 14051 pw.println(); 14052 } 14053 for (int userId : sUserManager.getUserIds()) { 14054 pw.println("Domain preferred apps for User " + userId + ":"); 14055 pw.println(); 14056 count = 0; 14057 for (PackageSetting ps : allPackageSettings) { 14058 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 14059 if (ivi == null || ivi.getPackageName() == null) { 14060 continue; 14061 } 14062 final int status = ps.getDomainVerificationStatusForUser(userId); 14063 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 14064 continue; 14065 } 14066 pw.println(prefix + "Package Name: " + ivi.getPackageName()); 14067 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 14068 String statusStr = IntentFilterVerificationInfo. 14069 getStatusStringFromValue(status); 14070 pw.println(prefix + "Status: " + statusStr); 14071 pw.println(); 14072 count++; 14073 } 14074 if (count == 0) { 14075 pw.println(prefix + "No domain preferred apps!"); 14076 pw.println(); 14077 } 14078 } 14079 } 14080 } 14081 } 14082 14083 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 14084 mSettings.dumpPermissionsLPr(pw, packageName, dumpState); 14085 if (packageName == null) { 14086 for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) { 14087 if (iperm == 0) { 14088 if (dumpState.onTitlePrinted()) 14089 pw.println(); 14090 pw.println("AppOp Permissions:"); 14091 } 14092 pw.print(" AppOp Permission "); 14093 pw.print(mAppOpPermissionPackages.keyAt(iperm)); 14094 pw.println(":"); 14095 ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm); 14096 for (int ipkg=0; ipkg<pkgs.size(); ipkg++) { 14097 pw.print(" "); pw.println(pkgs.valueAt(ipkg)); 14098 } 14099 } 14100 } 14101 } 14102 14103 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 14104 boolean printedSomething = false; 14105 for (PackageParser.Provider p : mProviders.mProviders.values()) { 14106 if (packageName != null && !packageName.equals(p.info.packageName)) { 14107 continue; 14108 } 14109 if (!printedSomething) { 14110 if (dumpState.onTitlePrinted()) 14111 pw.println(); 14112 pw.println("Registered ContentProviders:"); 14113 printedSomething = true; 14114 } 14115 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 14116 pw.print(" "); pw.println(p.toString()); 14117 } 14118 printedSomething = false; 14119 for (Map.Entry<String, PackageParser.Provider> entry : 14120 mProvidersByAuthority.entrySet()) { 14121 PackageParser.Provider p = entry.getValue(); 14122 if (packageName != null && !packageName.equals(p.info.packageName)) { 14123 continue; 14124 } 14125 if (!printedSomething) { 14126 if (dumpState.onTitlePrinted()) 14127 pw.println(); 14128 pw.println("ContentProvider Authorities:"); 14129 printedSomething = true; 14130 } 14131 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 14132 pw.print(" "); pw.println(p.toString()); 14133 if (p.info != null && p.info.applicationInfo != null) { 14134 final String appInfo = p.info.applicationInfo.toString(); 14135 pw.print(" applicationInfo="); pw.println(appInfo); 14136 } 14137 } 14138 } 14139 14140 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 14141 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState); 14142 } 14143 14144 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 14145 mSettings.dumpPackagesLPr(pw, packageName, dumpState, checkin); 14146 } 14147 14148 if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 14149 mSettings.dumpSharedUsersLPr(pw, packageName, dumpState, checkin); 14150 } 14151 14152 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) { 14153 // XXX should handle packageName != null by dumping only install data that 14154 // the given package is involved with. 14155 if (dumpState.onTitlePrinted()) pw.println(); 14156 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120)); 14157 } 14158 14159 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 14160 if (dumpState.onTitlePrinted()) pw.println(); 14161 mSettings.dumpReadMessagesLPr(pw, dumpState); 14162 14163 pw.println(); 14164 pw.println("Package warning messages:"); 14165 BufferedReader in = null; 14166 String line = null; 14167 try { 14168 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 14169 while ((line = in.readLine()) != null) { 14170 if (line.contains("ignored: updated version")) continue; 14171 pw.println(line); 14172 } 14173 } catch (IOException ignored) { 14174 } finally { 14175 IoUtils.closeQuietly(in); 14176 } 14177 } 14178 14179 if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) { 14180 BufferedReader in = null; 14181 String line = null; 14182 try { 14183 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 14184 while ((line = in.readLine()) != null) { 14185 if (line.contains("ignored: updated version")) continue; 14186 pw.print("msg,"); 14187 pw.println(line); 14188 } 14189 } catch (IOException ignored) { 14190 } finally { 14191 IoUtils.closeQuietly(in); 14192 } 14193 } 14194 } 14195 } 14196 14197 // ------- apps on sdcard specific code ------- 14198 static final boolean DEBUG_SD_INSTALL = false; 14199 14200 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 14201 14202 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 14203 14204 private boolean mMediaMounted = false; 14205 14206 static String getEncryptKey() { 14207 try { 14208 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 14209 SD_ENCRYPTION_KEYSTORE_NAME); 14210 if (sdEncKey == null) { 14211 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 14212 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 14213 if (sdEncKey == null) { 14214 Slog.e(TAG, "Failed to create encryption keys"); 14215 return null; 14216 } 14217 } 14218 return sdEncKey; 14219 } catch (NoSuchAlgorithmException nsae) { 14220 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 14221 return null; 14222 } catch (IOException ioe) { 14223 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 14224 return null; 14225 } 14226 } 14227 14228 /* 14229 * Update media status on PackageManager. 14230 */ 14231 @Override 14232 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 14233 int callingUid = Binder.getCallingUid(); 14234 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 14235 throw new SecurityException("Media status can only be updated by the system"); 14236 } 14237 // reader; this apparently protects mMediaMounted, but should probably 14238 // be a different lock in that case. 14239 synchronized (mPackages) { 14240 Log.i(TAG, "Updating external media status from " 14241 + (mMediaMounted ? "mounted" : "unmounted") + " to " 14242 + (mediaStatus ? "mounted" : "unmounted")); 14243 if (DEBUG_SD_INSTALL) 14244 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 14245 + ", mMediaMounted=" + mMediaMounted); 14246 if (mediaStatus == mMediaMounted) { 14247 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 14248 : 0, -1); 14249 mHandler.sendMessage(msg); 14250 return; 14251 } 14252 mMediaMounted = mediaStatus; 14253 } 14254 // Queue up an async operation since the package installation may take a 14255 // little while. 14256 mHandler.post(new Runnable() { 14257 public void run() { 14258 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 14259 } 14260 }); 14261 } 14262 14263 /** 14264 * Called by MountService when the initial ASECs to scan are available. 14265 * Should block until all the ASEC containers are finished being scanned. 14266 */ 14267 public void scanAvailableAsecs() { 14268 updateExternalMediaStatusInner(true, false, false); 14269 if (mShouldRestoreconData) { 14270 SELinuxMMAC.setRestoreconDone(); 14271 mShouldRestoreconData = false; 14272 } 14273 } 14274 14275 /* 14276 * Collect information of applications on external media, map them against 14277 * existing containers and update information based on current mount status. 14278 * Please note that we always have to report status if reportStatus has been 14279 * set to true especially when unloading packages. 14280 */ 14281 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 14282 boolean externalStorage) { 14283 ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>(); 14284 int[] uidArr = EmptyArray.INT; 14285 14286 final String[] list = PackageHelper.getSecureContainerList(); 14287 if (ArrayUtils.isEmpty(list)) { 14288 Log.i(TAG, "No secure containers found"); 14289 } else { 14290 // Process list of secure containers and categorize them 14291 // as active or stale based on their package internal state. 14292 14293 // reader 14294 synchronized (mPackages) { 14295 for (String cid : list) { 14296 // Leave stages untouched for now; installer service owns them 14297 if (PackageInstallerService.isStageName(cid)) continue; 14298 14299 if (DEBUG_SD_INSTALL) 14300 Log.i(TAG, "Processing container " + cid); 14301 String pkgName = getAsecPackageName(cid); 14302 if (pkgName == null) { 14303 Slog.i(TAG, "Found stale container " + cid + " with no package name"); 14304 continue; 14305 } 14306 if (DEBUG_SD_INSTALL) 14307 Log.i(TAG, "Looking for pkg : " + pkgName); 14308 14309 final PackageSetting ps = mSettings.mPackages.get(pkgName); 14310 if (ps == null) { 14311 Slog.i(TAG, "Found stale container " + cid + " with no matching settings"); 14312 continue; 14313 } 14314 14315 /* 14316 * Skip packages that are not external if we're unmounting 14317 * external storage. 14318 */ 14319 if (externalStorage && !isMounted && !isExternal(ps)) { 14320 continue; 14321 } 14322 14323 final AsecInstallArgs args = new AsecInstallArgs(cid, 14324 getAppDexInstructionSets(ps), ps.isForwardLocked()); 14325 // The package status is changed only if the code path 14326 // matches between settings and the container id. 14327 if (ps.codePathString != null 14328 && ps.codePathString.startsWith(args.getCodePath())) { 14329 if (DEBUG_SD_INSTALL) { 14330 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 14331 + " at code path: " + ps.codePathString); 14332 } 14333 14334 // We do have a valid package installed on sdcard 14335 processCids.put(args, ps.codePathString); 14336 final int uid = ps.appId; 14337 if (uid != -1) { 14338 uidArr = ArrayUtils.appendInt(uidArr, uid); 14339 } 14340 } else { 14341 Slog.i(TAG, "Found stale container " + cid + ": expected codePath=" 14342 + ps.codePathString); 14343 } 14344 } 14345 } 14346 14347 Arrays.sort(uidArr); 14348 } 14349 14350 // Process packages with valid entries. 14351 if (isMounted) { 14352 if (DEBUG_SD_INSTALL) 14353 Log.i(TAG, "Loading packages"); 14354 loadMediaPackages(processCids, uidArr); 14355 startCleaningPackages(); 14356 mInstallerService.onSecureContainersAvailable(); 14357 } else { 14358 if (DEBUG_SD_INSTALL) 14359 Log.i(TAG, "Unloading packages"); 14360 unloadMediaPackages(processCids, uidArr, reportStatus); 14361 } 14362 } 14363 14364 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 14365 ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) { 14366 final int size = infos.size(); 14367 final String[] packageNames = new String[size]; 14368 final int[] packageUids = new int[size]; 14369 for (int i = 0; i < size; i++) { 14370 final ApplicationInfo info = infos.get(i); 14371 packageNames[i] = info.packageName; 14372 packageUids[i] = info.uid; 14373 } 14374 sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids, 14375 finishedReceiver); 14376 } 14377 14378 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 14379 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 14380 sendResourcesChangedBroadcast(mediaStatus, replacing, 14381 pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver); 14382 } 14383 14384 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 14385 String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 14386 int size = pkgList.length; 14387 if (size > 0) { 14388 // Send broadcasts here 14389 Bundle extras = new Bundle(); 14390 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 14391 if (uidArr != null) { 14392 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 14393 } 14394 if (replacing) { 14395 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 14396 } 14397 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 14398 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 14399 sendPackageBroadcast(action, null, extras, null, finishedReceiver, null); 14400 } 14401 } 14402 14403 /* 14404 * Look at potentially valid container ids from processCids If package 14405 * information doesn't match the one on record or package scanning fails, 14406 * the cid is added to list of removeCids. We currently don't delete stale 14407 * containers. 14408 */ 14409 private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr) { 14410 ArrayList<String> pkgList = new ArrayList<String>(); 14411 Set<AsecInstallArgs> keys = processCids.keySet(); 14412 14413 for (AsecInstallArgs args : keys) { 14414 String codePath = processCids.get(args); 14415 if (DEBUG_SD_INSTALL) 14416 Log.i(TAG, "Loading container : " + args.cid); 14417 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 14418 try { 14419 // Make sure there are no container errors first. 14420 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { 14421 Slog.e(TAG, "Failed to mount cid : " + args.cid 14422 + " when installing from sdcard"); 14423 continue; 14424 } 14425 // Check code path here. 14426 if (codePath == null || !codePath.startsWith(args.getCodePath())) { 14427 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() 14428 + " does not match one in settings " + codePath); 14429 continue; 14430 } 14431 // Parse package 14432 int parseFlags = mDefParseFlags; 14433 if (args.isExternalAsec()) { 14434 parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE; 14435 } 14436 if (args.isFwdLocked()) { 14437 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 14438 } 14439 14440 synchronized (mInstallLock) { 14441 PackageParser.Package pkg = null; 14442 try { 14443 pkg = scanPackageLI(new File(codePath), parseFlags, 0, 0, null); 14444 } catch (PackageManagerException e) { 14445 Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage()); 14446 } 14447 // Scan the package 14448 if (pkg != null) { 14449 /* 14450 * TODO why is the lock being held? doPostInstall is 14451 * called in other places without the lock. This needs 14452 * to be straightened out. 14453 */ 14454 // writer 14455 synchronized (mPackages) { 14456 retCode = PackageManager.INSTALL_SUCCEEDED; 14457 pkgList.add(pkg.packageName); 14458 // Post process args 14459 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 14460 pkg.applicationInfo.uid); 14461 } 14462 } else { 14463 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 14464 } 14465 } 14466 14467 } finally { 14468 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 14469 Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode); 14470 } 14471 } 14472 } 14473 // writer 14474 synchronized (mPackages) { 14475 // If the platform SDK has changed since the last time we booted, 14476 // we need to re-grant app permission to catch any new ones that 14477 // appear. This is really a hack, and means that apps can in some 14478 // cases get permissions that the user didn't initially explicitly 14479 // allow... it would be nice to have some better way to handle 14480 // this situation. 14481 final boolean regrantPermissions = mSettings.mExternalSdkPlatform != mSdkVersion; 14482 if (regrantPermissions) 14483 Slog.i(TAG, "Platform changed from " + mSettings.mExternalSdkPlatform + " to " 14484 + mSdkVersion + "; regranting permissions for external storage"); 14485 mSettings.mExternalSdkPlatform = mSdkVersion; 14486 14487 // Make sure group IDs have been assigned, and any permission 14488 // changes in other apps are accounted for 14489 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 14490 | (regrantPermissions 14491 ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL) 14492 : 0)); 14493 14494 mSettings.updateExternalDatabaseVersion(); 14495 14496 // can downgrade to reader 14497 // Persist settings 14498 mSettings.writeLPr(); 14499 } 14500 // Send a broadcast to let everyone know we are done processing 14501 if (pkgList.size() > 0) { 14502 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 14503 } 14504 } 14505 14506 /* 14507 * Utility method to unload a list of specified containers 14508 */ 14509 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 14510 // Just unmount all valid containers. 14511 for (AsecInstallArgs arg : cidArgs) { 14512 synchronized (mInstallLock) { 14513 arg.doPostDeleteLI(false); 14514 } 14515 } 14516 } 14517 14518 /* 14519 * Unload packages mounted on external media. This involves deleting package 14520 * data from internal structures, sending broadcasts about diabled packages, 14521 * gc'ing to free up references, unmounting all secure containers 14522 * corresponding to packages on external media, and posting a 14523 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 14524 * that we always have to post this message if status has been requested no 14525 * matter what. 14526 */ 14527 private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[], 14528 final boolean reportStatus) { 14529 if (DEBUG_SD_INSTALL) 14530 Log.i(TAG, "unloading media packages"); 14531 ArrayList<String> pkgList = new ArrayList<String>(); 14532 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 14533 final Set<AsecInstallArgs> keys = processCids.keySet(); 14534 for (AsecInstallArgs args : keys) { 14535 String pkgName = args.getPackageName(); 14536 if (DEBUG_SD_INSTALL) 14537 Log.i(TAG, "Trying to unload pkg : " + pkgName); 14538 // Delete package internally 14539 PackageRemovedInfo outInfo = new PackageRemovedInfo(); 14540 synchronized (mInstallLock) { 14541 boolean res = deletePackageLI(pkgName, null, false, null, null, 14542 PackageManager.DELETE_KEEP_DATA, outInfo, false); 14543 if (res) { 14544 pkgList.add(pkgName); 14545 } else { 14546 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 14547 failedList.add(args); 14548 } 14549 } 14550 } 14551 14552 // reader 14553 synchronized (mPackages) { 14554 // We didn't update the settings after removing each package; 14555 // write them now for all packages. 14556 mSettings.writeLPr(); 14557 } 14558 14559 // We have to absolutely send UPDATED_MEDIA_STATUS only 14560 // after confirming that all the receivers processed the ordered 14561 // broadcast when packages get disabled, force a gc to clean things up. 14562 // and unload all the containers. 14563 if (pkgList.size() > 0) { 14564 sendResourcesChangedBroadcast(false, false, pkgList, uidArr, 14565 new IIntentReceiver.Stub() { 14566 public void performReceive(Intent intent, int resultCode, String data, 14567 Bundle extras, boolean ordered, boolean sticky, 14568 int sendingUser) throws RemoteException { 14569 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 14570 reportStatus ? 1 : 0, 1, keys); 14571 mHandler.sendMessage(msg); 14572 } 14573 }); 14574 } else { 14575 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 14576 keys); 14577 mHandler.sendMessage(msg); 14578 } 14579 } 14580 14581 private void loadPrivatePackages(VolumeInfo vol) { 14582 final ArrayList<ApplicationInfo> loaded = new ArrayList<>(); 14583 final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE; 14584 synchronized (mInstallLock) { 14585 synchronized (mPackages) { 14586 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid); 14587 for (PackageSetting ps : packages) { 14588 final PackageParser.Package pkg; 14589 try { 14590 pkg = scanPackageLI(ps.codePath, parseFlags, 0, 0, null); 14591 loaded.add(pkg.applicationInfo); 14592 } catch (PackageManagerException e) { 14593 Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage()); 14594 } 14595 } 14596 14597 // TODO: regrant any permissions that changed based since original install 14598 14599 mSettings.writeLPr(); 14600 } 14601 } 14602 14603 Slog.d(TAG, "Loaded packages " + loaded); 14604 sendResourcesChangedBroadcast(true, false, loaded, null); 14605 } 14606 14607 private void unloadPrivatePackages(VolumeInfo vol) { 14608 final ArrayList<ApplicationInfo> unloaded = new ArrayList<>(); 14609 synchronized (mInstallLock) { 14610 synchronized (mPackages) { 14611 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid); 14612 for (PackageSetting ps : packages) { 14613 if (ps.pkg == null) continue; 14614 14615 final ApplicationInfo info = ps.pkg.applicationInfo; 14616 final PackageRemovedInfo outInfo = new PackageRemovedInfo(); 14617 if (deletePackageLI(ps.name, null, false, null, null, 14618 PackageManager.DELETE_KEEP_DATA, outInfo, false)) { 14619 unloaded.add(info); 14620 } else { 14621 Slog.w(TAG, "Failed to unload " + ps.codePath); 14622 } 14623 } 14624 14625 mSettings.writeLPr(); 14626 } 14627 } 14628 14629 Slog.d(TAG, "Unloaded packages " + unloaded); 14630 sendResourcesChangedBroadcast(false, false, unloaded, null); 14631 } 14632 14633 private void unfreezePackage(String packageName) { 14634 synchronized (mPackages) { 14635 final PackageSetting ps = mSettings.mPackages.get(packageName); 14636 if (ps != null) { 14637 ps.frozen = false; 14638 } 14639 } 14640 } 14641 14642 @Override 14643 public int movePackage(final String packageName, final String volumeUuid) { 14644 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 14645 14646 final int moveId = mNextMoveId.getAndIncrement(); 14647 try { 14648 movePackageInternal(packageName, volumeUuid, moveId); 14649 } catch (PackageManagerException e) { 14650 Slog.d(TAG, "Failed to move " + packageName, e); 14651 mMoveCallbacks.notifyStatusChanged(moveId, 14652 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 14653 } 14654 return moveId; 14655 } 14656 14657 private void movePackageInternal(final String packageName, final String volumeUuid, 14658 final int moveId) throws PackageManagerException { 14659 final UserHandle user = new UserHandle(UserHandle.getCallingUserId()); 14660 final StorageManager storage = mContext.getSystemService(StorageManager.class); 14661 final PackageManager pm = mContext.getPackageManager(); 14662 14663 final boolean currentAsec; 14664 final String currentVolumeUuid; 14665 final File codeFile; 14666 final String installerPackageName; 14667 final String packageAbiOverride; 14668 final int appId; 14669 final String seinfo; 14670 final String label; 14671 14672 // reader 14673 synchronized (mPackages) { 14674 final PackageParser.Package pkg = mPackages.get(packageName); 14675 final PackageSetting ps = mSettings.mPackages.get(packageName); 14676 if (pkg == null || ps == null) { 14677 throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package"); 14678 } 14679 14680 if (pkg.applicationInfo.isSystemApp()) { 14681 throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE, 14682 "Cannot move system application"); 14683 } 14684 14685 if (Objects.equals(ps.volumeUuid, volumeUuid)) { 14686 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 14687 "Package already moved to " + volumeUuid); 14688 } 14689 14690 final File probe = new File(pkg.codePath); 14691 final File probeOat = new File(probe, "oat"); 14692 if (!probe.isDirectory() || !probeOat.isDirectory()) { 14693 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 14694 "Move only supported for modern cluster style installs"); 14695 } 14696 14697 if (ps.frozen) { 14698 throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING, 14699 "Failed to move already frozen package"); 14700 } 14701 ps.frozen = true; 14702 14703 currentAsec = pkg.applicationInfo.isForwardLocked() 14704 || pkg.applicationInfo.isExternalAsec(); 14705 currentVolumeUuid = ps.volumeUuid; 14706 codeFile = new File(pkg.codePath); 14707 installerPackageName = ps.installerPackageName; 14708 packageAbiOverride = ps.cpuAbiOverrideString; 14709 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 14710 seinfo = pkg.applicationInfo.seinfo; 14711 label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo)); 14712 } 14713 14714 // Now that we're guarded by frozen state, kill app during move 14715 killApplication(packageName, appId, "move pkg"); 14716 14717 final Bundle extras = new Bundle(); 14718 extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName); 14719 extras.putString(Intent.EXTRA_TITLE, label); 14720 mMoveCallbacks.notifyCreated(moveId, extras); 14721 14722 int installFlags; 14723 final boolean moveCompleteApp; 14724 final File measurePath; 14725 14726 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) { 14727 installFlags = INSTALL_INTERNAL; 14728 moveCompleteApp = !currentAsec; 14729 measurePath = Environment.getDataAppDirectory(volumeUuid); 14730 } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) { 14731 installFlags = INSTALL_EXTERNAL; 14732 moveCompleteApp = false; 14733 measurePath = storage.getPrimaryPhysicalVolume().getPath(); 14734 } else { 14735 final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid); 14736 if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE 14737 || !volume.isMountedWritable()) { 14738 unfreezePackage(packageName); 14739 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 14740 "Move location not mounted private volume"); 14741 } 14742 14743 Preconditions.checkState(!currentAsec); 14744 14745 installFlags = INSTALL_INTERNAL; 14746 moveCompleteApp = true; 14747 measurePath = Environment.getDataAppDirectory(volumeUuid); 14748 } 14749 14750 final PackageStats stats = new PackageStats(null, -1); 14751 synchronized (mInstaller) { 14752 if (!getPackageSizeInfoLI(packageName, -1, stats)) { 14753 unfreezePackage(packageName); 14754 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 14755 "Failed to measure package size"); 14756 } 14757 } 14758 14759 Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size " + stats.dataSize); 14760 14761 final long startFreeBytes = measurePath.getFreeSpace(); 14762 final long sizeBytes; 14763 if (moveCompleteApp) { 14764 sizeBytes = stats.codeSize + stats.dataSize; 14765 } else { 14766 sizeBytes = stats.codeSize; 14767 } 14768 14769 if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) { 14770 unfreezePackage(packageName); 14771 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 14772 "Not enough free space to move"); 14773 } 14774 14775 mMoveCallbacks.notifyStatusChanged(moveId, 10); 14776 14777 final CountDownLatch installedLatch = new CountDownLatch(1); 14778 final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() { 14779 @Override 14780 public void onUserActionRequired(Intent intent) throws RemoteException { 14781 throw new IllegalStateException(); 14782 } 14783 14784 @Override 14785 public void onPackageInstalled(String basePackageName, int returnCode, String msg, 14786 Bundle extras) throws RemoteException { 14787 Slog.d(TAG, "Install result for move: " 14788 + PackageManager.installStatusToString(returnCode, msg)); 14789 14790 installedLatch.countDown(); 14791 14792 // Regardless of success or failure of the move operation, 14793 // always unfreeze the package 14794 unfreezePackage(packageName); 14795 14796 final int status = PackageManager.installStatusToPublicStatus(returnCode); 14797 switch (status) { 14798 case PackageInstaller.STATUS_SUCCESS: 14799 mMoveCallbacks.notifyStatusChanged(moveId, 14800 PackageManager.MOVE_SUCCEEDED); 14801 break; 14802 case PackageInstaller.STATUS_FAILURE_STORAGE: 14803 mMoveCallbacks.notifyStatusChanged(moveId, 14804 PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE); 14805 break; 14806 default: 14807 mMoveCallbacks.notifyStatusChanged(moveId, 14808 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 14809 break; 14810 } 14811 } 14812 }; 14813 14814 final MoveInfo move; 14815 if (moveCompleteApp) { 14816 // Kick off a thread to report progress estimates 14817 new Thread() { 14818 @Override 14819 public void run() { 14820 while (true) { 14821 try { 14822 if (installedLatch.await(1, TimeUnit.SECONDS)) { 14823 break; 14824 } 14825 } catch (InterruptedException ignored) { 14826 } 14827 14828 final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace(); 14829 final int progress = 10 + (int) MathUtils.constrain( 14830 ((deltaFreeBytes * 80) / sizeBytes), 0, 80); 14831 mMoveCallbacks.notifyStatusChanged(moveId, progress); 14832 } 14833 } 14834 }.start(); 14835 14836 final String dataAppName = codeFile.getName(); 14837 move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName, 14838 dataAppName, appId, seinfo); 14839 } else { 14840 move = null; 14841 } 14842 14843 installFlags |= PackageManager.INSTALL_REPLACE_EXISTING; 14844 14845 final Message msg = mHandler.obtainMessage(INIT_COPY); 14846 final OriginInfo origin = OriginInfo.fromExistingFile(codeFile); 14847 msg.obj = new InstallParams(origin, move, installObserver, installFlags, 14848 installerPackageName, volumeUuid, null, user, packageAbiOverride); 14849 mHandler.sendMessage(msg); 14850 } 14851 14852 @Override 14853 public int movePrimaryStorage(String volumeUuid) throws RemoteException { 14854 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 14855 14856 final int realMoveId = mNextMoveId.getAndIncrement(); 14857 final Bundle extras = new Bundle(); 14858 extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid); 14859 mMoveCallbacks.notifyCreated(realMoveId, extras); 14860 14861 final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() { 14862 @Override 14863 public void onCreated(int moveId, Bundle extras) { 14864 // Ignored 14865 } 14866 14867 @Override 14868 public void onStatusChanged(int moveId, int status, long estMillis) { 14869 mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis); 14870 } 14871 }; 14872 14873 final StorageManager storage = mContext.getSystemService(StorageManager.class); 14874 storage.setPrimaryStorageUuid(volumeUuid, callback); 14875 return realMoveId; 14876 } 14877 14878 @Override 14879 public int getMoveStatus(int moveId) { 14880 mContext.enforceCallingOrSelfPermission( 14881 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 14882 return mMoveCallbacks.mLastStatus.get(moveId); 14883 } 14884 14885 @Override 14886 public void registerMoveCallback(IPackageMoveObserver callback) { 14887 mContext.enforceCallingOrSelfPermission( 14888 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 14889 mMoveCallbacks.register(callback); 14890 } 14891 14892 @Override 14893 public void unregisterMoveCallback(IPackageMoveObserver callback) { 14894 mContext.enforceCallingOrSelfPermission( 14895 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 14896 mMoveCallbacks.unregister(callback); 14897 } 14898 14899 @Override 14900 public boolean setInstallLocation(int loc) { 14901 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 14902 null); 14903 if (getInstallLocation() == loc) { 14904 return true; 14905 } 14906 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 14907 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 14908 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 14909 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 14910 return true; 14911 } 14912 return false; 14913 } 14914 14915 @Override 14916 public int getInstallLocation() { 14917 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 14918 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 14919 PackageHelper.APP_INSTALL_AUTO); 14920 } 14921 14922 /** Called by UserManagerService */ 14923 void cleanUpUserLILPw(UserManagerService userManager, int userHandle) { 14924 mDirtyUsers.remove(userHandle); 14925 mSettings.removeUserLPw(userHandle); 14926 mPendingBroadcasts.remove(userHandle); 14927 if (mInstaller != null) { 14928 // Technically, we shouldn't be doing this with the package lock 14929 // held. However, this is very rare, and there is already so much 14930 // other disk I/O going on, that we'll let it slide for now. 14931 final StorageManager storage = StorageManager.from(mContext); 14932 final List<VolumeInfo> vols = storage.getVolumes(); 14933 for (VolumeInfo vol : vols) { 14934 if (vol.getType() == VolumeInfo.TYPE_PRIVATE && vol.isMountedWritable()) { 14935 final String volumeUuid = vol.getFsUuid(); 14936 Slog.d(TAG, "Removing user data on volume " + volumeUuid); 14937 mInstaller.removeUserDataDirs(volumeUuid, userHandle); 14938 } 14939 } 14940 } 14941 mUserNeedsBadging.delete(userHandle); 14942 removeUnusedPackagesLILPw(userManager, userHandle); 14943 } 14944 14945 /** 14946 * We're removing userHandle and would like to remove any downloaded packages 14947 * that are no longer in use by any other user. 14948 * @param userHandle the user being removed 14949 */ 14950 private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) { 14951 final boolean DEBUG_CLEAN_APKS = false; 14952 int [] users = userManager.getUserIdsLPr(); 14953 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 14954 while (psit.hasNext()) { 14955 PackageSetting ps = psit.next(); 14956 if (ps.pkg == null) { 14957 continue; 14958 } 14959 final String packageName = ps.pkg.packageName; 14960 // Skip over if system app 14961 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) { 14962 continue; 14963 } 14964 if (DEBUG_CLEAN_APKS) { 14965 Slog.i(TAG, "Checking package " + packageName); 14966 } 14967 boolean keep = false; 14968 for (int i = 0; i < users.length; i++) { 14969 if (users[i] != userHandle && ps.getInstalled(users[i])) { 14970 keep = true; 14971 if (DEBUG_CLEAN_APKS) { 14972 Slog.i(TAG, " Keeping package " + packageName + " for user " 14973 + users[i]); 14974 } 14975 break; 14976 } 14977 } 14978 if (!keep) { 14979 if (DEBUG_CLEAN_APKS) { 14980 Slog.i(TAG, " Removing package " + packageName); 14981 } 14982 mHandler.post(new Runnable() { 14983 public void run() { 14984 deletePackageX(packageName, userHandle, 0); 14985 } //end run 14986 }); 14987 } 14988 } 14989 } 14990 14991 /** Called by UserManagerService */ 14992 void createNewUserLILPw(int userHandle, File path) { 14993 if (mInstaller != null) { 14994 mInstaller.createUserConfig(userHandle); 14995 mSettings.createNewUserLILPw(this, mInstaller, userHandle, path); 14996 } 14997 } 14998 14999 void newUserCreatedLILPw(int userHandle) { 15000 // Adding a user requires updating runtime permissions for system apps. 15001 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL); 15002 } 15003 15004 @Override 15005 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 15006 mContext.enforceCallingOrSelfPermission( 15007 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 15008 "Only package verification agents can read the verifier device identity"); 15009 15010 synchronized (mPackages) { 15011 return mSettings.getVerifierDeviceIdentityLPw(); 15012 } 15013 } 15014 15015 @Override 15016 public void setPermissionEnforced(String permission, boolean enforced) { 15017 mContext.enforceCallingOrSelfPermission(GRANT_REVOKE_PERMISSIONS, null); 15018 if (READ_EXTERNAL_STORAGE.equals(permission)) { 15019 synchronized (mPackages) { 15020 if (mSettings.mReadExternalStorageEnforced == null 15021 || mSettings.mReadExternalStorageEnforced != enforced) { 15022 mSettings.mReadExternalStorageEnforced = enforced; 15023 mSettings.writeLPr(); 15024 } 15025 } 15026 // kill any non-foreground processes so we restart them and 15027 // grant/revoke the GID. 15028 final IActivityManager am = ActivityManagerNative.getDefault(); 15029 if (am != null) { 15030 final long token = Binder.clearCallingIdentity(); 15031 try { 15032 am.killProcessesBelowForeground("setPermissionEnforcement"); 15033 } catch (RemoteException e) { 15034 } finally { 15035 Binder.restoreCallingIdentity(token); 15036 } 15037 } 15038 } else { 15039 throw new IllegalArgumentException("No selective enforcement for " + permission); 15040 } 15041 } 15042 15043 @Override 15044 @Deprecated 15045 public boolean isPermissionEnforced(String permission) { 15046 return true; 15047 } 15048 15049 @Override 15050 public boolean isStorageLow() { 15051 final long token = Binder.clearCallingIdentity(); 15052 try { 15053 final DeviceStorageMonitorInternal 15054 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 15055 if (dsm != null) { 15056 return dsm.isMemoryLow(); 15057 } else { 15058 return false; 15059 } 15060 } finally { 15061 Binder.restoreCallingIdentity(token); 15062 } 15063 } 15064 15065 @Override 15066 public IPackageInstaller getPackageInstaller() { 15067 return mInstallerService; 15068 } 15069 15070 private boolean userNeedsBadging(int userId) { 15071 int index = mUserNeedsBadging.indexOfKey(userId); 15072 if (index < 0) { 15073 final UserInfo userInfo; 15074 final long token = Binder.clearCallingIdentity(); 15075 try { 15076 userInfo = sUserManager.getUserInfo(userId); 15077 } finally { 15078 Binder.restoreCallingIdentity(token); 15079 } 15080 final boolean b; 15081 if (userInfo != null && userInfo.isManagedProfile()) { 15082 b = true; 15083 } else { 15084 b = false; 15085 } 15086 mUserNeedsBadging.put(userId, b); 15087 return b; 15088 } 15089 return mUserNeedsBadging.valueAt(index); 15090 } 15091 15092 @Override 15093 public KeySet getKeySetByAlias(String packageName, String alias) { 15094 if (packageName == null || alias == null) { 15095 return null; 15096 } 15097 synchronized(mPackages) { 15098 final PackageParser.Package pkg = mPackages.get(packageName); 15099 if (pkg == null) { 15100 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 15101 throw new IllegalArgumentException("Unknown package: " + packageName); 15102 } 15103 KeySetManagerService ksms = mSettings.mKeySetManagerService; 15104 return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias)); 15105 } 15106 } 15107 15108 @Override 15109 public KeySet getSigningKeySet(String packageName) { 15110 if (packageName == null) { 15111 return null; 15112 } 15113 synchronized(mPackages) { 15114 final PackageParser.Package pkg = mPackages.get(packageName); 15115 if (pkg == null) { 15116 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 15117 throw new IllegalArgumentException("Unknown package: " + packageName); 15118 } 15119 if (pkg.applicationInfo.uid != Binder.getCallingUid() 15120 && Process.SYSTEM_UID != Binder.getCallingUid()) { 15121 throw new SecurityException("May not access signing KeySet of other apps."); 15122 } 15123 KeySetManagerService ksms = mSettings.mKeySetManagerService; 15124 return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName)); 15125 } 15126 } 15127 15128 @Override 15129 public boolean isPackageSignedByKeySet(String packageName, KeySet ks) { 15130 if (packageName == null || ks == null) { 15131 return false; 15132 } 15133 synchronized(mPackages) { 15134 final PackageParser.Package pkg = mPackages.get(packageName); 15135 if (pkg == null) { 15136 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 15137 throw new IllegalArgumentException("Unknown package: " + packageName); 15138 } 15139 IBinder ksh = ks.getToken(); 15140 if (ksh instanceof KeySetHandle) { 15141 KeySetManagerService ksms = mSettings.mKeySetManagerService; 15142 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh); 15143 } 15144 return false; 15145 } 15146 } 15147 15148 @Override 15149 public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) { 15150 if (packageName == null || ks == null) { 15151 return false; 15152 } 15153 synchronized(mPackages) { 15154 final PackageParser.Package pkg = mPackages.get(packageName); 15155 if (pkg == null) { 15156 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 15157 throw new IllegalArgumentException("Unknown package: " + packageName); 15158 } 15159 IBinder ksh = ks.getToken(); 15160 if (ksh instanceof KeySetHandle) { 15161 KeySetManagerService ksms = mSettings.mKeySetManagerService; 15162 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh); 15163 } 15164 return false; 15165 } 15166 } 15167 15168 public void getUsageStatsIfNoPackageUsageInfo() { 15169 if (!mPackageUsage.isHistoricalPackageUsageAvailable()) { 15170 UsageStatsManager usm = (UsageStatsManager) mContext.getSystemService(Context.USAGE_STATS_SERVICE); 15171 if (usm == null) { 15172 throw new IllegalStateException("UsageStatsManager must be initialized"); 15173 } 15174 long now = System.currentTimeMillis(); 15175 Map<String, UsageStats> stats = usm.queryAndAggregateUsageStats(now - mDexOptLRUThresholdInMills, now); 15176 for (Map.Entry<String, UsageStats> entry : stats.entrySet()) { 15177 String packageName = entry.getKey(); 15178 PackageParser.Package pkg = mPackages.get(packageName); 15179 if (pkg == null) { 15180 continue; 15181 } 15182 UsageStats usage = entry.getValue(); 15183 pkg.mLastPackageUsageTimeInMills = usage.getLastTimeUsed(); 15184 mPackageUsage.mIsHistoricalPackageUsageAvailable = true; 15185 } 15186 } 15187 } 15188 15189 /** 15190 * Check and throw if the given before/after packages would be considered a 15191 * downgrade. 15192 */ 15193 private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after) 15194 throws PackageManagerException { 15195 if (after.versionCode < before.mVersionCode) { 15196 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 15197 "Update version code " + after.versionCode + " is older than current " 15198 + before.mVersionCode); 15199 } else if (after.versionCode == before.mVersionCode) { 15200 if (after.baseRevisionCode < before.baseRevisionCode) { 15201 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 15202 "Update base revision code " + after.baseRevisionCode 15203 + " is older than current " + before.baseRevisionCode); 15204 } 15205 15206 if (!ArrayUtils.isEmpty(after.splitNames)) { 15207 for (int i = 0; i < after.splitNames.length; i++) { 15208 final String splitName = after.splitNames[i]; 15209 final int j = ArrayUtils.indexOf(before.splitNames, splitName); 15210 if (j != -1) { 15211 if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) { 15212 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 15213 "Update split " + splitName + " revision code " 15214 + after.splitRevisionCodes[i] + " is older than current " 15215 + before.splitRevisionCodes[j]); 15216 } 15217 } 15218 } 15219 } 15220 } 15221 } 15222 15223 private static class MoveCallbacks extends Handler { 15224 private static final int MSG_CREATED = 1; 15225 private static final int MSG_STATUS_CHANGED = 2; 15226 15227 private final RemoteCallbackList<IPackageMoveObserver> 15228 mCallbacks = new RemoteCallbackList<>(); 15229 15230 private final SparseIntArray mLastStatus = new SparseIntArray(); 15231 15232 public MoveCallbacks(Looper looper) { 15233 super(looper); 15234 } 15235 15236 public void register(IPackageMoveObserver callback) { 15237 mCallbacks.register(callback); 15238 } 15239 15240 public void unregister(IPackageMoveObserver callback) { 15241 mCallbacks.unregister(callback); 15242 } 15243 15244 @Override 15245 public void handleMessage(Message msg) { 15246 final SomeArgs args = (SomeArgs) msg.obj; 15247 final int n = mCallbacks.beginBroadcast(); 15248 for (int i = 0; i < n; i++) { 15249 final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i); 15250 try { 15251 invokeCallback(callback, msg.what, args); 15252 } catch (RemoteException ignored) { 15253 } 15254 } 15255 mCallbacks.finishBroadcast(); 15256 args.recycle(); 15257 } 15258 15259 private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args) 15260 throws RemoteException { 15261 switch (what) { 15262 case MSG_CREATED: { 15263 callback.onCreated(args.argi1, (Bundle) args.arg2); 15264 break; 15265 } 15266 case MSG_STATUS_CHANGED: { 15267 callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3); 15268 break; 15269 } 15270 } 15271 } 15272 15273 private void notifyCreated(int moveId, Bundle extras) { 15274 Slog.v(TAG, "Move " + moveId + " created " + extras.toString()); 15275 15276 final SomeArgs args = SomeArgs.obtain(); 15277 args.argi1 = moveId; 15278 args.arg2 = extras; 15279 obtainMessage(MSG_CREATED, args).sendToTarget(); 15280 } 15281 15282 private void notifyStatusChanged(int moveId, int status) { 15283 notifyStatusChanged(moveId, status, -1); 15284 } 15285 15286 private void notifyStatusChanged(int moveId, int status, long estMillis) { 15287 Slog.v(TAG, "Move " + moveId + " status " + status); 15288 15289 final SomeArgs args = SomeArgs.obtain(); 15290 args.argi1 = moveId; 15291 args.argi2 = status; 15292 args.arg3 = estMillis; 15293 obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget(); 15294 15295 synchronized (mLastStatus) { 15296 mLastStatus.put(moveId, status); 15297 } 15298 } 15299 } 15300} 15301